@a-company/paradigm 5.37.0 → 5.37.1

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 (194) hide show
  1. package/dist/{accept-orchestration-36AP7HTX.js → accept-orchestration-SBZVK3H4.js} +1 -1
  2. package/dist/{add-FGKNJS3F.js → add-P76GEMGF.js} +1 -1
  3. package/dist/{agent-E7LDKJ4O.js → agent-X6I2YWOB.js} +1 -1
  4. package/dist/{agent-loader-2HXKVL6J.js → agent-loader-RIVI6QPP.js} +1 -1
  5. package/dist/{agent-loader-XS6LIMUG.js → agent-loader-RJRVO5GQ.js} +1 -1
  6. package/dist/{agent-state-L7LCPRC3.js → agent-state-KSQ3S7OB.js} +1 -1
  7. package/dist/{agents-suggest-Y5D6AALG.js → agents-suggest-HYTFMQD3.js} +1 -1
  8. package/dist/{aggregate-OZJRRAQR.js → aggregate-W66DM3GA.js} +1 -1
  9. package/dist/{ambient-4NSPAQDJ.js → ambient-GJAEXF7B.js} +4 -4
  10. package/dist/{assess-AMPVSWK7.js → assess-UFPYEJKP.js} +1 -1
  11. package/dist/{auto-A7VUHCUC.js → auto-RHJXOZFL.js} +1 -1
  12. package/dist/{beacon-YBLUUTYY.js → beacon-5QVYV5DF.js} +1 -1
  13. package/dist/{calibration-FQ4YVOE4.js → calibration-OLJYB5HN.js} +1 -1
  14. package/dist/{check-46QL3KMQ.js → check-THVGY4R5.js} +1 -1
  15. package/dist/{chunk-EMMMBAID.js → chunk-3KVVC4WV.js} +1 -1
  16. package/dist/{chunk-3QMRDN65.js → chunk-4Q7XYPL4.js} +2 -2
  17. package/dist/{chunk-3OMJI5TT.js → chunk-4SCKMGTB.js} +2 -2
  18. package/dist/chunk-5TAVYPOV.js +2 -0
  19. package/dist/{chunk-6PP2RPIZ.js → chunk-74SGKSRQ.js} +2 -2
  20. package/dist/{chunk-RN35IVA2.js → chunk-BV5PRPLB.js} +1 -1
  21. package/dist/{chunk-YG5G5GEQ.js → chunk-CMCQHU46.js} +13 -13
  22. package/dist/{chunk-JIF7OSGH.js → chunk-CVPKQ3JH.js} +1 -1
  23. package/dist/{chunk-RLJ5K3J5.js → chunk-D6ZXAI26.js} +1 -1
  24. package/dist/chunk-EK4ZRIFJ.js +3 -0
  25. package/dist/{chunk-X54WXWCX.js → chunk-FILLU77P.js} +5 -5
  26. package/dist/{chunk-7PB7AXQE.js → chunk-J6KWGCHN.js} +1 -1
  27. package/dist/{chunk-BCOPNVPY.js → chunk-JOHAOLEC.js} +2 -2
  28. package/dist/{chunk-JUOOVKK6.js → chunk-KFNHCQ4R.js} +1 -1
  29. package/dist/{chunk-77WX6HGV.js → chunk-LBQBWIEX.js} +1 -1
  30. package/dist/chunk-MBPLJKE5.js +3 -0
  31. package/dist/{chunk-W6WVJLHO.js → chunk-ODVKPZZ4.js} +1 -1
  32. package/dist/{chunk-5YHR77AL.js → chunk-ORDKEGII.js} +1 -1
  33. package/dist/chunk-QGZRM6ZB.js +2 -0
  34. package/dist/chunk-QO7YPQXC.js +2 -0
  35. package/dist/{chunk-DG3VCY43.js → chunk-SUU6M4JH.js} +1 -1
  36. package/dist/{chunk-XNB4TZTD.js → chunk-UNHTQLYO.js} +1 -1
  37. package/dist/chunk-UPFCBVXY.js +3 -0
  38. package/dist/{chunk-6QKCUEEY.js → chunk-VCKKJDLP.js} +1 -1
  39. package/dist/{chunk-4W5TBL3O.js → chunk-VG7FN2TU.js} +1 -1
  40. package/dist/{chunk-7YTAA6XA.js → chunk-WS2N27RX.js} +1 -1
  41. package/dist/{chunk-7SGNNVE5.js → chunk-X3U3IGYT.js} +2 -2
  42. package/dist/{chunk-IW5K3RNR.js → chunk-ZUAUFZRJ.js} +1 -1
  43. package/dist/{claude-OX54QSLC.js → claude-4LR3LJQZ.js} +1 -1
  44. package/dist/{claude-cli-FHLJQVJC.js → claude-cli-UP6HGH7C.js} +1 -1
  45. package/dist/{claude-code-GVGU3A3B.js → claude-code-RLJ4GX77.js} +1 -1
  46. package/dist/{claude-code-teams-ZRHPTGPP.js → claude-code-teams-R37HJY3Y.js} +1 -1
  47. package/dist/{compliance-PHSPVYK2.js → compliance-BPGQMQAX.js} +3 -3
  48. package/dist/{compliance-health-HCZTJDN7.js → compliance-health-JNP3P35P.js} +1 -1
  49. package/dist/{conductor-LYBMM66Z.js → conductor-Y5IXELTL.js} +1 -1
  50. package/dist/{config-schema-URJW6UZH.js → config-schema-GUQY2QN7.js} +1 -1
  51. package/dist/{constellation-PX3ZKMWQ.js → constellation-CG7C4WFE.js} +1 -1
  52. package/dist/{context-audit-APFKELFT.js → context-audit-XRPT3OU2.js} +2 -2
  53. package/dist/{cost-B5SAHPOJ.js → cost-IDNVMAEV.js} +1 -1
  54. package/dist/{cost-MMWUDGZC.js → cost-PK4KIF7R.js} +1 -1
  55. package/dist/{cursor-cli-Q2HLQ5TE.js → cursor-cli-QKF7Z6M2.js} +1 -1
  56. package/dist/{cursorrules-3BW6K6D5.js → cursorrules-U5O4G5T4.js} +1 -1
  57. package/dist/{decision-loader-4KMQVAXZ.js → decision-loader-2XPZE4EZ.js} +1 -1
  58. package/dist/{delete-7PQZUERZ.js → delete-P5VULXR4.js} +1 -1
  59. package/dist/{diff-F2HUO2H3.js → diff-JVEYCXUC.js} +1 -1
  60. package/dist/{discipline-ARFFIXQL.js → discipline-H7LDI6NT.js} +1 -1
  61. package/dist/{dist-MRZDZ5SX.js → dist-3ZCH25SG.js} +1 -1
  62. package/dist/{dist-KGRCLBJP-R5CCPPXN.js → dist-KGRCLBJP-2QAPFYNF.js} +1 -1
  63. package/dist/{dist-YUXXIXB3.js → dist-QBTQW4ZW.js} +1 -1
  64. package/dist/{dist-OKM6BXTH.js → dist-VGFSP3XM.js} +1 -1
  65. package/dist/{dist-VWC6FA46.js → dist-VXCZWVVJ.js} +1 -1
  66. package/dist/{dist-5IUWRFG6.js → dist-W3XCATBJ.js} +1 -1
  67. package/dist/{docs-6WOQILZS.js → docs-EDQ2STFK.js} +1 -1
  68. package/dist/{docs-BI2DO7B2.js → docs-USDAF26F.js} +2 -2
  69. package/dist/doctor-G37LCXG5.js +2 -0
  70. package/dist/{drift-6QPDKKUO.js → drift-ILZE5BFJ.js} +1 -1
  71. package/dist/{echo-3JJDKCNF.js → echo-UPTQUEDU.js} +1 -1
  72. package/dist/{edit-PLCGL5OV.js → edit-GUU3HBVW.js} +1 -1
  73. package/dist/{enforcement-IWABOHMY.js → enforcement-46XWPNSA.js} +1 -1
  74. package/dist/{enforcement-5MHSQAXE.js → enforcement-BEGPQIUN.js} +1 -1
  75. package/dist/{event-5J3GBWKT.js → event-Y3VXC2RV.js} +1 -1
  76. package/dist/{explain-files-LPHTJL4N.js → explain-files-3GPZUETV.js} +1 -1
  77. package/dist/{export-NXUFTFPW.js → export-CV5KCTPS.js} +1 -1
  78. package/dist/{flow-IT2IVXXT.js → flow-POQP27WA.js} +1 -1
  79. package/dist/{gap-narrator-DVXPWNFN.js → gap-narrator-NTXLUI7I.js} +1 -1
  80. package/dist/{global-J2VTYKCC.js → global-C44FW4G2.js} +1 -1
  81. package/dist/{graduate-N2HF4JT6.js → graduate-3BBSC27A.js} +1 -1
  82. package/dist/graph-CNDE5TAT.js +2 -0
  83. package/dist/{graph-server-TBHHBFOM.js → graph-server-COZR5C3Z.js} +1 -1
  84. package/dist/{habits-JTMWGVPH.js → habits-BX2IRSUI.js} +3 -3
  85. package/dist/{history-FHS7EC3Z.js → history-UW454SDP.js} +1 -1
  86. package/dist/{hooks-BL6CXRVK.js → hooks-BNWRGACA.js} +1 -1
  87. package/dist/index.js +5 -5
  88. package/dist/init-EHVSM7YY.js +2 -0
  89. package/dist/{integrity-UBMZCB77.js → integrity-UYDOOJDP.js} +1 -1
  90. package/dist/{integrity-checker-VSR3ITBL.js → integrity-checker-DHGMZQDG.js} +1 -1
  91. package/dist/journal-loader-GLH7XFTK.js +2 -0
  92. package/dist/{lint-KQQ2RMSJ.js → lint-IGKE6UPS.js} +1 -1
  93. package/dist/{list-37UCWCOQ.js → list-5IUGP3ZB.js} +1 -1
  94. package/dist/{list-6WY4CFUR.js → list-YKIQNKGB.js} +1 -1
  95. package/dist/lore-loader-RVQI5GXL.js +2 -0
  96. package/dist/{lore-loader-PBUDKXAJ.js → lore-loader-XY5MZRR2.js} +1 -1
  97. package/dist/{lore-server-A3KKZLSY.js → lore-server-FC2GMDLT.js} +1 -1
  98. package/dist/{manual-HKI6OXB4.js → manual-RXSPSFLL.js} +1 -1
  99. package/dist/mcp.js +1 -1
  100. package/dist/{migrate-W3KCXLDS.js → migrate-YQG2FG3J.js} +2 -2
  101. package/dist/{migrate-assessments-D2TOBJ5V.js → migrate-assessments-GEI5WMI2.js} +1 -1
  102. package/dist/{model-discovery-TWX4A4YD.js → model-discovery-HMB3YI4L.js} +1 -1
  103. package/dist/{nomination-engine-A24774W4.js → nomination-engine-KNSOAT4W.js} +1 -1
  104. package/dist/{notebook-LXJ2LHUA.js → notebook-PE3JSYZI.js} +1 -1
  105. package/dist/notebook-loader-CENTDDUJ.js +2 -0
  106. package/dist/{orchestrate-WFCNV2II.js → orchestrate-RCAMBOIB.js} +1 -1
  107. package/dist/{peers-7TPZTKH7.js → peers-P2KXU7ZK.js} +1 -1
  108. package/dist/{persona-UGTCFEGT.js → persona-STQWZH5P.js} +1 -1
  109. package/dist/{pipeline-7PZ6ILWX.js → pipeline-MZUITRVN.js} +1 -1
  110. package/dist/{platform-server-YIBX4YDJ.js → platform-server-DNAMH4YI.js} +2 -2
  111. package/dist/{plugin-update-checker-2EM4K45U.js → plugin-update-checker-M7PW434O.js} +1 -1
  112. package/dist/{portal-check-YSDJRZUR.js → portal-check-Z3OCQEQR.js} +1 -1
  113. package/dist/{portal-compliance-OBPK2IR5.js → portal-compliance-4MG5F2GI.js} +1 -1
  114. package/dist/{probe-WKXR3IN4.js → probe-B22G2JKF.js} +1 -1
  115. package/dist/{project-type-MRBJAKC7.js → project-type-EUCFKEAZ.js} +1 -1
  116. package/dist/{promote-VHBA56KW.js → promote-NJQDZBZA.js} +2 -2
  117. package/dist/{providers-RX7SBLHZ.js → providers-AWA7WLLM.js} +1 -1
  118. package/dist/{quiz-3SQNPRJ3.js → quiz-FE5UGAY2.js} +1 -1
  119. package/dist/{record-7QJPZZP7.js → record-YXPB34MY.js} +1 -1
  120. package/dist/{registry-LR5QACRK.js → registry-KOOKFUWD.js} +2 -2
  121. package/dist/reindex-O3WUCEE2.js +2 -0
  122. package/dist/{remember-SFGBTTEE.js → remember-MJRNTXYS.js} +1 -1
  123. package/dist/{retag-GFXUYP7S.js → retag-N5XF3KXP.js} +1 -1
  124. package/dist/{review-6KKZWV3A.js → review-6UAH6V3R.js} +1 -1
  125. package/dist/{review-GEBSYOZB.js → review-77QI6VOC.js} +1 -1
  126. package/dist/{ripple-4F5ZCXS4.js → ripple-ZGDITCGB.js} +1 -1
  127. package/dist/{roster-RI3UC2YI.js → roster-HV5KYUOI.js} +1 -1
  128. package/dist/{scaffold-WA4L2K7J.js → scaffold-D57JXPCC.js} +1 -1
  129. package/dist/{scopes-commands-5FFIUDRC.js → scopes-commands-NSPERZWV.js} +1 -1
  130. package/dist/{sentinel-37ZEEWT7.js → sentinel-HYAZ3CO5.js} +2 -2
  131. package/dist/{sentinel-bridge-EZGFRVFH.js → sentinel-bridge-VR357PKL.js} +1 -1
  132. package/dist/{serve-2BXDL35A.js → serve-L52ZUTU6.js} +2 -2
  133. package/dist/{serve-5JME5QEM.js → serve-OY6XYL7F.js} +2 -2
  134. package/dist/{serve-2LSTQFFQ.js → serve-U47GULB6.js} +2 -2
  135. package/dist/{server-XLHIYDTZ.js → server-2MNROHF6.js} +1 -1
  136. package/dist/{server-AIXFROYL.js → server-4YNUIK4W.js} +1 -1
  137. package/dist/session-tracker-D2CH7RJF.js +2 -0
  138. package/dist/{session-work-log-6GKGUQ5C.js → session-work-log-BX434ZLK.js} +1 -1
  139. package/dist/{session-work-log-UYMIWWOX.js → session-work-log-NQA7WJEC.js} +1 -1
  140. package/dist/{setup-ZM4JFV5D.js → setup-3F5IK7MO.js} +2 -2
  141. package/dist/{setup-F2N4LUR7.js → setup-KPIMRZ4Q.js} +1 -1
  142. package/dist/{shift-DDYVQJ75.js → shift-RRNL6E4O.js} +3 -3
  143. package/dist/{show-RFOIR2GQ.js → show-BOAVWZPZ.js} +1 -1
  144. package/dist/{show-CZLVYLM5.js → show-PJ5LFLIL.js} +1 -1
  145. package/dist/{snapshot-6N564OUJ.js → snapshot-L2G56RPL.js} +1 -1
  146. package/dist/{spawn-HYARN3RL.js → spawn-M5BAV252.js} +1 -1
  147. package/dist/{status-WBJ6D7BD.js → status-77M3SDIF.js} +1 -1
  148. package/dist/{status-CUG3PKGC.js → status-A37ECYNJ.js} +1 -1
  149. package/dist/{summary-2AM4QVPW.js → summary-LXLHFRN7.js} +1 -1
  150. package/dist/{sweep-WHDT7ENV.js → sweep-HU74OPVW.js} +1 -1
  151. package/dist/{switch-HBGIFNF6.js → switch-CTW4PDGI.js} +1 -1
  152. package/dist/{symphony-CWKKMFAS.js → symphony-7INZR43F.js} +5 -5
  153. package/dist/{symphony-VTHVTE57.js → symphony-G6IENE4K.js} +1 -1
  154. package/dist/{symphony-loader-RYFZOQJS.js → symphony-loader-VA4UREOM.js} +1 -1
  155. package/dist/{symphony-peers-LWBUQ3T4.js → symphony-peers-U4KHMKGI.js} +1 -1
  156. package/dist/{symphony-peers-ISJPKX7W.js → symphony-peers-X5NGWXFP.js} +1 -1
  157. package/dist/{symphony-relay-L3BY6RGM.js → symphony-relay-2RHG25Z4.js} +1 -1
  158. package/dist/{sync-WIFD7UCL.js → sync-DLUBV5HQ.js} +1 -1
  159. package/dist/{sync-llms-MZ3RQWFX.js → sync-llms-7CAI74QL.js} +1 -1
  160. package/dist/{task-loader-EU7JLTR3.js → task-loader-NZFDTUQ5.js} +1 -1
  161. package/dist/{team-C3PWO7XL.js → team-NSP6PMPS.js} +1 -1
  162. package/dist/{test-6MUL4EXS.js → test-BQJMS4Y2.js} +1 -1
  163. package/dist/{thread-K6UHDIUW.js → thread-HFXK65D4.js} +1 -1
  164. package/dist/{timeline-S26CQWHT.js → timeline-K3ZFKJ3R.js} +1 -1
  165. package/dist/tools-NNPANZRA.js +2 -0
  166. package/dist/{triage-YF6WYZY4.js → triage-FCWOZASE.js} +1 -1
  167. package/dist/{tutorial-UEBX7Z2G.js → tutorial-UC6YQMNN.js} +1 -1
  168. package/dist/{university-UMT7PAKE.js → university-FJ7OCOA3.js} +1 -1
  169. package/dist/{upgrade-USW7YJEX.js → upgrade-GX56QE3C.js} +1 -1
  170. package/dist/{validate-VZGBVTPM.js → validate-C6SMKGYD.js} +1 -1
  171. package/dist/{validate-2PZTNYSS.js → validate-LSCDOLBO.js} +1 -1
  172. package/dist/{validate-KW3YFGTV.js → validate-VZXTJHGO.js} +1 -1
  173. package/dist/{watch-KQU3S7KE.js → watch-PZCCUP6K.js} +1 -1
  174. package/dist/{watch-HL3ZOALL.js → watch-YCODNIET.js} +1 -1
  175. package/dist/{wisdom-UU7HOE3M.js → wisdom-XZ3QKPNP.js} +1 -1
  176. package/dist/{work-log-loader-J27XSFCE.js → work-log-loader-DL5GZ2BQ.js} +1 -1
  177. package/dist/workspace-MKSQN7B2.js +2 -0
  178. package/package.json +1 -1
  179. package/dist/chunk-BRHQJLTG.js +0 -2
  180. package/dist/chunk-DSYEGRQ2.js +0 -3
  181. package/dist/chunk-F5BSUC2L.js +0 -3
  182. package/dist/chunk-NFQLONFY.js +0 -3
  183. package/dist/chunk-OVDYPOHR.js +0 -2
  184. package/dist/chunk-XHJ27CER.js +0 -2
  185. package/dist/doctor-JLTCBMS4.js +0 -2
  186. package/dist/graph-VLMP6DW2.js +0 -2
  187. package/dist/init-ZS7RAR7L.js +0 -2
  188. package/dist/journal-loader-EELDB4P2.js +0 -2
  189. package/dist/lore-loader-CP5RUJ4A.js +0 -2
  190. package/dist/notebook-loader-CF52PNZC.js +0 -2
  191. package/dist/reindex-F7EV3Z34.js +0 -2
  192. package/dist/session-tracker-VSFRNFRL.js +0 -2
  193. package/dist/tools-4WKLLDFU.js +0 -2
  194. package/dist/workspace-CE6LNXVI.js +0 -2
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$1,b as b$3}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$2,n as n$1,c as c$1,d as d$4,q as q$2,p,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$6,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-3QMRDN65.js';import {o as o$2,A,y,x,f as f$4,r as r$1}from'./chunk-KLBH26PA.js';import {d as d$6,b as b$6,a as a$5}from'./chunk-JNSJVCTU.js';import {g as g$5,d as d$3,a as a$3}from'./chunk-Q2J542ST.js';import {i as i$4}from'./chunk-XROULIQN.js';import {n as n$3,j as j$4,P,O,K,Q as Q$1,L,I,J as J$1,D as D$1,H,m as m$2,l as l$2,E as E$2,v as v$2,N,q as q$3,C as C$1,S,o as o$3,z as z$2,t as t$2,B as B$1,s as s$2}from'./chunk-IW5K3RNR.js';import {f,g as g$2,e as e$1,q as q$1,t,o,v as v$1,i,m,V,h,k,l,j as j$2,n as n$2,u,r,ka as ka$1,s,la as la$1,F,R,_,x as x$1,E as E$1,D,G,w,C,B,A as A$1,z as z$1,y as y$1,U,Z,T,Y,X,W,O as O$1,I as I$1,K as K$1,M as M$1,L as L$1,P as P$1,N as N$1,J as J$2,H as H$1,S as S$1,Q as Q$2,a as a$9,d as d$a,c as c$4,$,aa as aa$1,ia as ia$1,ha as ha$1,ba as ba$1,fa as fa$1,ca as ca$1,da as da$1,ea as ea$1,ja as ja$1,ga as ga$1,b as b$b}from'./chunk-X54WXWCX.js';import {j,a as a$2,i as i$1,b as b$4,h as h$2,g as g$4,c,d as d$2}from'./chunk-W6WVJLHO.js';import {z,f as f$2,p as p$1,h as h$3,b as b$8,d as d$8,e as e$5,i as i$3,y as y$2,l as l$3,c as c$5}from'./chunk-6PP2RPIZ.js';import {j as j$1,d as d$1,e as e$2,f as f$1,g as g$3,h as h$1}from'./chunk-NFQLONFY.js';import {b as b$1,a}from'./chunk-F5BSUC2L.js';import {n,b as b$a}from'./chunk-3OMJI5TT.js';import {f as f$3,b as b$7,e as e$4,d as d$7,a as a$7,c as c$2}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$5,d as d$5,a as a$4}from'./chunk-OVDYPOHR.js';import {g,d as d$9,c as c$3,b as b$9,a as a$8}from'./chunk-4W5TBL3O.js';import {b,d,f as f$5}from'./chunk-XHJ27CER.js';import*as E from'fs';import*as q from'path';import*as be from'js-yaml';import*as Fo from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {execSync}from'child_process';var Pt,Cs,Rs=b(()=>{Pt={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},Cs=new Set(["tool-called","context-checked"]);});var ca={};d(ca,{getAllStates:()=>js,getConfig:()=>tt,getState:()=>Rn,incrementFailure:()=>aa,invalidateGraduationCache:()=>Ud,isGraduated:()=>Wd,loadGraduation:()=>Le,markNeverGraduate:()=>Jd,saveGraduation:()=>Cn,setTier:()=>oa});function ra(t){return q.join(t,".paradigm","graduation.yaml")}function Le(t){let e=q.resolve(t);if(jt&&Sn===e&&Date.now()-_n<Gd)return jt;let s=ra(e),n;if(E.existsSync(s))try{let i=E.readFileSync(s,"utf8");n=be.load(i);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),jt=n,Sn=e,_n=Date.now(),n}function Cn(t,e){let s=q.resolve(t),n=ra(s),i=q.dirname(n);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=be.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});E.writeFileSync(n,r,"utf8"),jt=e,Sn=s,_n=Date.now();}function tt(t){let e=Le(t);return {...Pt,...e.config,thresholds:{...Pt.thresholds,...e.config?.thresholds},demotion:{...Pt.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??Pt.neverGraduate}}function Ps(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Rn(t,e){let n=Le(t).states[e];return n?{...Ps(e),...n,habitId:e}:Ps(e)}function js(t){let e=Le(t),s={};for(let[n,i]of Object.entries(e.states))s[n]={...Ps(n),...i,habitId:n};return s}function Wd(t,e){return Rn(t,e).tier==="hook"}function oa(t,e,s,n){let i=Le(t),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Cn(t,i);}function Jd(t,e){let s=Le(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Cn(t,s);}function aa(t,e){let s=Le(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Cn(t,s),n}function Ud(){jt=null,Sn=null,_n=0;}var jt,Sn,_n,Gd,Pn=b(()=>{Rs();jt=null,Sn=null,_n=0,Gd=3e4;});b$1();b$1();var Zc=30*1e3,ds=new Map,ps=".paradigm/wisdom";async function Br(t){let e=q.resolve(t),s=ds.get(e);if(s&&Date.now()-s.loadedAt<Zc)return s.context;let n=await el(e);return ds.set(e,{context:n,loadedAt:Date.now()}),n}async function el(t){let e=q.join(t,ps),s=E.existsSync(e),[n,i,r,o]=s?await Promise.all([tl(e),nl(e),sl(e),il(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d$1(),c=e$2(),l=f$1();}catch{}let d=new Set(i.map(f=>f.id)),u=i.map(f=>({...f,scope:"project"}));for(let f of a)d.has(f.id)||u.push({...f,scope:"global"});let g=new Set(o.map(f=>f.id)),p=o.map(f=>({...f,scope:"project"}));for(let f of c)g.has(f.id)||p.push({...f,scope:"global"});let m=n;if(l&&!n)m=l;else if(l&&n){let f={...n.by_symbol};if(l.by_symbol)for(let[y,b]of Object.entries(l.by_symbol))f[y]||(f[y]=b);m={...n,by_symbol:f,global:{...l.global,...n.global}};}return {preferences:m,antipatterns:u,decisions:p,expertise:r}}function Fe(t){let e=q.resolve(t);ds.delete(e);}async function tl(t){let e=q.join(t,"preferences.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:s}),null}}async function nl(t){let e=q.join(t,"antipatterns.yaml");if(!E.existsSync(e))return [];try{let s=E.readFileSync(e,"utf8");return be.load(s).antipatterns||[]}catch(s){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:s}),[]}}async function sl(t){let e=q.join(t,"expertise.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:s}),null}}async function il(t){let e=q.join(t,"decisions");if(!E.existsSync(e))return [];let s=[];try{let n=E.readdirSync(e);for(let i of n){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=q.join(e,i);try{let o=E.readFileSync(r,"utf8"),a=be.load(o);s.push(a);}catch(o){a.component("#wisdom-loader").error(`Error parsing ${i}`,{error:o});}}}catch(n){a.component("#wisdom-loader").error("Error reading decisions directory",{error:n});}return s.sort((n,i)=>n.id.localeCompare(i.id)),s}function zr(t,e){return e.map(s=>rl(t,s))}function rl(t,e){let s=t.preferences?.by_symbol?.[e]||null,n=t.antipatterns.filter(o=>o.symbols.some(a=>a===e||en(e,a))),i=t.decisions.filter(o=>o.symbols.some(a=>a===e||en(e,a))),r=t.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||en(e,a)))||[];return {symbol:e,preferences:s,antipatterns:n,decisions:i,experts:r}}function Yr(t,e){return t.expertise?t.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(n=>n===e.symbol||en(e.symbol,n))||e.area&&s.areas&&s.areas.some(n=>n.toLowerCase().includes(e.area.toLowerCase())))):[]}function en(t,e){if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}return t===e}async function Vr(t,e){let s=q.join(t,ps),n=q.join(s,"antipatterns.yaml");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(E.existsSync(n)){let r=E.readFileSync(n,"utf8");i=be.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),E.writeFileSync(n,be.dump(i,{lineWidth:-1})),Fe(t);}async function Kr(t,e){let s=q.join(t,ps,"decisions");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=`${e.id}-${ol(e.title)}.yaml`,i=q.join(s,n);E.writeFileSync(i,be.dump(e,{lineWidth:-1})),Fe(t);}function ol(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}b$1();var Qr=".paradigm/history";async function Xr(t){let e=q.join(t,Qr);if(!E.existsSync(e))return {index:null,validation:null};let[s,n]=await Promise.all([al(e),cl(e)]);return {index:s,validation:n}}async function al(t){let e=q.join(t,"index.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#history-loader").error("Error parsing index.yaml",{error:s.message}),null}}async function cl(t){let e=q.join(t,"validation.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#history-loader").error("Error parsing validation.yaml",{error:s.message}),null}}function Zr(t,e){return e.map(s=>ll(t,s))}function ll(t,e){let s=t.index?.by_symbol?.[e]||null,n=[];if(t.index?.co_changes){for(let r of t.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!n.includes(o)&&n.push(o);}let i=t.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:n,validation:i}}function eo(t,e){let s=[],n=[];if(!t.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=t.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=t.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=t.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&n.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),n.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:n,safe_to_modify:i,recommendations:r}}async function us(t,e){let s=q.join(t,Qr),n=q.join(s,"log.jsonl");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i=dl(n),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
2
+ import {a as a$1,b as b$3}from'./chunk-4UJ4NIEQ.js';import {e,v,b as b$2,n as n$1,c as c$2,d as d$3,q as q$2,p,o as o$1,s as s$1,i as i$2,k as k$1,l as l$1,a as a$6,m as m$1,t as t$1,u as u$1,j as j$3}from'./chunk-4Q7XYPL4.js';import {o as o$2,A,y,x,f as f$4,r as r$1}from'./chunk-KLBH26PA.js';import {d as d$5,b as b$6,a as a$5}from'./chunk-JNSJVCTU.js';import {g as g$5,d as d$2,a as a$3}from'./chunk-Q2J542ST.js';import {i as i$4}from'./chunk-XROULIQN.js';import {n as n$3,j as j$4,P,O,K,Q as Q$1,L,I,J as J$1,D as D$1,H,m as m$2,l as l$2,E as E$2,v as v$2,N,q as q$3,C as C$1,S,o as o$3,z as z$2,t as t$2,B as B$1,s as s$2}from'./chunk-ZUAUFZRJ.js';import {f,g as g$2,e as e$1,q as q$1,t,o,v as v$1,i,m,V,h,k,l,j as j$2,n as n$2,u,r,ka as ka$1,s,la as la$1,F,R,_,x as x$1,E as E$1,D,G,w,C,B,A as A$1,z as z$1,y as y$1,U,Z,T,Y,X,W,O as O$1,I as I$1,K as K$1,M as M$1,L as L$1,P as P$1,N as N$1,J as J$2,H as H$1,S as S$1,Q as Q$2,a as a$9,d as d$9,c as c$5,$,aa as aa$1,ia as ia$1,ha as ha$1,ba as ba$1,fa as fa$1,ca as ca$1,da as da$1,ea as ea$1,ja as ja$1,ga as ga$1,b as b$b}from'./chunk-FILLU77P.js';import {j,a as a$2,i as i$1,b as b$4,h as h$2,g as g$4,c as c$1,d as d$1}from'./chunk-ODVKPZZ4.js';import {z,f as f$2,p as p$1,h as h$3,b as b$8,d as d$7,e as e$5,i as i$3,y as y$2,l as l$3,c as c$6}from'./chunk-74SGKSRQ.js';import {j as j$1,d,e as e$2,f as f$1,g as g$3,h as h$1}from'./chunk-UPFCBVXY.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {n,b as b$a}from'./chunk-4SCKMGTB.js';import {f as f$3,b as b$7,e as e$4,d as d$6,a as a$7,c as c$3}from'./chunk-DVZWCXB6.js';import {g as g$1,e as e$3,b as b$5,d as d$4,a as a$4}from'./chunk-QGZRM6ZB.js';import {g,d as d$8,c as c$4,b as b$9,a as a$8}from'./chunk-VG7FN2TU.js';import {b,c,d as d$a}from'./chunk-5TAVYPOV.js';import*as E from'fs';import*as q from'path';import*as be from'js-yaml';import*as Fo from'os';import {ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {execSync}from'child_process';var Pt,Cs,Rs=b(()=>{Pt={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]},Cs=new Set(["tool-called","context-checked"]);});var ca={};c(ca,{getAllStates:()=>js,getConfig:()=>tt,getState:()=>Rn,incrementFailure:()=>aa,invalidateGraduationCache:()=>Ud,isGraduated:()=>Wd,loadGraduation:()=>Le,markNeverGraduate:()=>Jd,saveGraduation:()=>Cn,setTier:()=>oa});function ra(t){return q.join(t,".paradigm","graduation.yaml")}function Le(t){let e=q.resolve(t);if(jt&&Sn===e&&Date.now()-_n<Gd)return jt;let s=ra(e),n;if(E.existsSync(s))try{let i=E.readFileSync(s,"utf8");n=be.load(i);}catch{n={version:"1.0",config:{},states:{}};}else n={version:"1.0",config:{},states:{}};return n.version||(n.version="1.0"),n.config||(n.config={}),n.states||(n.states={}),jt=n,Sn=e,_n=Date.now(),n}function Cn(t,e){let s=q.resolve(t),n=ra(s),i=q.dirname(n);E.existsSync(i)||E.mkdirSync(i,{recursive:true});let r=be.dump(e,{lineWidth:120,noRefs:true,sortKeys:true});E.writeFileSync(n,r,"utf8"),jt=e,Sn=s,_n=Date.now();}function tt(t){let e=Le(t);return {...Pt,...e.config,thresholds:{...Pt.thresholds,...e.config?.thresholds},demotion:{...Pt.demotion,...e.config?.demotion},neverGraduate:e.config?.neverGraduate??Pt.neverGraduate}}function Ps(t){return {habitId:t,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function Rn(t,e){let n=Le(t).states[e];return n?{...Ps(e),...n,habitId:e}:Ps(e)}function js(t){let e=Le(t),s={};for(let[n,i]of Object.entries(e.states))s[n]={...Ps(n),...i,habitId:n};return s}function Wd(t,e){return Rn(t,e).tier==="hook"}function oa(t,e,s,n){let i=Le(t),r=i.states[e]||{};i.states[e]={...r,tier:s,previousTier:r.tier||"habit",...s==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...s==="habit"&&r.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...n},Cn(t,i);}function Jd(t,e){let s=Le(t);s.states[e]||(s.states[e]={}),s.states[e].neverGraduate=true,s.states[e].tier="habit",Cn(t,s);}function aa(t,e){let s=Le(t);s.states[e]||(s.states[e]={});let n=(s.states[e].failureCount||0)+1;return s.states[e].failureCount=n,Cn(t,s),n}function Ud(){jt=null,Sn=null,_n=0;}var jt,Sn,_n,Gd,Pn=b(()=>{Rs();jt=null,Sn=null,_n=0,Gd=3e4;});b$1();b$1();var Zc=30*1e3,ds=new Map,ps=".paradigm/wisdom";async function Br(t){let e=q.resolve(t),s=ds.get(e);if(s&&Date.now()-s.loadedAt<Zc)return s.context;let n=await el(e);return ds.set(e,{context:n,loadedAt:Date.now()}),n}async function el(t){let e=q.join(t,ps),s=E.existsSync(e),[n,i,r,o]=s?await Promise.all([tl(e),nl(e),sl(e),il(e)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e$2(),l=f$1();}catch{}let d$1=new Set(i.map(f=>f.id)),u=i.map(f=>({...f,scope:"project"}));for(let f of a)d$1.has(f.id)||u.push({...f,scope:"global"});let g=new Set(o.map(f=>f.id)),p=o.map(f=>({...f,scope:"project"}));for(let f of c)g.has(f.id)||p.push({...f,scope:"global"});let m=n;if(l&&!n)m=l;else if(l&&n){let f={...n.by_symbol};if(l.by_symbol)for(let[y,b]of Object.entries(l.by_symbol))f[y]||(f[y]=b);m={...n,by_symbol:f,global:{...l.global,...n.global}};}return {preferences:m,antipatterns:u,decisions:p,expertise:r}}function Fe(t){let e=q.resolve(t);ds.delete(e);}async function tl(t){let e=q.join(t,"preferences.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:s}),null}}async function nl(t){let e=q.join(t,"antipatterns.yaml");if(!E.existsSync(e))return [];try{let s=E.readFileSync(e,"utf8");return be.load(s).antipatterns||[]}catch(s){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:s}),[]}}async function sl(t){let e=q.join(t,"expertise.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:s}),null}}async function il(t){let e=q.join(t,"decisions");if(!E.existsSync(e))return [];let s=[];try{let n=E.readdirSync(e);for(let i of n){if(!i.endsWith(".yaml")&&!i.endsWith(".yml"))continue;let r=q.join(e,i);try{let o=E.readFileSync(r,"utf8"),a=be.load(o);s.push(a);}catch(o){a.component("#wisdom-loader").error(`Error parsing ${i}`,{error:o});}}}catch(n){a.component("#wisdom-loader").error("Error reading decisions directory",{error:n});}return s.sort((n,i)=>n.id.localeCompare(i.id)),s}function zr(t,e){return e.map(s=>rl(t,s))}function rl(t,e){let s=t.preferences?.by_symbol?.[e]||null,n=t.antipatterns.filter(o=>o.symbols.some(a=>a===e||en(e,a))),i=t.decisions.filter(o=>o.symbols.some(a=>a===e||en(e,a))),r=t.expertise?.experts.filter(o=>o.symbols?.some(a=>a===e||en(e,a)))||[];return {symbol:e,preferences:s,antipatterns:n,decisions:i,experts:r}}function Yr(t,e){return t.expertise?t.expertise.experts.filter(s=>!!(e.symbol&&s.symbols&&s.symbols.some(n=>n===e.symbol||en(e.symbol,n))||e.area&&s.areas&&s.areas.some(n=>n.toLowerCase().includes(e.area.toLowerCase())))):[]}function en(t,e){if(e.endsWith("*")){let s=e.slice(0,-1);return t.startsWith(s)}return t===e}async function Vr(t,e){let s=q.join(t,ps),n=q.join(s,"antipatterns.yaml");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i={version:"1.0",antipatterns:[]};if(E.existsSync(n)){let r=E.readFileSync(n,"utf8");i=be.load(r);}i.antipatterns.push({...e,added:new Date().toISOString()}),E.writeFileSync(n,be.dump(i,{lineWidth:-1})),Fe(t);}async function Kr(t,e){let s=q.join(t,ps,"decisions");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=`${e.id}-${ol(e.title)}.yaml`,i=q.join(s,n);E.writeFileSync(i,be.dump(e,{lineWidth:-1})),Fe(t);}function ol(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}b$1();var Qr=".paradigm/history";async function Xr(t){let e=q.join(t,Qr);if(!E.existsSync(e))return {index:null,validation:null};let[s,n]=await Promise.all([al(e),cl(e)]);return {index:s,validation:n}}async function al(t){let e=q.join(t,"index.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#history-loader").error("Error parsing index.yaml",{error:s.message}),null}}async function cl(t){let e=q.join(t,"validation.yaml");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch(s){return a.component("#history-loader").error("Error parsing validation.yaml",{error:s.message}),null}}function Zr(t,e){return e.map(s=>ll(t,s))}function ll(t,e){let s=t.index?.by_symbol?.[e]||null,n=[];if(t.index?.co_changes){for(let r of t.index.co_changes)if(r.symbols.includes(e))for(let o of r.symbols)o!==e&&!n.includes(o)&&n.push(o);}let i=t.validation?.by_symbol?.[e]||null;return {symbol:e,summary:s,recent:s?.recent||[],co_changes:n,validation:i}}function eo(t,e){let s=[],n=[];if(!t.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let o of e){let a=t.index.by_symbol?.[o];a&&(a.fragility==="high"||a.fragility==="critical")&&s.push({symbol:o,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=t.index.fragile_symbols?.find(l=>l.symbol===o);c&&!s.find(l=>l.symbol===o)&&s.push(c);}for(let o of e){let a=t.index.co_changes?.filter(c=>c.symbols.includes(o));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==o&&!e.includes(d));l.length>0&&c.correlation>.7&&n.push(`${o} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let i=s.filter(o=>o.fragility==="critical").length===0,r=[];return s.length>0&&(r.push("Consider adding extra test coverage before modifying fragile symbols"),r.push("Review recent rollbacks and failures for these symbols")),n.length>0&&r.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:s,warnings:n,safe_to_modify:i,recommendations:r}}async function us(t,e){let s=q.join(t,Qr),n=q.join(s,"log.jsonl");E.existsSync(s)||E.mkdirSync(s,{recursive:true});let i=dl(n),r=new Date().toISOString(),o={id:i,ts:r,...e},a=JSON.stringify(o)+`
3
3
  `;return E.appendFileSync(n,a),i}async function to(t,e,s,n){return us(t,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:s,tests:n})}function dl(t){let e=1;return E.existsSync(t)&&(e=E.readFileSync(t,"utf8").split(`
4
- `).filter(n=>n.trim()).length+1),`h${String(e).padStart(4,"0")}`}b$1();function pl(t){let e=q.resolve(t),s=E.readFileSync(e,"utf8"),n=be.load(s);if(!n||typeof n!="object")throw new Error(`Invalid workspace file: ${t}`);let i={version:String(n.version||"1.0"),name:String(n.name||"unnamed-workspace"),members:[]};if(Array.isArray(n.members)){for(let r of n.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function so(t,e){let s=q.resolve(t),n=q.resolve(s,e);if(!E.existsSync(n))return a.component("#workspace-loader").warn("Workspace file not found",{workspacePath:n}),null;let i;try{i=pl(n);}catch(c){return a.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let r=q.dirname(n),o="";for(let c of i.members){let l=q.resolve(r,c.path);if(no(l)===no(s)){o=c.name;break}}if(!o)return a.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:i.name}),null;let a$1=new Map;for(let c of i.members){if(c.name===o)continue;let l=q.resolve(r,c.path),d=q.join(l,".paradigm","scan-index.json");if(!E.existsSync(d)){a.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let u=JSON.parse(E.readFileSync(d,"utf8")),g=ml(u);c.exports&&c.exports.length>0&&(g=ul(g,c.exports));let p=null,m=q.join(l,"portal.yaml");if(E.existsSync(m))try{let f=E.readFileSync(m,"utf8"),y=be.load(f);y&&(p=y);}catch{}a$1.set(c.name,{index:g,gateConfig:p});}catch(u){a.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:u.message});}}return {config:i,workspacePath:n,currentMember:o,siblingIndices:a$1}}function ul(t,e){let n=n$2(t).filter(i=>{let r=i.symbol;return e.some(o=>gl(o,r))});return fl(n)}function gl(t,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function bt(t,e){let s=[];for(let[n,i]of t.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:n,symbol:`${n}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function io(t,e){let s=[],n=e.includes("/")?e.split("/").pop():e;for(let[i,r]of t.siblingIndices){let o=[],a=n$2(r.index);for(let c of a){let l=c.references||[],d=c.description||"",u=l.some(p=>p===n||p===e||p.endsWith(`/${n}`)),g=d.includes(n);(u||g)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function no(t){return q.resolve(t).replace(/\/+$/,"")}function ml(t){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[n,i]of Object.entries(e)){let r=t[n];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$2({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function fl(t){return g$2({symbols:t.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function sg(t){let e=q.resolve(t),s=await f(e),n=g$2(s),i=null,r=q.join(e,"portal.yaml");if(E.existsSync(r))try{i=await e$1(r);}catch(d){a.component("#index-loader").warn("Could not parse portal.yaml",{error:d.message});}let o=q.basename(e),a$1=q.join(e,".premise");if(E.existsSync(a$1))try{let u=E.readFileSync(a$1,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);u&&(o=u[1].trim());}catch{}let c=null,l=q.join(e,".paradigm","config.yaml");if(E.existsSync(l))try{let d=E.readFileSync(l,"utf8"),u=be.load(d);u&&typeof u=="object"&&(u.version||a.component("#index-loader").warn('config.yaml missing "version" field'),u.project||a.component("#index-loader").warn('config.yaml missing "project" field')),u&&typeof u.workspace=="string"&&(c=so(e,u.workspace));}catch(d){a.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:n,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function nn(t){return t.wisdom||(t.wisdom=await Br(t.rootDir)),t.wisdom}async function ms(t){return t.history||(t.history=await Xr(t.rootDir)),t.history}j();function ao(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function sn(t,e,s){switch(t){case "paradigm_wisdom_context":{let{symbols:n,include_global:i=true}=e,r=await nn(s),o=zr(r,n),a={symbols:n,wisdom:o.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(u=>({id:u.id,description:u.description,reason:u.reason,alternative:u.alternative,scope:u.scope||"project"})),decisions:d.decisions.map(u=>({id:u.id,title:u.title,status:u.status,decision:u.decision,scope:u.scope||"project"})),experts:d.experts.map(u=>u.name)}))};i&&r.preferences?.global&&(a.global_preferences=r.preferences.global);let c=o.reduce((d,u)=>d+u.antipatterns.length,0),l=o.reduce((d,u)=>d+u.decisions.length,0);a.summary={symbols_with_preferences:o.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:o.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},u=[];for(let g of n){let p=await a$2(s.rootDir,{symbol:g,hasAssessment:!0,limit:100});if(p.length===0)continue;let m={correct:0,partial:0,incorrect:0},f=0,y=0;for(let h of p){let v=h.assessment.verdict;m[v]++,h.confidence!=null&&(f+=h.confidence,y++);}d[g]={total:p.length,...m,avgConfidence:y>0?Math.round(f/y*1e3)/1e3:null};let b=(m.correct+m.partial*.5)/p.length;b<.6&&p.length>=3&&u.push(`Low historical accuracy for ${g}: ${Math.round(b*100)}% across ${p.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),u.length>0&&(a.calibration_warnings=u);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:n,id:i,symbols:r,description:o,reason:a,alternative:c,title:l,status:d,rationale:u,consequences:g,scope:p="project"}=e;if(n==="antipattern"){if(!o||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a,alternative:c};return p==="global"?g$3(m):await Vr(s.rootDir,m),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:p,message:`Antipattern recorded to ${p} scope`})}}if(n==="decision"){if(!l||!o||!u||!g)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};let m={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a||"",decision:o,rationale:u,consequences:g};return p==="global"?h$1(m):await Kr(s.rootDir,m),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:p,message:`Decision recorded to ${p} scope`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_promote":{let{type:n,id:i}=e,r=await nn(s),o=q.basename(s.rootDir);if(n==="antipattern"){let a=r.antipatterns.find(l=>l.id===i);return a?d$1().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Antipattern "${i}" already exists in global scope`})}:(g$3({...a,learned_from:`promoted from ${o}`}),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,promoted_from:o,message:`Antipattern "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${i}" not found in project`})}}if(n==="decision"){let a=r.decisions.find(l=>l.id===i);return a?e$2().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Decision "${i}" already exists in global scope`})}:(h$1(a),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,promoted_from:o,message:`Decision "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${i}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_expert":{let{symbol:n,area:i}=e;if(!n&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await nn(s),o=Yr(r,{symbol:n,area:i});return {handled:true,text:JSON.stringify({query:{symbol:n,area:i},count:o.length,experts:o.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:o.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function co(){return [{name:"paradigm_history_context",description:"Get implementation history for symbols before modifying. Shows recent changes, stability, and who has worked on these areas. Returns recent commits, authors, and change frequency. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get history for (e.g., ["@checkout", "#payment-form"])'}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_history_record",description:"Record an implementation event (feature, fix, refactor). Call this after making changes to track what was done. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["implement","refactor","rollback"],description:"Type of change"},symbols:{type:"array",items:{type:"string"},description:"Symbols affected by this change"},intent:{type:"string",enum:["feature","fix","refactor","experimental","confirmed"],description:"Intent of the change"},description:{type:"string",description:"What was done"},commit:{type:"string",description:"Git commit hash (optional)"},files:{type:"array",items:{type:"string"},description:"Files affected (optional)"},reason:{type:"string",description:"Reason for rollback (if type is rollback)"}},required:["type","symbols","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_validate",description:"Record a validation result (tests passed/failed). Call this after running tests. ~100 tokens.",inputSchema:{type:"object",properties:{implementation_id:{type:"string",description:"ID of the implementation being validated (from paradigm_history_record)"},result:{type:"string",enum:["pass","fail","partial"],description:"Validation result"},tests:{type:"object",properties:{passed:{type:"number"},failed:{type:"number"},skipped:{type:"number"}},description:"Test counts"}},required:["result"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_fragility",description:"Check fragility of symbols before modifying. Returns stability scores and warnings for fragile areas. Returns numeric stability scores (0-100) and actionable warnings. ~150 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols to check fragility for"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function lo(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,i=await ms(s),r=Zr(i,n),o={symbols:n,history:r.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:r.filter(a=>a.summary).length,fragile_count:r.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await us(s.rootDir,{type:n,symbols:i,author:{type:"agent",id:"claude"},intent:r,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:i,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:i,tests:r}=e,o=await to(s.rootDir,n||"unknown",i,r);return {handled:true,text:JSON.stringify({success:true,id:o,result:i,tests:r,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,i=await ms(s),r=eo(i,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:r.safe_to_modify,fragile:r.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:r.warnings,recommendations:r.recommendations,summary:r.fragile.length===0?"All symbols are stable - safe to proceed":r.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}b$1();var yl=".paradigm/navigator.yaml";async function go(t){let e=q.join(t,yl);if(!E.existsSync(e))return {config:null,configPath:null};try{let s=E.readFileSync(e,"utf8");return {config:be.load(s),configPath:e}}catch(s){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:s}),{config:null,configPath:e}}}function mo(t,e,s){switch(e.intent){case "find":return hl(t,e.target||"");case "explore":return bl(t,e.target||"");case "context":return wl(t,e.task||"");default:return {paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function hl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=t.symbols[e];if(i)n.paths.push(i),n.symbols.push(e),n.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(t.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(n.paths=r.map(([,o])=>o),n.symbols=r.map(([o])=>o),n.explanation=`Found ${r.length} symbols matching "${e}"`):n.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(t.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)n.paths=i.map(([,r])=>r),n.symbols=i.map(([r])=>r),n.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=vl(t,e);r?(n.paths=r.paths,n.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):n.explanation=`No matches found for "${e}"`;}}return n.suggested_order=fs(n.paths,t),n}function bl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(t.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){n.paths.push(...o.paths);let a=Object.entries(t.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);n.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(t.key_files))r.toLowerCase().includes(i)&&n.paths.push(...o);if(n.paths.length===0){let r=Object.entries(t.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);n.paths=[...new Set(r.map(([,o])=>o))],n.symbols=r.map(([o])=>o);}return n.explanation=`Exploration paths for "${e}": ${n.paths.length} locations, ${n.symbols.length} symbols`,n.suggested_order=fs(n.paths,t),n}function wl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=kl(i);for(let[o,a]of Object.entries(t.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&n.paths.push(...a.paths);for(let[o,a]of Object.entries(t.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(n.paths.push(a),n.symbols.push(o));}return n.paths.push(...t.key_files.config),n.paths=[...new Set(n.paths)],n.symbols=[...new Set(n.symbols)],i.includes("test")?n.skip=t.skip_patterns.always:n.skip=[...t.skip_patterns.always,...t.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&n.skip.push(...t.skip_patterns.unless_docs),n.explanation=`Context for "${e}": ${n.paths.length} relevant files, ${n.symbols.length} symbols`,n.suggested_order=fs(n.paths,t),n}function vl(t,e){let s=e.toLowerCase();for(let[n,i]of Object.entries(t.structure))if(i&&(n.toLowerCase().includes(s)||s.includes(n.toLowerCase())))return i;return null}function kl(t){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return t.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function fs(t,e){let s={};for(let n of t){let i=0;e.key_files.config.some(r=>n.includes(r))&&(i+=100),e.key_files.entry.some(r=>n.includes(r))&&(i+=80),e.key_files.types.some(r=>n.includes(r))&&(i+=60),i-=n.split("/").length*2,s[n]=i;}return [...t].sort((n,i)=>(s[i]||0)-(s[n]||0))}var Sl={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function fo(){return [Sl]}async function on(t,e,s){if(t!=="paradigm_navigate")return {handled:false,text:""};let n={intent:e.intent||"find",target:e.target,task:e.task},i=await go(s.rootDir);if(i.config||(i={config:_l(s),configPath:null}),false);if(n.intent==="context"&&!n.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((n.intent==="find"||n.intent==="explore")&&!n.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${n.intent} intent`,example:n.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${n.intent}:${n.target||""}:${n.task||""}`,o=await v$1.getOrCompute(r,()=>{let c=mo(i.config,n,s.rootDir),l={intent:n.intent,...n.target&&{target:n.target},...n.task&&{task:n.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(i.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),s.workspace){if(n.intent==="find"&&n.target&&c.paths.length===0){let d=bt(s.workspace,n.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(n.intent==="context"&&n.task){let d=bt(s.workspace,n.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})));}}return JSON.stringify(l,null,2)}),a=o;if(e.response_format==="concise")try{let c=JSON.parse(o);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}return {handled:true,text:a}}function _l(t){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},n=n$2(t.index),i=new Set;for(let a of n)if(a.filePath){e[a.symbol]=a.filePath,i.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":s.features.paths.includes(c)||s.features.paths.push(c);break;case "component":s.components.paths.includes(c)||s.components.paths.push(c);break;case "gate":s.gates.paths.includes(c)||s.gates.paths.push(c);break;case "flow":s.flows.paths.includes(c)||s.flows.paths.push(c);break}}let r=[],o=[];for(let a of t.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),t.gateConfig&&r.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:s,key_files:{config:r.slice(0,10),entry:o,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}var an=null,ys=false;function xl(t){if(an||(an=new f$4),!ys)try{let e=r$1();for(let s of e)try{an.addPattern(s);}catch{}ys=!0;}catch{ys=true;}return an}function yo(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ho(t,e,s){let n=xl(),i=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:r,environment:a,search:c});if(d.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let u=d.map(g=>{let p=i.match(g,{maxResults:3});return {id:g.id,timestamp:g.timestamp,status:g.status,error:g.error.message,symbols:g.symbols,environment:g.environment,matches:p.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:u.length,incidents:u},null,2)}}case "paradigm_sentinel_show":{let{incidentId:r,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(r);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let l=i.match(c,{maxResults:5}),d={incident:c,matches:l.map(u=>({patternId:u.pattern.id,name:u.pattern.name,confidence:u.confidence,matchedCriteria:u.matchedCriteria,resolution:u.pattern.resolution}))};if(o&&c.flowPosition){let u=new x().build(c);u&&(d.timeline=new x().renderStructured(u));}if(a){let u=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(g=>g.id!==r);d.similar=u.map(g=>({id:g.id,error:g.error.message,status:g.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(r)?d?(n.updateIncident(r,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} marked as won't fix`})}):(n.recordResolution({incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${r} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:r,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return r&&(l=c.filter(d=>{let u=d.pattern.symbols;return Object.values(u).some(g=>g?Array.isArray(g)?g.includes(r)||g.some(p=>r.match(p.replace("*",".*"))):g===r||r.match(g.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:r,name:o,description:a,pattern:c,resolution:l,tags:d}=e,u={id:r,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(u),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${r} created`,pattern:u})}}case "paradigm_sentinel_record":{let{error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,u=n.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),g=n.getIncident(u),p=g?i.match(g,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:u,matches:p.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:r="7d",symbol:o}=e,a=new y(n);if(o){let u=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:u},null,2)}}let c=r.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:r,minOccurrences:o}=e,a=new A(n);if(r){let l=n.getIncident(r);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:r,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:g=50}=e,p=n.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:g}),m=n.getLogCount({level:r,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:p.length,total:m,logs:p.map(f=>({timestamp:f.timestamp,level:f.level,symbol:f.symbol,service:f.service,message:f.message,data:f.data,sessionId:f.sessionId,correlationId:f.correlationId,durationMs:f.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let r=n.getServices();return {handled:true,text:JSON.stringify({count:r.length,services:r.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:r}=e,o=r?n.getAppState(r):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:r}=e,o=n.getLogCount({symbol:r});return {handled:true,text:JSON.stringify({symbol:r,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:r,service:o,since:a}=e,l=n.queryLogs({symbol:r,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:r,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&r){let g=n.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(g,null,2)}}let u=n.queryMetrics({name:r,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:u.length,metrics:u.map(g=>({timestamp:g.timestamp,name:g.name,type:g.type,value:g.value,tags:g.tags,service:g.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:r,service:o,symbol:a,since:c,limit:l}=e;if(r){let u=n.getTrace(r);return u?{handled:true,text:JSON.stringify(u,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.map(u=>({traceId:u.traceId,services:u.services,spanCount:u.spans.length,totalDurationMs:u.totalDurationMs,startTime:u.startTime,endTime:u.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:r}=e;if(r){let a=n.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=n.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:g,limit:p}=e,m=n.queryEvents({schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:g,limit:Math.min(p||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(f=>({id:f.id,schemaId:f.schemaId,eventType:f.eventType,category:f.category,timestamp:f.timestamp,scopeValue:f.scopeValue,service:f.service,severity:f.severity,data:f.data,parentEventId:f.parentEventId,depth:f.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:r,sessionId:o,limit:a}=e,c=n.getEventScopes(r,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${r}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}b$1();var Cl=30*1e3,bo=new Map;async function dn(t){let e=q.resolve(t),s=bo.get(e);if(s&&Date.now()-s.loadedAt<Cl)return s.index;let n=await Rl(e);return n&&bo.set(e,{index:n,loadedAt:Date.now()}),n}async function Rl(t){let e=q.join(t,".paradigm","flow-index.json");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:s}),null}}function Pl(t,e){let s=t.symbolToFlows[e]||[],n=[];for(let i of s){let r=t.flows[i];if(!r)continue;let o=r.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of o){let l=r.steps.slice(c+1).map(d=>d.id);n.push({flowId:r.id,definedIn:r.definedIn,description:r.description,trigger:r.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:r.validation});}}return n}function pn(t,e){let s=Pl(t,e),n=new Set;for(let o of s)o.validation?.command&&n.add(o.validation.command);let i="low",r=s.reduce((o,a)=>o+a.downstreamSteps.length,0);return s.length>3||r>10?i="high":(s.length>1||r>3)&&(i="medium"),{symbol:e,totalFlows:s.length,impactLevel:i,affectedFlows:s,validationCommands:Array.from(n),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${n.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function wo(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function vo(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:i=true}=e,r=await dn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
4
+ `).filter(n=>n.trim()).length+1),`h${String(e).padStart(4,"0")}`}b$1();function pl(t){let e=q.resolve(t),s=E.readFileSync(e,"utf8"),n=be.load(s);if(!n||typeof n!="object")throw new Error(`Invalid workspace file: ${t}`);let i={version:String(n.version||"1.0"),name:String(n.name||"unnamed-workspace"),members:[]};if(Array.isArray(n.members)){for(let r of n.members)if(typeof r=="object"&&r!==null){let o=r;i.members.push({name:String(o.name||""),path:String(o.path||""),role:o.role,exports:Array.isArray(o.exports)?o.exports.map(String):void 0});}}return i}function so(t,e){let s=q.resolve(t),n=q.resolve(s,e);if(!E.existsSync(n))return a.component("#workspace-loader").warn("Workspace file not found",{workspacePath:n}),null;let i;try{i=pl(n);}catch(c){return a.component("#workspace-loader").warn("Could not parse workspace file",{error:c.message}),null}let r=q.dirname(n),o="";for(let c of i.members){let l=q.resolve(r,c.path);if(no(l)===no(s)){o=c.name;break}}if(!o)return a.component("#workspace-loader").warn("Current directory is not a member of workspace",{workspace:i.name}),null;let a$1=new Map;for(let c of i.members){if(c.name===o)continue;let l=q.resolve(r,c.path),d=q.join(l,".paradigm","scan-index.json");if(!E.existsSync(d)){a.component("#workspace-loader").warn("No scan-index.json for workspace member",{member:c.name,scanIndexPath:d});continue}try{let u=JSON.parse(E.readFileSync(d,"utf8")),g=ml(u);c.exports&&c.exports.length>0&&(g=ul(g,c.exports));let p=null,m=q.join(l,"portal.yaml");if(E.existsSync(m))try{let f=E.readFileSync(m,"utf8"),y=be.load(f);y&&(p=y);}catch{}a$1.set(c.name,{index:g,gateConfig:p});}catch(u){a.component("#workspace-loader").warn("Could not load index for workspace member",{member:c.name,error:u.message});}}return {config:i,workspacePath:n,currentMember:o,siblingIndices:a$1}}function ul(t,e){let n=n$2(t).filter(i=>{let r=i.symbol;return e.some(o=>gl(o,r))});return fl(n)}function gl(t,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`,"i").test(e)}function bt(t,e){let s=[];for(let[n,i]of t.siblingIndices){let r=j$2(i.index,e);for(let o of r)s.push({project:n,symbol:`${n}/${o.symbol}`,type:o.type,description:o.description,filePath:o.filePath});}return s}function io(t,e){let s=[],n=e.includes("/")?e.split("/").pop():e;for(let[i,r]of t.siblingIndices){let o=[],a=n$2(r.index);for(let c of a){let l=c.references||[],d=c.description||"",u=l.some(p=>p===n||p===e||p.endsWith(`/${n}`)),g=d.includes(n);(u||g)&&o.push({symbol:c.symbol,type:c.type,description:c.description});}o.length>0&&s.push({project:i,references:o});}return s}function no(t){return q.resolve(t).replace(/\/+$/,"")}function ml(t){let e={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"},s=[];for(let[n,i]of Object.entries(e)){let r=t[n];if(!(!r||typeof r!="object"))for(let[o,a]of Object.entries(r)){let c={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"}[i]||"#";s.push({id:o,symbol:a.symbol||`${c}${o}`,type:i,source:"purpose",filePath:a.path||"",data:{},references:a.related||[],referencedBy:[],description:a.description,tags:a.visualTags||[]});}}return g$2({symbols:s,purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}function fl(t){return g$2({symbols:t.map(e=>({id:e.id||e.symbol.replace(/^[#$^!~]/,""),symbol:e.symbol,type:e.type,source:"purpose",filePath:e.filePath||"",data:e.data||{},references:e.references||[],referencedBy:e.referencedBy||[],description:e.description,tags:e.tags})),purposeFiles:[],portalFiles:[],errors:[],timestamp:Date.now()})}async function sg(t){let e=q.resolve(t),s=await f(e),n=g$2(s),i=null,r=q.join(e,"portal.yaml");if(E.existsSync(r))try{i=await e$1(r);}catch(d){a.component("#index-loader").warn("Could not parse portal.yaml",{error:d.message});}let o=q.basename(e),a$1=q.join(e,".premise");if(E.existsSync(a$1))try{let u=E.readFileSync(a$1,"utf8").match(/name:\s*["']?([^"'\n]+)["']?/);u&&(o=u[1].trim());}catch{}let c=null,l=q.join(e,".paradigm","config.yaml");if(E.existsSync(l))try{let d=E.readFileSync(l,"utf8"),u=be.load(d);u&&typeof u=="object"&&(u.version||a.component("#index-loader").warn('config.yaml missing "version" field'),u.project||a.component("#index-loader").warn('config.yaml missing "project" field')),u&&typeof u.workspace=="string"&&(c=so(e,u.workspace));}catch(d){a.component("#index-loader").warn("Failed to load workspace config",{error:d.message});}return {rootDir:e,index:n,aggregation:s,gateConfig:i,projectName:o,wisdom:null,history:null,workspace:c,_loadedAt:Date.now()}}async function nn(t){return t.wisdom||(t.wisdom=await Br(t.rootDir)),t.wisdom}async function ms(t){return t.history||(t.history=await Xr(t.rootDir)),t.history}j();function ao(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function sn(t,e,s){switch(t){case "paradigm_wisdom_context":{let{symbols:n,include_global:i=true}=e,r=await nn(s),o=zr(r,n),a={symbols:n,wisdom:o.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(u=>({id:u.id,description:u.description,reason:u.reason,alternative:u.alternative,scope:u.scope||"project"})),decisions:d.decisions.map(u=>({id:u.id,title:u.title,status:u.status,decision:u.decision,scope:u.scope||"project"})),experts:d.experts.map(u=>u.name)}))};i&&r.preferences?.global&&(a.global_preferences=r.preferences.global);let c=o.reduce((d,u)=>d+u.antipatterns.length,0),l=o.reduce((d,u)=>d+u.decisions.length,0);a.summary={symbols_with_preferences:o.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:o.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},u=[];for(let g of n){let p=await a$2(s.rootDir,{symbol:g,hasAssessment:!0,limit:100});if(p.length===0)continue;let m={correct:0,partial:0,incorrect:0},f=0,y=0;for(let h of p){let v=h.assessment.verdict;m[v]++,h.confidence!=null&&(f+=h.confidence,y++);}d[g]={total:p.length,...m,avgConfidence:y>0?Math.round(f/y*1e3)/1e3:null};let b=(m.correct+m.partial*.5)/p.length;b<.6&&p.length>=3&&u.push(`Low historical accuracy for ${g}: ${Math.round(b*100)}% across ${p.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),u.length>0&&(a.calibration_warnings=u);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:n,id:i,symbols:r,description:o,reason:a,alternative:c,title:l,status:d,rationale:u,consequences:g,scope:p="project"}=e;if(n==="antipattern"){if(!o||!a||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let m={id:i,symbols:r,description:o,reason:a,alternative:c};return p==="global"?g$3(m):await Vr(s.rootDir,m),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,scope:p,message:`Antipattern recorded to ${p} scope`})}}if(n==="decision"){if(!l||!o||!u||!g)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};let m={id:i,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:r,context:a||"",decision:o,rationale:u,consequences:g};return p==="global"?h$1(m):await Kr(s.rootDir,m),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,scope:p,message:`Decision recorded to ${p} scope`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_promote":{let{type:n,id:i}=e,r=await nn(s),o=q.basename(s.rootDir);if(n==="antipattern"){let a=r.antipatterns.find(l=>l.id===i);return a?d().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Antipattern "${i}" already exists in global scope`})}:(g$3({...a,learned_from:`promoted from ${o}`}),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:i,promoted_from:o,message:`Antipattern "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${i}" not found in project`})}}if(n==="decision"){let a=r.decisions.find(l=>l.id===i);return a?e$2().some(l=>l.id===i)?{handled:true,text:JSON.stringify({error:`Decision "${i}" already exists in global scope`})}:(h$1(a),Fe(s.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:i,promoted_from:o,message:`Decision "${i}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${i}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${n}`})}}case "paradigm_wisdom_expert":{let{symbol:n,area:i}=e;if(!n&&!i)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let r=await nn(s),o=Yr(r,{symbol:n,area:i});return {handled:true,text:JSON.stringify({query:{symbol:n,area:i},count:o.length,experts:o.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:o.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function co(){return [{name:"paradigm_history_context",description:"Get implementation history for symbols before modifying. Shows recent changes, stability, and who has worked on these areas. Returns recent commits, authors, and change frequency. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get history for (e.g., ["@checkout", "#payment-form"])'}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_history_record",description:"Record an implementation event (feature, fix, refactor). Call this after making changes to track what was done. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["implement","refactor","rollback"],description:"Type of change"},symbols:{type:"array",items:{type:"string"},description:"Symbols affected by this change"},intent:{type:"string",enum:["feature","fix","refactor","experimental","confirmed"],description:"Intent of the change"},description:{type:"string",description:"What was done"},commit:{type:"string",description:"Git commit hash (optional)"},files:{type:"array",items:{type:"string"},description:"Files affected (optional)"},reason:{type:"string",description:"Reason for rollback (if type is rollback)"}},required:["type","symbols","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_validate",description:"Record a validation result (tests passed/failed). Call this after running tests. ~100 tokens.",inputSchema:{type:"object",properties:{implementation_id:{type:"string",description:"ID of the implementation being validated (from paradigm_history_record)"},result:{type:"string",enum:["pass","fail","partial"],description:"Validation result"},tests:{type:"object",properties:{passed:{type:"number"},failed:{type:"number"},skipped:{type:"number"}},description:"Test counts"}},required:["result"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_history_fragility",description:"Check fragility of symbols before modifying. Returns stability scores and warnings for fragile areas. Returns numeric stability scores (0-100) and actionable warnings. ~150 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:"Symbols to check fragility for"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function lo(t,e,s){switch(t){case "paradigm_history_context":{let{symbols:n}=e,i=await ms(s),r=Zr(i,n),o={symbols:n,history:r.map(a=>({symbol:a.symbol,summary:a.summary?{total_changes:a.summary.total_changes,last_modified:a.summary.last_modified,stability_score:a.summary.stability_score,fragility:a.summary.fragility,contributors:a.summary.contributors}:null,recent:a.recent.slice(0,3).map(c=>({type:c.type,description:c.description,author:c.author,ts:c.ts})),co_changes:a.co_changes.slice(0,5)})),summary:{total_symbols:n.length,with_history:r.filter(a=>a.summary).length,fragile_count:r.filter(a=>a.summary?.fragility==="high"||a.summary?.fragility==="critical").length}};return {handled:true,text:JSON.stringify(o,null,2)}}case "paradigm_history_record":{let{type:n,symbols:i,intent:r,description:o,commit:a,files:c,reason:l}=e,d=await us(s.rootDir,{type:n,symbols:i,author:{type:"agent",id:"claude"},intent:r,description:o,commit:a,files:c,reason:l});return {handled:true,text:JSON.stringify({success:true,id:d,type:n,symbols:i,message:"History entry recorded successfully",note:"Run paradigm history reindex to update the index after multiple entries"})}}case "paradigm_history_validate":{let{implementation_id:n,result:i,tests:r}=e,o=await to(s.rootDir,n||"unknown",i,r);return {handled:true,text:JSON.stringify({success:true,id:o,result:i,tests:r,message:"Validation recorded successfully"})}}case "paradigm_history_fragility":{let{symbols:n}=e,i=await ms(s),r=eo(i,n);return {handled:true,text:JSON.stringify({symbols:n,safe_to_modify:r.safe_to_modify,fragile:r.fragile.map(o=>({symbol:o.symbol,fragility:o.fragility,reason:o.reason})),warnings:r.warnings,recommendations:r.recommendations,summary:r.fragile.length===0?"All symbols are stable - safe to proceed":r.safe_to_modify?"Some fragile symbols detected - proceed with extra testing":"Critical fragility detected - consider deferring changes or adding extensive tests"})}}default:return {handled:false,text:""}}}b$1();var yl=".paradigm/navigator.yaml";async function go(t){let e=q.join(t,yl);if(!E.existsSync(e))return {config:null,configPath:null};try{let s=E.readFileSync(e,"utf8");return {config:be.load(s),configPath:e}}catch(s){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:s}),{config:null,configPath:e}}}function mo(t,e,s){switch(e.intent){case "find":return hl(t,e.target||"");case "explore":return bl(t,e.target||"");case "context":return wl(t,e.task||"");default:return {paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function hl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let i=t.symbols[e];if(i)n.paths.push(i),n.symbols.push(e),n.explanation=`Found symbol ${e} at ${i}`;else {let r=Object.entries(t.symbols).filter(([o])=>o.includes(e.slice(1))).slice(0,5);r.length>0?(n.paths=r.map(([,o])=>o),n.symbols=r.map(([o])=>o),n.explanation=`Found ${r.length} symbols matching "${e}"`):n.explanation=`Symbol ${e} not found in navigator`;}}else {let i=Object.entries(t.symbols).filter(([r])=>r.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(i.length>0)n.paths=i.map(([,r])=>r),n.symbols=i.map(([r])=>r),n.explanation=`Found ${i.length} symbols matching "${e}"`;else {let r=vl(t,e);r?(n.paths=r.paths,n.explanation=`Found ${e} in structure: ${r.paths.join(", ")}`):n.explanation=`No matches found for "${e}"`;}}return n.suggested_order=fs(n.paths,t),n}function bl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase();for(let[r,o]of Object.entries(t.structure))if(o&&(r.toLowerCase().includes(i)||i.includes(r.toLowerCase()))){n.paths.push(...o.paths);let a=Object.entries(t.symbols).filter(([c])=>c.startsWith(o.symbol)).slice(0,10);n.symbols.push(...a.map(([c])=>c));}for(let[r,o]of Object.entries(t.key_files))r.toLowerCase().includes(i)&&n.paths.push(...o);if(n.paths.length===0){let r=Object.entries(t.symbols).filter(([o,a])=>o.toLowerCase().includes(i)||a.toLowerCase().includes(i)).slice(0,10);n.paths=[...new Set(r.map(([,o])=>o))],n.symbols=r.map(([o])=>o);}return n.explanation=`Exploration paths for "${e}": ${n.paths.length} locations, ${n.symbols.length} symbols`,n.suggested_order=fs(n.paths,t),n}function wl(t,e,s){let n={paths:[],symbols:[],skip:t.skip_patterns.always,suggested_order:[]},i=e.toLowerCase(),r=kl(i);for(let[o,a]of Object.entries(t.structure))a&&r.some(c=>o.toLowerCase().includes(c))&&n.paths.push(...a.paths);for(let[o,a]of Object.entries(t.symbols)){let c=o.slice(1).toLowerCase();r.some(l=>c.includes(l)||l.includes(c))&&(n.paths.push(a),n.symbols.push(o));}return n.paths.push(...t.key_files.config),n.paths=[...new Set(n.paths)],n.symbols=[...new Set(n.symbols)],i.includes("test")?n.skip=t.skip_patterns.always:n.skip=[...t.skip_patterns.always,...t.skip_patterns.unless_testing],!i.includes("doc")&&!i.includes("readme")&&n.skip.push(...t.skip_patterns.unless_docs),n.explanation=`Context for "${e}": ${n.paths.length} relevant files, ${n.symbols.length} symbols`,n.suggested_order=fs(n.paths,t),n}function vl(t,e){let s=e.toLowerCase();for(let[n,i]of Object.entries(t.structure))if(i&&(n.toLowerCase().includes(s)||s.includes(n.toLowerCase())))return i;return null}function kl(t){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return t.split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s.length>2&&!e.has(s))}function fs(t,e){let s={};for(let n of t){let i=0;e.key_files.config.some(r=>n.includes(r))&&(i+=100),e.key_files.entry.some(r=>n.includes(r))&&(i+=80),e.key_files.types.some(r=>n.includes(r))&&(i+=60),i-=n.split("/").length*2,s[n]=i;}return [...t].sort((n,i)=>(s[i]||0)-(s[n]||0))}var Sl={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function fo(){return [Sl]}async function on(t,e,s){if(t!=="paradigm_navigate")return {handled:false,text:""};let n={intent:e.intent||"find",target:e.target,task:e.task},i=await go(s.rootDir);if(i.config||(i={config:_l(s),configPath:null}),false);if(n.intent==="context"&&!n.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((n.intent==="find"||n.intent==="explore")&&!n.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${n.intent} intent`,example:n.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let r=`navigate:${n.intent}:${n.target||""}:${n.task||""}`,o=await v$1.getOrCompute(r,()=>{let c=mo(i.config,n,s.rootDir),l={intent:n.intent,...n.target&&{target:n.target},...n.task&&{task:n.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(i.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),s.workspace){if(n.intent==="find"&&n.target&&c.paths.length===0){let d=bt(s.workspace,n.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(n.intent==="context"&&n.task){let d=bt(s.workspace,n.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})));}}return JSON.stringify(l,null,2)}),a=o;if(e.response_format==="concise")try{let c=JSON.parse(o);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}return {handled:true,text:a}}function _l(t){let e={},s={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},n=n$2(t.index),i=new Set;for(let a of n)if(a.filePath){e[a.symbol]=a.filePath,i.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":s.features.paths.includes(c)||s.features.paths.push(c);break;case "component":s.components.paths.includes(c)||s.components.paths.push(c);break;case "gate":s.gates.paths.includes(c)||s.gates.paths.push(c);break;case "flow":s.flows.paths.includes(c)||s.flows.paths.push(c);break}}let r=[],o=[];for(let a of t.aggregation.purposeFiles)r.push(a.filePath);return r.push(".paradigm/config.yaml"),t.gateConfig&&r.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:s,key_files:{config:r.slice(0,10),entry:o,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}var an=null,ys=false;function xl(t){if(an||(an=new f$4),!ys)try{let e=r$1();for(let s of e)try{an.addPattern(s);}catch{}ys=!0;}catch{ys=true;}return an}function yo(){return [{name:"paradigm_sentinel_triage",description:"View and filter incidents with pattern matches. Returns recent errors with symbolic context and resolution suggestions. ~200-400 tokens depending on incident count.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter by symbol (e.g., @checkout, ^auth)"},status:{type:"string",enum:["open","investigating","resolved","wont-fix","all"],description:"Filter by status (default: all)"},environment:{type:"string",description:"Filter by environment"},search:{type:"string",description:"Search in error messages"},limit:{type:"number",description:"Max results (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_show",description:"Get full details of a specific incident including timeline and matched patterns. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID (e.g., INC-001)"},includeTimeline:{type:"boolean",description:"Include flow timeline"},includeSimilar:{type:"boolean",description:"Include similar incidents"}},required:["incidentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_resolve",description:"Mark an incident as resolved with optional pattern and commit reference. ~100 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Incident ID"},patternId:{type:"string",description:"Pattern that led to resolution"},commitHash:{type:"string",description:"Fix commit hash"},prUrl:{type:"string",description:"PR URL"},notes:{type:"string",description:"Resolution notes"},wontFix:{type:"boolean",description:"Mark as wont-fix instead of resolved"}},required:["incidentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_patterns",description:"List and filter failure patterns with confidence scores. Returns pattern names, match counts, and confidence scores. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Filter patterns for this symbol"},minConfidence:{type:"number",description:"Minimum confidence score"},source:{type:"string",enum:["manual","suggested","imported","community"],description:"Filter by source"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_add_pattern",description:"Create a new failure pattern. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Pattern ID (kebab-case)"},name:{type:"string",description:"Human-readable name"},description:{type:"string",description:"What this pattern matches"},pattern:{type:"object",properties:{symbols:{type:"object",description:"Symbol criteria"},errorContains:{type:"array",items:{type:"string"},description:"Error keywords"},missingSignals:{type:"array",items:{type:"string"},description:"Expected missing signals"}}},resolution:{type:"object",properties:{description:{type:"string",description:"Resolution steps"},strategy:{type:"string",enum:["retry","fallback","fix-data","fix-code","ignore","escalate"]},priority:{type:"string",enum:["low","medium","high","critical"]},codeHint:{type:"string",description:"Code fix hint"}},required:["description","strategy"]},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"}},required:["id","name","pattern","resolution"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_record",description:"Manually record a new incident. ~100 tokens.",inputSchema:{type:"object",properties:{error:{type:"object",properties:{message:{type:"string",description:"Error message"},stack:{type:"string",description:"Stack trace"},code:{type:"string",description:"Error code"},type:{type:"string",description:"Error type"}},required:["message"]},symbols:{type:"object",properties:{feature:{type:"string"},component:{type:"string"},flow:{type:"string"},gate:{type:"string"},signal:{type:"string"},state:{type:"string"},integration:{type:"string"}}},environment:{type:"string",description:"Environment (required)"},service:{type:"string",description:"Service name"},version:{type:"string",description:"App version"},flowPosition:{type:"object",properties:{flowId:{type:"string"},expected:{type:"array",items:{type:"string"}},actual:{type:"array",items:{type:"string"}},missing:{type:"array",items:{type:"string"}},failedAt:{type:"string"}}}},required:["error","symbols","environment"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_sentinel_stats",description:"Get statistics and health metrics. Returns open/resolved counts, MTTR, and symbol breakdown. ~150 tokens.",inputSchema:{type:"object",properties:{period:{type:"string",description:"Period: 1d, 7d, 30d, 90d (default: 7d)"},symbol:{type:"string",description:"Get health for specific symbol"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_suggest_pattern",description:"Get AI suggestions for patterns based on incidents. ~200 tokens.",inputSchema:{type:"object",properties:{incidentId:{type:"string",description:"Suggest from specific incident"},minOccurrences:{type:"number",description:"Min similar incidents for suggestion"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_logs",description:"Query structured logs from connected apps. Filters by level, symbol, service, search text, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{level:{type:"string",enum:["debug","info","warn","error"],description:"Filter by log level"},symbol:{type:"string",description:"Filter by symbol (partial match)"},service:{type:"string",description:"Filter by service name"},search:{type:"string",description:"Search in log messages"},since:{type:"string",description:"ISO timestamp \u2014 logs after this time"},sessionId:{type:"string",description:"Filter by session ID"},correlationId:{type:"string",description:"Filter by correlation ID"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_services",description:"List all registered services with version, environment, and last-seen time. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_app_state",description:"Get live app state snapshots. Shows current state, active flows, and held gates for connected services. ~200 tokens.",inputSchema:{type:"object",properties:{service:{type:"string",description:"Filter by service name"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_validate_symbol",description:"Check if a symbol exists in the project index. Returns known/unknown status with suggestions for typos. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to validate (e.g., #checkout, ^auth)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_flow_activity",description:"Get recent flow events \u2014 which flow nodes were hit, in what order, by which service. ~200 tokens.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Filter by flow ID (e.g., $checkout-flow)"},service:{type:"string",description:"Filter by service name"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_metrics",description:"Query metrics (counters, gauges, histograms) from connected apps. Supports filtering and aggregation. ~200 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Metric name filter"},type:{type:"string",enum:["counter","gauge","histogram"],description:"Metric type filter"},service:{type:"string",description:"Service name filter"},since:{type:"string",description:"ISO timestamp \u2014 metrics after this time"},aggregate:{type:"boolean",description:"If true and name is provided, return aggregation (count/sum/min/max/avg) instead of raw data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_traces",description:"Query distributed traces across services. Shows span trees with timing, status, and service hops. ~200 tokens.",inputSchema:{type:"object",properties:{traceId:{type:"string",description:"Get a specific trace by ID"},service:{type:"string",description:"Filter by service name"},symbol:{type:"string",description:"Filter by symbol"},since:{type:"string",description:"ISO timestamp \u2014 traces after this time"},limit:{type:"number",description:"Max traces (default: 10, max: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_schemas",description:"List or get registered event schemas. Schemas define event types, scopes, causality, and visualization for application-agnostic observability. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Get a specific schema by ID. Omit to list all."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_events",description:"Query generic events from any registered schema. Filters by schema, event type, category, scope, service, severity, time range. ~200-400 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:'Filter by schema ID (e.g., "pretend-engine")'},eventType:{type:"string",description:'Filter by event type (e.g., "rule:fire")'},category:{type:"string",description:'Filter by category (e.g., "rules")'},service:{type:"string",description:"Filter by service name"},scopeValue:{type:"string",description:"Filter by scope value (e.g., frame number)"},severity:{type:"string",enum:["debug","info","warn","error"],description:"Filter by severity"},since:{type:"string",description:"ISO timestamp \u2014 events after this time"},search:{type:"string",description:"Full-text search in event data"},limit:{type:"number",description:"Max results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_sentinel_scopes",description:"Get scope summaries for a schema \u2014 e.g., frame list with event counts, request list with category breakdown. ~200 tokens.",inputSchema:{type:"object",properties:{schemaId:{type:"string",description:"Schema ID (required)"},sessionId:{type:"string",description:"Filter by session ID"},limit:{type:"number",description:"Max scopes (default: 50)"}},required:["schemaId"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ho(t,e,s){let n=xl(),i=new o$2(n);switch(t){case "paradigm_sentinel_triage":{let{symbol:r,status:o="all",environment:a,search:c,limit:l=10}=e,d=n.getRecentIncidents({limit:l,status:o,symbol:r,environment:a,search:c});if(d.length===0)return {handled:true,text:JSON.stringify({count:0,incidents:[],tip:"No incidents recorded yet. Incidents are created when errors occur in production or via paradigm_sentinel_record.",howToRecord:{description:"Record incidents manually with paradigm_sentinel_record",example:{error:{message:"Connection timeout",code:"ETIMEDOUT"},symbols:{feature:"@checkout",integration:"&stripe"},environment:"production"}}},null,2)};let u=d.map(g=>{let p=i.match(g,{maxResults:3});return {id:g.id,timestamp:g.timestamp,status:g.status,error:g.error.message,symbols:g.symbols,environment:g.environment,matches:p.map(m=>({patternId:m.pattern.id,name:m.pattern.name,confidence:m.confidence,strategy:m.pattern.resolution.strategy,description:m.pattern.resolution.description}))}});return {handled:true,text:JSON.stringify({count:u.length,incidents:u},null,2)}}case "paradigm_sentinel_show":{let{incidentId:r,includeTimeline:o,includeSimilar:a}=e,c=n.getIncident(r);if(!c)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let l=i.match(c,{maxResults:5}),d={incident:c,matches:l.map(u=>({patternId:u.pattern.id,name:u.pattern.name,confidence:u.confidence,matchedCriteria:u.matchedCriteria,resolution:u.pattern.resolution}))};if(o&&c.flowPosition){let u=new x().build(c);u&&(d.timeline=new x().renderStructured(u));}if(a){let u=n.getRecentIncidents({symbol:Object.values(c.symbols)[0],limit:5}).filter(g=>g.id!==r);d.similar=u.map(g=>({id:g.id,error:g.error.message,status:g.status}));}return {handled:true,text:JSON.stringify(d,null,2)}}case "paradigm_sentinel_resolve":{let{incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l,wontFix:d}=e;return n.getIncident(r)?d?(n.updateIncident(r,{status:"wont-fix",resolvedAt:new Date().toISOString(),resolvedBy:"manual",resolution:{notes:l}}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} marked as won't fix`})}):(n.recordResolution({incidentId:r,patternId:o,commitHash:a,prUrl:c,notes:l}),{handled:true,text:JSON.stringify({success:true,message:`Incident ${r} resolved`,patternId:o,commitHash:a,prUrl:c})}):{handled:true,text:JSON.stringify({error:`Incident ${r} not found`})}}case "paradigm_sentinel_patterns":{let{symbol:r,minConfidence:o,source:a}=e,c=n.getAllPatterns({source:a,minConfidence:o,includePrivate:false}),l=c;return r&&(l=c.filter(d=>{let u=d.pattern.symbols;return Object.values(u).some(g=>g?Array.isArray(g)?g.includes(r)||g.some(p=>r.match(p.replace("*",".*"))):g===r||r.match(g.replace("*",".*")):false)})),{handled:true,text:JSON.stringify({count:l.length,patterns:l.map(d=>({id:d.id,name:d.name,description:d.description,confidence:d.confidence.score,resolution:d.resolution,tags:d.tags}))},null,2)}}case "paradigm_sentinel_add_pattern":{let{id:r,name:o,description:a,pattern:c,resolution:l,tags:d}=e,u={id:r,name:o,description:a||"",pattern:{symbols:c.symbols||{},errorContains:c.errorContains,missingSignals:c.missingSignals},resolution:{description:l.description,strategy:l.strategy,priority:l.priority||"medium",codeHint:l.codeHint},source:"manual",private:false,tags:d||[]};return n.addPattern(u),{handled:true,text:JSON.stringify({success:true,message:`Pattern ${r} created`,pattern:u})}}case "paradigm_sentinel_record":{let{error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}=e,u=n.recordIncident({error:r,symbols:o,environment:a,service:c,version:l,flowPosition:d}),g=n.getIncident(u),p=g?i.match(g,{maxResults:3}):[];return {handled:true,text:JSON.stringify({success:true,incidentId:u,matches:p.map(m=>({patternId:m.pattern.id,confidence:m.confidence,resolution:m.pattern.resolution.description}))},null,2)}}case "paradigm_sentinel_stats":{let{period:r="7d",symbol:o}=e,a=new y(n);if(o){let u=a.getSymbolHealth(o);return {handled:true,text:JSON.stringify({symbol:o,health:u},null,2)}}let c=r.match(/^(\d+)d$/),l=c?parseInt(c[1],10):7,d=a.getStats(l);return {handled:true,text:JSON.stringify({period:`${l}d`,stats:d},null,2)}}case "paradigm_sentinel_suggest_pattern":{let{incidentId:r,minOccurrences:o}=e,a=new A(n);if(r){let l=n.getIncident(r);if(!l)return {handled:true,text:JSON.stringify({error:`Incident ${r} not found`})};let d=a.suggestFromIncident(l);return {handled:true,text:JSON.stringify({source:"incident",incidentId:r,suggestion:d},null,2)}}let c=a.findPatternCandidates(o||3);return {handled:true,text:JSON.stringify({source:"analysis",candidates:c.slice(0,5).map(l=>({occurrences:l.occurrenceCount,sampleIncidents:l.incidents.slice(0,3).map(d=>d.id),suggestion:l.suggestedPattern}))},null,2)}}case "paradigm_sentinel_logs":{let{level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:g=50}=e,p=n.queryLogs({level:r,symbol:o,service:a,search:c,since:l,sessionId:d,correlationId:u,limit:g}),m=n.getLogCount({level:r,symbol:o,service:a,since:l});return {handled:true,text:JSON.stringify({count:p.length,total:m,logs:p.map(f=>({timestamp:f.timestamp,level:f.level,symbol:f.symbol,service:f.service,message:f.message,data:f.data,sessionId:f.sessionId,correlationId:f.correlationId,durationMs:f.durationMs}))},null,2)}}case "paradigm_sentinel_services":{let r=n.getServices();return {handled:true,text:JSON.stringify({count:r.length,services:r.map(o=>({name:o.name,version:o.version,environment:o.environment,lastSeen:o.lastSeenAt,startedAt:o.startedAt,pid:o.pid}))},null,2)}}case "paradigm_sentinel_app_state":{let{service:r}=e,o=r?n.getAppState(r):n.getAllAppStates();return {handled:true,text:JSON.stringify({states:o.map(a=>({service:a.service,sessionId:a.sessionId,state:a.state,activeFlows:a.activeFlows,activeGates:a.activeGates,timestamp:a.timestamp}))},null,2)}}case "paradigm_sentinel_validate_symbol":{let{symbol:r}=e,o=n.getLogCount({symbol:r});return {handled:true,text:JSON.stringify({symbol:r,usedInLogs:o>0,logCount:o,tip:o===0?"This symbol has not appeared in any logs. It may be a typo or unused.":`This symbol has been used in ${o} log entries.`},null,2)}}case "paradigm_sentinel_flow_activity":{let{flowId:r,service:o,since:a}=e,l=n.queryLogs({symbol:r,service:o,since:a,limit:100}).filter(d=>["flow","signal","gate"].includes(d.symbolType)).map(d=>({timestamp:d.timestamp,symbol:d.symbol,symbolType:d.symbolType,service:d.service,message:d.message,level:d.level}));return {handled:true,text:JSON.stringify({count:l.length,events:l},null,2)}}case "paradigm_sentinel_metrics":{let{name:r,type:o,service:a,since:c,aggregate:l,limit:d}=e;if(l&&r){let g=n.aggregateMetric(r,{service:a,since:c});return {handled:true,text:JSON.stringify(g,null,2)}}let u=n.queryMetrics({name:r,type:o,service:a,since:c,limit:Math.min(d||50,100)});return {handled:true,text:JSON.stringify({count:u.length,metrics:u.map(g=>({timestamp:g.timestamp,name:g.name,type:g.type,value:g.value,tags:g.tags,service:g.service}))},null,2)}}case "paradigm_sentinel_traces":{let{traceId:r,service:o,symbol:a,since:c,limit:l}=e;if(r){let u=n.getTrace(r);return u?{handled:true,text:JSON.stringify(u,null,2)}:{handled:true,text:JSON.stringify({error:"Trace not found"})}}let d=n.queryTraces({service:o,symbol:a,since:c,limit:Math.min(l||10,20)});return {handled:true,text:JSON.stringify({count:d.length,traces:d.map(u=>({traceId:u.traceId,services:u.services,spanCount:u.spans.length,totalDurationMs:u.totalDurationMs,startTime:u.startTime,endTime:u.endTime}))},null,2)}}case "paradigm_sentinel_schemas":{let{id:r}=e;if(r){let a=n.getSchema(r);return a?{handled:true,text:JSON.stringify(a,null,2)}:{handled:true,text:JSON.stringify({error:`Schema "${r}" not found`})}}let o=n.listSchemas();return o.length===0?{handled:true,text:JSON.stringify({count:0,schemas:[],tip:"No event schemas registered yet. Applications register schemas via POST /api/schemas or SentinelWebClient.registerSchema()."},null,2)}:{handled:true,text:JSON.stringify({count:o.length,schemas:o.map(a=>({id:a.id,version:a.version,name:a.name,description:a.description,eventTypeCount:a.eventTypes.length,scope:a.scope.label,tags:a.tags,registeredAt:a.registeredAt}))},null,2)}}case "paradigm_sentinel_events":{let{schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:g,limit:p}=e,m=n.queryEvents({schemaId:r,eventType:o,category:a,service:c,scopeValue:l,severity:d,since:u,search:g,limit:Math.min(p||50,100)});return m.length===0?{handled:true,text:JSON.stringify({count:0,events:[],tip:"No events found. Events are ingested via POST /api/events or SentinelWebClient.emit()."},null,2)}:{handled:true,text:JSON.stringify({count:m.length,events:m.map(f=>({id:f.id,schemaId:f.schemaId,eventType:f.eventType,category:f.category,timestamp:f.timestamp,scopeValue:f.scopeValue,service:f.service,severity:f.severity,data:f.data,parentEventId:f.parentEventId,depth:f.depth}))},null,2)}}case "paradigm_sentinel_scopes":{let{schemaId:r,sessionId:o,limit:a}=e,c=n.getEventScopes(r,{limit:Math.min(a||50,200),sessionId:o});return c.length===0?{handled:true,text:JSON.stringify({count:0,scopes:[],tip:`No scopes found for schema "${r}". Events with scope values are required.`},null,2)}:{handled:true,text:JSON.stringify({count:c.length,scopes:c},null,2)}}default:return {handled:false,text:""}}}b$1();var Cl=30*1e3,bo=new Map;async function dn(t){let e=q.resolve(t),s=bo.get(e);if(s&&Date.now()-s.loadedAt<Cl)return s.index;let n=await Rl(e);return n&&bo.set(e,{index:n,loadedAt:Date.now()}),n}async function Rl(t){let e=q.join(t,".paradigm","flow-index.json");if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch(s){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:s}),null}}function Pl(t,e){let s=t.symbolToFlows[e]||[],n=[];for(let i of s){let r=t.flows[i];if(!r)continue;let o=r.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of o){let l=r.steps.slice(c+1).map(d=>d.id);n.push({flowId:r.id,definedIn:r.definedIn,description:r.description,trigger:r.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:r.validation});}}return n}function pn(t,e){let s=Pl(t,e),n=new Set;for(let o of s)o.validation?.command&&n.add(o.validation.command);let i="low",r=s.reduce((o,a)=>o+a.downstreamSteps.length,0);return s.length>3||r>10?i="high":(s.length>1||r>3)&&(i="medium"),{symbol:e,totalFlows:s.length,impactLevel:i,affectedFlows:s,validationCommands:Array.from(n),suggestion:s.length>0?`Changes to ${e} may affect ${s.length} flow(s). ${n.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function wo(){return [{name:"paradigm_flows_affected",description:"Find flows affected by changes to a symbol. Returns flows that include the symbol in their steps, with downstream impact analysis and validation commands. Returns flow IDs, step positions, and validation commands. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol being modified (e.g., @tasks, ^project-member, !task-created)"},includeValidation:{type:"boolean",description:"Include validation commands in response (default: true)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_flow_check",description:"Check flow definition completeness \u2014 verifies that gates referenced in flows.yaml exist in portal.yaml and that required fields are present. Does not trace code execution paths.",inputSchema:{type:"object",properties:{flowId:{type:"string",description:"Specific flow ID to validate (e.g., $task-creation). If not provided, validates all flows."},checkImplementation:{type:"boolean",description:"Deep check: verify actions and signals exist in codebase (default: false)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function vo(t,e,s){switch(t){case "paradigm_flows_affected":{let{symbol:n,includeValidation:i=true}=e,r=await dn(s.rootDir);if(!r)return {handled:true,text:JSON.stringify({error:"Flow index not found",symbol:n,suggestion:"Run `paradigm scan` to generate the flow index. Ensure .purpose files contain flows definitions.",example:`
5
5
  flows:
6
6
  $task-creation:
7
7
  description: "Full task creation flow"
@@ -59,7 +59,7 @@ payloads:
59
59
  title: "New Task"
60
60
  description: "Task description"
61
61
  `},null,2)};if(!n){let c=vs(r);return {handled:true,text:JSON.stringify({available:c,usage:{getAllUsers:'paradigm_test_fixtures({ category: "users" })',getSpecificUser:'paradigm_test_fixtures({ category: "users", name: "admin" })',getAllPayloads:'paradigm_test_fixtures({ category: "payloads" })',getEverything:'paradigm_test_fixtures({ category: "all" })'}},null,2)}}if(i&&n!=="all"){let c=xo(r,n,i);if(!c){let d=vs(r);return {handled:true,text:JSON.stringify({error:`Fixture "${i}" not found in category "${n}"`,availableInCategory:d[n]||[]},null,2)}}return {handled:true,text:JSON.stringify(c,null,2)}}let o=ws(r,n);return {handled:true,text:JSON.stringify(o,null,2)}}default:return {handled:false,text:""}}}z();function mn(t,e,s={}){let{maxResults:n=20}=s,i=[],r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=[`rg -n --no-heading "${r}" "${t}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${r}" "${t}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of o)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return i;let c=a.trim().split(`
62
- `);for(let l of c.slice(0,n)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,u,g,p]=d,m=q.relative(t,u),f="unknown";m.includes(".purpose")||m.includes("portal.yaml")?f="purpose":p.includes("//")||p.includes("#")||p.includes("*")?f="comment":f="code",i.push({filePath:m,line:parseInt(g,10),content:p.trim().slice(0,200),context:f});}}return i}function jo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function fn(t,e,s){if(t!=="paradigm_ripple")return {handled:false,text:""};let{symbol:n,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h(s.index,n);if(!a){let x=Al(s.rootDir,n);return o(x.length,t),{handled:true,text:x}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,n),d=new Set([n]),u=new Map;function g(x,_){if(_>=c)return;let R=[];for(let I of x){if(d.has(I))continue;d.add(I);let P=k(s.index,I);for(let D of P)d.has(D.symbol)||R.push(D.symbol);}R.length>0&&(u.set(_+1,R),g(R,_+1));}g(l$1.map(x=>x.symbol),1);let p=new Set;for(let[,x]of u)for(let _ of x)_!==n&&!l$1.find(R=>R.symbol===_)&&p.add(_);let m=l(s.index,n),f=l$1.length+p.size,y="low";f>10?y="high":f>3&&(y="medium");let b=await dn(s.rootDir),h$1=null;if(b){let x=pn(b,n);x.totalFlows>0&&(x.impactLevel==="high"&&y==="low"?y="medium":x.impactLevel==="high"&&(y="high"),h$1={totalFlows:x.totalFlows,affectedFlows:x.affectedFlows.map(_=>({flowId:_.flowId,impactLevel:_.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${_.stepAffected.position}, affects ${_.downstreamSteps.length} downstream steps`})),validationSuggestion:x.validationCommands.length>0?`Run: ${x.validationCommands[0]}`:void 0});}let v=new Set([n,...l$1.map(x=>x.symbol),...p]),w=[];try{let x=i(s.index,"gate");for(let _ of x)v.has(_.symbol)&&w.push({gate:_.symbol,description:_.description});for(let _ of l$1)_.type==="gate"&&!w.find(R=>R.gate===_.symbol)&&w.push({gate:_.symbol,description:_.description});}catch{}let S={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:y,analysis:{directlyAffected:l$1.map(x=>({symbol:x.symbol,type:x.type,description:x.description})),indirectlyAffected:Array.from(p),indirectByLevel:Object.fromEntries(u),dependsOn:m.map(x=>({symbol:x.symbol,type:x.type}))},summary:{directCount:l$1.length,indirectCount:p.size,totalAffected:f,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Il(y)};h$1&&(S.affectedFlows=h$1),w.length>0&&(S.affectedGates=w),S.suggestedReviewScope=$l(y,l$1.length,p.size,w.length,h$1?.totalFlows??0);try{let x=await F(s.rootDir,n);x.length>0&&(S.personas_affected=x,x.length>2&&y==="low"&&(S.impact="medium"));}catch{}try{let x=R(s.rootDir,n);x.length>0&&(S.university_content_affected=x.map(_=>({id:_.id,title:_.title,type:_.type,stale:_.stale})));}catch{}if(r&&s.workspace){let x=io(s.workspace,n);if(x.length>0){S.workspaceImpact={siblings:x.map(R=>({project:R.project,references:R.references.map(I=>({symbol:I.symbol,type:I.type,description:I.description}))}))};let _=x.reduce((R,I)=>R+I.references.length,0);_>0&&y==="low"&&(S.impact="medium"),_>5&&(S.impact="high");}}let k$1=o$1==="concise"?{symbol:S.symbol,impact:S.impact,summary:S.summary}:S,C=JSON.stringify(k$1,null,2);return o(C.length,t),{handled:true,text:C}}function Al(t,e){let s=mn(t,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let n=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return n.length>10||s.length>20?r="high":(n.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:n.slice(0,10),totalFilesAffected:n.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Il(t){switch(t){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function $l(t,e,s,n,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),n>0&&r.push(`Verify ${n} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),t==="high"?r.push("Consider running full test suite before merging"):t==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}function To(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function yn(t,e,s){switch(t){case "paradigm_protocol_search":{let n=e.task,i=e.limit||3,r=await W(s.rootDir,n,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:n,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:n,matches:r.map(o=>({id:o.protocol.id,name:o.protocol.name,description:o.protocol.description,score:o.score,status:o.protocol.status,exemplar:o.protocol.exemplar,last_verified:o.protocol.last_verified,steps:o.protocol.steps.map(Fl)}))},null,2)}}case "paradigm_protocol_get":{let n=e.id,i=await U(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let r=Z(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let n=e.steps||[],i=await X(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:n,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let n=e.id,i=e.refresh,r={};e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.trigger!==void 0&&(r.trigger=e.trigger),e.tags!==void 0&&(r.tags=e.tags),e.symbols!==void 0&&(r.symbols=e.symbols),e.exemplar!==void 0&&(r.exemplar=e.exemplar),e.steps!==void 0&&(r.steps=e.steps);let o=await Y(s.rootDir,n,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:n,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${n}`})}}case "paradigm_protocol_validate":{let n=e.id;if(n){let a=await U(s.rootDir,n);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let c=Z(s.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let r=(await T(s.rootDir)).map(a=>{let c=Z(s.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),o={total:r.length,current:r.filter(a=>a.status==="current").length,stale:r.filter(a=>a.status==="stale").length,broken:r.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:r,health:o},null,2)}}default:return {handled:false,text:""}}}function Fl(t){let e={action:t.action};return t.target&&(e.target=t.target),t.template_from&&(e.template_from=t.template_from),t.reference&&(e.reference=t.reference),t.command&&(e.command=t.command),t.notes&&(e.notes=t.notes),e}j();var wt=null,ks=false;async function Ss(t){if(wt)ks||(await wt.ensureReady(),ks=true);else {let e=q.join(t,".paradigm","sentinel","sentinel.db");wt=new f$4(e),await wt.ensureReady(),ks=true;}return wt}async function Nl(t,e){return (await Ss(t)).recordPracticeEvent(e)}async function Oo(t,e){return (await Ss(t)).getPracticeEvents(e)}async function re(t,e){return (await Ss(t)).getComplianceRate(e)}async function vt(t,e){let s=["discovery","verification","testing","documentation","collaboration","security"],n=[];for(let i of s){let r=await re(t,{...e,habitCategory:i});r.total>0&&n.push({category:i,...r});}return n}async function Ao(t,e,s){let n=[];for(let i of e){let r=await Nl(t,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});n.push(r);}return n}function Io(){let t=process.env.PARADIGM_AUTHOR;if(t)return _s(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return _s(e)}catch{}try{let e=Fo.userInfo().username;if(e)return _s(e)}catch{}return "unknown"}function _s(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function No(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function kt(t,e,s){switch(t){case "paradigm_lore_search":{let n={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$2(s.rootDir,n);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)),entries:i.map($o)},null,2)}}case "paradigm_lore_record":{let{type:n,title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:g,duration_minutes:p,decisions:m,errors_encountered:f,learnings:y,verification:b,tags:h,meta:v,body:w,linked_lore:S,linked_tasks:k,linked_commits:C,confidence:x}=e,_$1;try{let j=new Date(Date.now()-2592e6).toISOString(),T=await re(s.rootDir,{dateFrom:j});if(T.total>0){let $=(await vt(s.rootDir,{dateFrom:j})).filter(F=>F.rate<60).map(F=>F.category);_$1={rate:T.rate,followed:T.followed,skipped:T.skipped,partial:T.partial,weakAreas:$.length>0?$:void 0};}}catch{}let R={id:"",type:n||"agent-session",timestamp:new Date().toISOString(),duration_minutes:p,author:Io(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:g,decisions:m,errors_encountered:f,learnings:y,verification:b,tags:h,meta:v||void 0,habit_compliance:_$1,body:w,linked_lore:S,linked_tasks:k,linked_commits:C,confidence:x!=null&&x>=0&&x<=1?x:void 0},I=await d$2(s.rootDir,R);j$1().setLastLoreEntryId(I);try{let j=process.env.PARADIGM_AGENT_ID;if(j&&o&&o.length>0){let{updateExpertiseFromLore:T}=await import('./agent-loader-XS6LIMUG.js');T(s.rootDir,j,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=_(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let j=e.stream,T=j==="auto"?Hl(e):j;try{if(T==="work-log"){let{recordWorkLog:A}=await import('./work-log-loader-J27XSFCE.js');A(s.rootDir,{agent:R.agent?.model||"unknown",summary:R.summary,outcome:R.verification?.status==="pass"?"pass":R.verification?.status==="fail"?"fail":"partial",files_modified:R.files_modified,symbols_touched:R.symbols_touched,commit:R.commit,linked_lore:R.id||I}),D="work-log";}else if(T==="journal"&&R.learnings?.length){let{recordJournalEntry:A}=await import('./journal-loader-EELDB4P2.js');for(let $ of R.learnings)A(R.agent?.model||"unknown",{trigger:"self_reflection",insight:$,project:s.projectName||"unknown",transferable:!1,linked_work_log:R.id||I});D="journal";}else if(T==="decision"&&R.decisions?.length){let{recordDecision:A}=await import('./decision-loader-4KMQVAXZ.js');for(let $ of R.decisions)A(s.rootDir,{title:$.decision.slice(0,100),decision:$.decision,rationale:$.rationale,participants:[{id:`agent/${R.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:R.symbols_touched,status:"active",linked_lore:R.id||I});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:I,type:n,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let n=e.limit||10,i=await c(s.rootDir),r=await a$2(s.rootDir,{limit:n}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of r){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map($o),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let n=e.id,i=await b$4(s.rootDir,n);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})}}case "paradigm_lore_update":{let n=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$4(s.rootDir,n,o);return {handled:true,text:JSON.stringify({success:a,id:n,message:a?"Lore entry updated":`Lore entry not found: ${n}`})}}case "paradigm_lore_assess":{let n=e.id,i=e.verdict,r=e.notes,o=await b$4(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})};let a={verdict:i,assessed_by:Io(),assessed_at:new Date().toISOString(),notes:r},c=await h$2(s.rootDir,n,a);try{let g=process.env.PARADIGM_AGENT_ID;if(g&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:p}=await import('./agent-loader-XS6LIMUG.js');p(s.rootDir,g,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,u=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:n,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:u,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${n}`})}}case "paradigm_lore_calibration":{let n={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$2(s.rootDir,n),r=i.filter(w=>w.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,u=0;for(let w of i){let S=w.assessment.verdict;c[S]++;let k=S==="correct"?1:S==="partial"?.5:0;l+=k,w.confidence!=null&&(d+=w.confidence,u+=Math.abs(k-w.confidence));}let g=o>0?l/o:0,p=a>0?d/a:null,m=a>0?l/o-d/a:null,f=a>0?1-u/a:null,y=e.groupBy,b;if(y&&o>0){let w=new Map;for(let S of i){let k=[];y==="symbol"?k=S.symbols_touched||[]:y==="tag"?k=S.tags||[]:y==="type"&&(k=[S.type||"agent-session"]);for(let C of k)w.has(C)||w.set(C,[]),w.get(C).push(S);}b=Array.from(w.entries()).map(([S,k])=>{let C=k.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},_=0,R=0,I=0;for(let P of k){let D=P.assessment.verdict;x[D]++;let j=D==="correct"?1:D==="partial"?.5:0;_+=j,P.confidence!=null&&(R+=P.confidence,I+=Math.abs(j-P.confidence));}return {key:S,total:k.length,accuracyRate:_/k.length,avgConfidence:C.length>0?R/C.length:null,calibrationScore:C.length>0?1-I/C.length:null,verdictBreakdown:x}}).sort((S,k)=>k.total-S.total);}let h=[],v=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return v&&h.push(v),f!=null&&(f>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(g*1e3)/1e3,avgConfidence:p!=null?Math.round(p*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let n=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,n);return {handled:true,text:JSON.stringify({success:r,id:n,message:r?"Lore entry deleted":`Lore entry not found: ${n}`})}}default:return {handled:false,text:""}}}function Hl(t){return t.task_ref||t.files_modified||t.commit?"work-log":t.learnings||t.confidence!==void 0?"journal":t.decisions?.some(s=>s.rationale)?"decision":"work-log"}function $o(t){return {id:t.id,type:t.type,title:t.title,summary:t.summary,author:t.author,agent:t.agent,timestamp:t.timestamp,duration_minutes:t.duration_minutes,symbols_touched:t.symbols_touched,verification:t.verification?.status,review:t.review?{completeness:t.review.completeness,quality:t.review.quality}:null,confidence:t.confidence??null,assessment:t.assessment?t.assessment.verdict:null,assessment_delta:t.assessment_delta??null,tags:t.tags}}function Ho(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function St(t,e,s){return t==="paradigm_captain_brief"?ql(e,s):t==="paradigm_captain_debrief"?Ml(e,s):{handled:false,text:""}}async function ql(t,e){let s=t.taskDescription,n=t.symbols||[],i=t.depth||"standard",r=q.join(e.rootDir,".paradigm"),o$1=q.join(r,".cid-session"),a=q.join(r,".cid-briefed");try{E.existsSync(a)&&E.unlinkSync(a);let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i};E.mkdirSync(r,{recursive:!0}),E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let c=Ll(s),l=[],d=new Set;for(let j of n)if(!d.has(j)){d.add(j);let T=Eo(j);l.push({id:j,type:T,description:"Provided as anchor symbol"});}let u=[];try{for(let j of c.slice(0,3)){let A=j$2(e.index,j).slice(0,5);for(let $ of A)if(!d.has($.symbol)){d.add($.symbol);let F=Wl($.type);l.push({id:$.symbol,type:F,description:$.description||"",file:$.file}),u.push($.symbol);}}}catch{}let g={directories:[],files:[]};try{let j=await on("paradigm_navigate",{intent:"context",task:s,response_format:"concise"},e);if(j.handled){let T=JSON.parse(j.text);if(T.files)for(let A of T.files){let $=typeof A=="string"?A:A.path||A.file||"";$&&g.files.push($);}if(T.directories)for(let A of T.directories){let $=typeof A=="string"?A:A.path||A.directory||"";$&&g.directories.push($);}if(T.symbols)for(let A of T.symbols){let $=typeof A=="string"?A:A.id;$&&!d.has($)&&(d.add($),l.push({id:$,type:Eo($),description:typeof A=="object"&&A.description||""}));}}}catch{}let p=new Set(g.directories);for(let j of g.files){let T=q.dirname(j);T&&T!=="."&&p.add(T);}let m=l.slice(0,i==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(i!=="quick"&&m.length>0)for(let j of m)try{let T=await fn("paradigm_ripple",{symbol:j.id,depth:2,response_format:"concise"},e);if(T.handled){let A=JSON.parse(T.text);if(A.analysis){for(let $ of A.analysis.directlyAffected||[]){let F=$.symbol||$;F&&!f.affectedSymbols.includes(F)&&f.affectedSymbols.push(F);}for(let $ of A.analysis.indirectlyAffected||[])$&&!f.affectedSymbols.includes($)&&f.affectedSymbols.push($);}if(A.affectedFlows?.affectedFlows)for(let $ of A.affectedFlows.affectedFlows){let F=$.flowId||$;F&&!f.affectedFlows.includes(F)&&f.affectedFlows.push(F);}if(A.affectedGates)for(let $ of A.affectedGates){let F=$.gate||$;F&&!f.affectedGates.includes(F)&&f.affectedGates.push(F);}A.impact==="high"&&(f.fragileSymbols.includes(j.id)||f.fragileSymbols.push(j.id));}}catch{}let y=[],b=Gl(s);if(b.length>0)try{let{handleGatesForRoute:j}=await import('./tools-4WKLLDFU.js').catch(()=>({handleGatesForRoute:null})),T=q.join(e.rootDir,"portal.yaml");if(E.existsSync(T)){let A=E.readFileSync(T,"utf8");for(let $ of b){let F=A.includes($);y.push({route:$,gate:"^authenticated",declared:F});}}else for(let A of b)y.push({route:A,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let h=[];if(i!=="quick"&&l.length>0)try{let j=l.slice(0,5).map(A=>A.id),T=await sn("paradigm_wisdom_context",{symbols:j,include_global:!0},e);if(T.handled){let A=JSON.parse(T.text);if(A.antipatterns)for(let $ of A.antipatterns.slice(0,3)){let F=$.pattern||$.description||$.text||String($);F&&!h.includes(F)&&h.push(F);}if(A.wisdom?.antipatterns)for(let $ of A.wisdom.antipatterns.slice(0,3)){let F=$.pattern||$.description||String($);F&&!h.includes(F)&&h.push(F);}}}catch{}let v={matched:false};try{let j=await yn("paradigm_protocol_search",{task:s,limit:1},e);if(j.handled){let T=JSON.parse(j.text),A=T.matches||T.protocols||T.results||[];if(A.length>0){let $=A[0];v={matched:!0,id:$.id,name:$.name||$.title,steps:($.steps||[]).slice(0,5).map(F=>typeof F=="string"?F:F.description||String(F))};}}}catch{}let w=[];if(i!=="quick")try{let j=l[0]?.id,T={limit:i==="deep"?5:3};j&&(T.symbol=j);let A=await kt("paradigm_lore_search",T,e);if(A.handled){let F=JSON.parse(A.text).entries||[];for(let G of F.slice(0,3))w.push({id:G.id,summary:(G.summary||G.title||"").slice(0,100),relevance:j?`Related to ${j}`:"Recent project history"});}}catch{}let S=Array.from(p),k=0;for(let j of S){let T=q.join(e.rootDir,j,".purpose");if(E.existsSync(T))try{E.readFileSync(T,"utf8").trim().length>50&&k++;}catch{}}let C=S.length>0?k/S.length:.5,x=Jl(C),_=Ul(C,x,S.length),R=f.affectedSymbols.length+g.files.length,I=R>20?"large":R>8?"medium":R>2?"small":"tiny",P={territory:{directories:S.slice(0,10),files:g.files.slice(0,10),estimatedScope:I},symbols:l.slice(0,10),blastRadius:f,gates:y,protocol:v,warnings:h,coverage:{score:C,label:x,note:_},loreRefs:w,renderedBrief:""};P.renderedBrief=Bl(P);try{let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i,coverageScore:C};E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let D=JSON.stringify(P,null,2);return o(D.length,"paradigm_captain_brief"),{handled:true,text:D}}async function Ml(t,e){let s=t.orchestrationId,n=t.sessionSummary,i=t.touchedFiles||[],r=t.newSymbols||[],o$1=t.notes,a=q.join(e.rootDir,".paradigm"),c=q.join(a,".cid-briefed"),l=q.join(a,".pending-review"),d=new Set;for(let _ of i){let R=q.dirname(_);R&&R!=="."&&d.add(R);}let u=0,g=d.size;for(let _ of d){let R=q.join(e.rootDir,_,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&u++;}catch{}}let p=g>0?u/g:1,m=[],f=[];for(let _ of d){let R=q.join(e.rootDir,_,".purpose"),I=q.join(e.rootDir,_),P=false;if(E.existsSync(R))try{P=E.readFileSync(R,"utf8").trim().length>50;}catch{}if(P){if(i.some(j=>q.dirname(j)===_&&r.length>0)){f.push(_);try{let j=JSON.stringify({path:_,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${s}: ${r.join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,j+`
62
+ `);for(let l of c.slice(0,n)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,u,g,p]=d,m=q.relative(t,u),f="unknown";m.includes(".purpose")||m.includes("portal.yaml")?f="purpose":p.includes("//")||p.includes("#")||p.includes("*")?f="comment":f="code",i.push({filePath:m,line:parseInt(g,10),content:p.trim().slice(0,200),context:f});}}return i}function jo(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function fn(t,e,s){if(t!=="paradigm_ripple")return {handled:false,text:""};let{symbol:n,depth:i$1=3,includeWorkspace:r=false,response_format:o$1}=e,a=h(s.index,n);if(!a){let x=Al(s.rootDir,n);return o(x.length,t),{handled:true,text:x}}let c=Math.min(Math.max(i$1||3,1),5),l$1=k(s.index,n),d=new Set([n]),u=new Map;function g(x,_){if(_>=c)return;let R=[];for(let I of x){if(d.has(I))continue;d.add(I);let P=k(s.index,I);for(let D of P)d.has(D.symbol)||R.push(D.symbol);}R.length>0&&(u.set(_+1,R),g(R,_+1));}g(l$1.map(x=>x.symbol),1);let p=new Set;for(let[,x]of u)for(let _ of x)_!==n&&!l$1.find(R=>R.symbol===_)&&p.add(_);let m=l(s.index,n),f=l$1.length+p.size,y="low";f>10?y="high":f>3&&(y="medium");let b=await dn(s.rootDir),h$1=null;if(b){let x=pn(b,n);x.totalFlows>0&&(x.impactLevel==="high"&&y==="low"?y="medium":x.impactLevel==="high"&&(y="high"),h$1={totalFlows:x.totalFlows,affectedFlows:x.affectedFlows.map(_=>({flowId:_.flowId,impactLevel:_.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${_.stepAffected.position}, affects ${_.downstreamSteps.length} downstream steps`})),validationSuggestion:x.validationCommands.length>0?`Run: ${x.validationCommands[0]}`:void 0});}let v=new Set([n,...l$1.map(x=>x.symbol),...p]),w=[];try{let x=i(s.index,"gate");for(let _ of x)v.has(_.symbol)&&w.push({gate:_.symbol,description:_.description});for(let _ of l$1)_.type==="gate"&&!w.find(R=>R.gate===_.symbol)&&w.push({gate:_.symbol,description:_.description});}catch{}let S={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:y,analysis:{directlyAffected:l$1.map(x=>({symbol:x.symbol,type:x.type,description:x.description})),indirectlyAffected:Array.from(p),indirectByLevel:Object.fromEntries(u),dependsOn:m.map(x=>({symbol:x.symbol,type:x.type}))},summary:{directCount:l$1.length,indirectCount:p.size,totalAffected:f,dependsOnCount:m.length,levelsAnalyzed:c},recommendation:Il(y)};h$1&&(S.affectedFlows=h$1),w.length>0&&(S.affectedGates=w),S.suggestedReviewScope=$l(y,l$1.length,p.size,w.length,h$1?.totalFlows??0);try{let x=await F(s.rootDir,n);x.length>0&&(S.personas_affected=x,x.length>2&&y==="low"&&(S.impact="medium"));}catch{}try{let x=R(s.rootDir,n);x.length>0&&(S.university_content_affected=x.map(_=>({id:_.id,title:_.title,type:_.type,stale:_.stale})));}catch{}if(r&&s.workspace){let x=io(s.workspace,n);if(x.length>0){S.workspaceImpact={siblings:x.map(R=>({project:R.project,references:R.references.map(I=>({symbol:I.symbol,type:I.type,description:I.description}))}))};let _=x.reduce((R,I)=>R+I.references.length,0);_>0&&y==="low"&&(S.impact="medium"),_>5&&(S.impact="high");}}let k$1=o$1==="concise"?{symbol:S.symbol,impact:S.impact,summary:S.summary}:S,C=JSON.stringify(k$1,null,2);return o(C.length,t),{handled:true,text:C}}function Al(t,e){let s=mn(t,e,{maxResults:20});if(s.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let n=[...new Set(s.map(o=>o.filePath))],i={};for(let o of s)i[o.context]=(i[o.context]||0)+1;let r="low";return n.length>10||s.length>20?r="high":(n.length>3||s.length>5)&&(r="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:r,analysis:{filesAffected:n.slice(0,10),totalFilesAffected:n.length,totalReferences:s.length,contextBreakdown:i,sampleReferences:s.slice(0,5).map(o=>({file:o.filePath,line:o.line,preview:o.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Il(t){switch(t){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function $l(t,e,s,n,i){let r=[];return e>0&&r.push(`Review ${e} direct dependent(s) for breaking changes`),s>0&&r.push(`Scan ${s} indirect dependent(s) for cascading effects`),n>0&&r.push(`Verify ${n} affected gate(s) still enforce correct auth/access`),i>0&&r.push(`Validate ${i} affected flow(s) end-to-end`),t==="high"?r.push("Consider running full test suite before merging"):t==="medium"&&r.push("Run targeted tests for affected components"),r.length===0&&r.push("No downstream dependents detected - safe to proceed"),r}function To(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function yn(t,e,s){switch(t){case "paradigm_protocol_search":{let n=e.task,i=e.limit||3,r=await W(s.rootDir,n,i);return r.length===0?{handled:true,text:JSON.stringify({count:0,task:n,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:r.length,task:n,matches:r.map(o=>({id:o.protocol.id,name:o.protocol.name,description:o.protocol.description,score:o.score,status:o.protocol.status,exemplar:o.protocol.exemplar,last_verified:o.protocol.last_verified,steps:o.protocol.steps.map(Fl)}))},null,2)}}case "paradigm_protocol_get":{let n=e.id,i=await U(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let r=Z(s.rootDir,i);return {handled:true,text:JSON.stringify({...i,freshness:{status:r.status,issues:r.issues}},null,2)}}case "paradigm_protocol_record":{let n=e.steps||[],i=await X(s.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:n,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:i,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let n=e.id,i=e.refresh,r={};e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),e.trigger!==void 0&&(r.trigger=e.trigger),e.tags!==void 0&&(r.tags=e.tags),e.symbols!==void 0&&(r.symbols=e.symbols),e.exemplar!==void 0&&(r.exemplar=e.exemplar),e.steps!==void 0&&(r.steps=e.steps);let o=await Y(s.rootDir,n,r,i===true);return {handled:true,text:JSON.stringify({success:o,id:n,refreshed:i===true,message:o?i?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${n}`})}}case "paradigm_protocol_validate":{let n=e.id;if(n){let a=await U(s.rootDir,n);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${n}`})};let c=Z(s.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let r=(await T(s.rootDir)).map(a=>{let c=Z(s.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),o={total:r.length,current:r.filter(a=>a.status==="current").length,stale:r.filter(a=>a.status==="stale").length,broken:r.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:r,health:o},null,2)}}default:return {handled:false,text:""}}}function Fl(t){let e={action:t.action};return t.target&&(e.target=t.target),t.template_from&&(e.template_from=t.template_from),t.reference&&(e.reference=t.reference),t.command&&(e.command=t.command),t.notes&&(e.notes=t.notes),e}j();var wt=null,ks=false;async function Ss(t){if(wt)ks||(await wt.ensureReady(),ks=true);else {let e=q.join(t,".paradigm","sentinel","sentinel.db");wt=new f$4(e),await wt.ensureReady(),ks=true;}return wt}async function Nl(t,e){return (await Ss(t)).recordPracticeEvent(e)}async function Oo(t,e){return (await Ss(t)).getPracticeEvents(e)}async function re(t,e){return (await Ss(t)).getComplianceRate(e)}async function vt(t,e){let s=["discovery","verification","testing","documentation","collaboration","security"],n=[];for(let i of s){let r=await re(t,{...e,habitCategory:i});r.total>0&&n.push({category:i,...r});}return n}async function Ao(t,e,s){let n=[];for(let i of e){let r=await Nl(t,{habitId:i.habitId,habitCategory:i.habitCategory,result:i.result,engineer:s.engineer,sessionId:s.sessionId,loreEntryId:s.loreEntryId,taskDescription:s.taskDescription,symbolsTouched:s.symbolsTouched,filesModified:s.filesModified,notes:i.notes});n.push(r);}return n}function Io(){let t=process.env.PARADIGM_AUTHOR;if(t)return _s(t);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return _s(e)}catch{}try{let e=Fo.userInfo().username;if(e)return _s(e)}catch{}return "unknown"}function _s(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function No(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, decision, milestone, etc.). Call after completing significant work. Returns the created entry ID and file path. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","decision","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function kt(t,e,s){switch(t){case "paradigm_lore_search":{let n={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},i=await a$2(s.rootDir,n);return {handled:true,text:JSON.stringify({count:i.length,filter:Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)),entries:i.map($o)},null,2)}}case "paradigm_lore_record":{let{type:n,title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:g,duration_minutes:p,decisions:m,errors_encountered:f,learnings:y,verification:b,tags:h,meta:v,body:w,linked_lore:S,linked_tasks:k,linked_commits:C,confidence:x}=e,_$1;try{let j=new Date(Date.now()-2592e6).toISOString(),T=await re(s.rootDir,{dateFrom:j});if(T.total>0){let $=(await vt(s.rootDir,{dateFrom:j})).filter(F=>F.rate<60).map(F=>F.category);_$1={rate:T.rate,followed:T.followed,skipped:T.skipped,partial:T.partial,weakAreas:$.length>0?$:void 0};}}catch{}let R={id:"",type:n||"agent-session",timestamp:new Date().toISOString(),duration_minutes:p,author:Io(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:i,summary:r,symbols_touched:o,symbols_created:a,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:g,decisions:m,errors_encountered:f,learnings:y,verification:b,tags:h,meta:v||void 0,habit_compliance:_$1,body:w,linked_lore:S,linked_tasks:k,linked_commits:C,confidence:x!=null&&x>=0&&x<=1?x:void 0},I=await d$1(s.rootDir,R);j$1().setLastLoreEntryId(I);try{let j=process.env.PARADIGM_AGENT_ID;if(j&&o&&o.length>0){let{updateExpertiseFromLore:T}=await import('./agent-loader-RJRVO5GQ.js');T(s.rootDir,j,{symbols_touched:o,confidence:x!=null&&x>=0&&x<=1?x:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=_(s.rootDir,c,l||[]));}catch{}let D;if(e.stream){let j=e.stream,T=j==="auto"?Hl(e):j;try{if(T==="work-log"){let{recordWorkLog:A}=await import('./work-log-loader-DL5GZ2BQ.js');A(s.rootDir,{agent:R.agent?.model||"unknown",summary:R.summary,outcome:R.verification?.status==="pass"?"pass":R.verification?.status==="fail"?"fail":"partial",files_modified:R.files_modified,symbols_touched:R.symbols_touched,commit:R.commit,linked_lore:R.id||I}),D="work-log";}else if(T==="journal"&&R.learnings?.length){let{recordJournalEntry:A}=await import('./journal-loader-GLH7XFTK.js');for(let $ of R.learnings)A(R.agent?.model||"unknown",{trigger:"self_reflection",insight:$,project:s.projectName||"unknown",transferable:!1,linked_work_log:R.id||I});D="journal";}else if(T==="decision"&&R.decisions?.length){let{recordDecision:A}=await import('./decision-loader-2XPZE4EZ.js');for(let $ of R.decisions)A(s.rootDir,{title:$.decision.slice(0,100),decision:$.decision,rationale:$.rationale,participants:[{id:`agent/${R.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:R.symbols_touched,status:"active",linked_lore:R.id||I});D="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:I,type:n,title:i,message:"Lore entry recorded successfully",...D?{stream:D}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let n=e.limit||10,i=await c$1(s.rootDir),r=await a$2(s.rootDir,{limit:n}),o={};for(let l of r)for(let d of l.symbols_touched)o[d]=(o[d]||0)+1;let a=Object.entries(o).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c={};for(let l of r){let d=l.author;c[d]||(c[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c[d].count++,l.agent&&(c[d].hasAgent=true),l.timestamp>c[d].lastActive&&(c[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:i||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:r.map($o),hotSymbols:a,authors:Object.entries(c).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let n=e.id,i=await b$4(s.rootDir,n);return i?{handled:true,text:JSON.stringify(i,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})}}case "paradigm_lore_update":{let n=e.id,{id:i,...r}=e,o={};for(let[c,l]of Object.entries(r))l!==void 0&&(o[c]=l);let a=await g$4(s.rootDir,n,o);return {handled:true,text:JSON.stringify({success:a,id:n,message:a?"Lore entry updated":`Lore entry not found: ${n}`})}}case "paradigm_lore_assess":{let n=e.id,i=e.verdict,r=e.notes,o=await b$4(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${n}`})};let a={verdict:i,assessed_by:Io(),assessed_at:new Date().toISOString(),notes:r},c=await h$2(s.rootDir,n,a);try{let g=process.env.PARADIGM_AGENT_ID;if(g&&c&&o.symbols_touched?.length){let{updateExpertiseFromAssessment:p}=await import('./agent-loader-RJRVO5GQ.js');p(s.rootDir,g,{symbols_touched:o.symbols_touched,verdict:i});}}catch{}let l=i==="correct"?1:i==="partial"?.5:0,d=o.confidence!=null?l-o.confidence:null,u=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:n,verdict:i,confidence:o.confidence??null,delta:d,deltaDescription:u,message:c?`Assessment recorded: ${i}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${n}`})}}case "paradigm_lore_calibration":{let n={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},i=await a$2(s.rootDir,n),r=i.filter(w=>w.confidence!=null),o=i.length,a=r.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,u=0;for(let w of i){let S=w.assessment.verdict;c[S]++;let k=S==="correct"?1:S==="partial"?.5:0;l+=k,w.confidence!=null&&(d+=w.confidence,u+=Math.abs(k-w.confidence));}let g=o>0?l/o:0,p=a>0?d/a:null,m=a>0?l/o-d/a:null,f=a>0?1-u/a:null,y=e.groupBy,b;if(y&&o>0){let w=new Map;for(let S of i){let k=[];y==="symbol"?k=S.symbols_touched||[]:y==="tag"?k=S.tags||[]:y==="type"&&(k=[S.type||"agent-session"]);for(let C of k)w.has(C)||w.set(C,[]),w.get(C).push(S);}b=Array.from(w.entries()).map(([S,k])=>{let C=k.filter(P=>P.confidence!=null),x={correct:0,partial:0,incorrect:0},_=0,R=0,I=0;for(let P of k){let D=P.assessment.verdict;x[D]++;let j=D==="correct"?1:D==="partial"?.5:0;_+=j,P.confidence!=null&&(R+=P.confidence,I+=Math.abs(j-P.confidence));}return {key:S,total:k.length,accuracyRate:_/k.length,avgConfidence:C.length>0?R/C.length:null,calibrationScore:C.length>0?1-I/C.length:null,verdictBreakdown:x}}).sort((S,k)=>k.total-S.total);}let h=[],v=o<5?`Low sample size (N=${o}). Stats may not be representative.`:o<15?`Moderate sample (N=${o}). Trends are directional, not conclusive.`:null;return v&&h.push(v),f!=null&&(f>=.9?h.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?h.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?h.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):h.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),m!=null&&(m>.15?h.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):m<-0.15&&h.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>o*.3&&o>=5&&h.push(`High error rate: ${c.incorrect}/${o} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:o,totalWithConfidence:a,accuracyRate:Math.round(g*1e3)/1e3,avgConfidence:p!=null?Math.round(p*1e3)/1e3:null,avgDelta:m!=null?Math.round(m*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...b?{groups:b}:{},insights:h},null,2)}}case "paradigm_lore_delete":{let n=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let r=await i$1(s.rootDir,n);return {handled:true,text:JSON.stringify({success:r,id:n,message:r?"Lore entry deleted":`Lore entry not found: ${n}`})}}default:return {handled:false,text:""}}}function Hl(t){return t.task_ref||t.files_modified||t.commit?"work-log":t.learnings||t.confidence!==void 0?"journal":t.decisions?.some(s=>s.rationale)?"decision":"work-log"}function $o(t){return {id:t.id,type:t.type,title:t.title,summary:t.summary,author:t.author,agent:t.agent,timestamp:t.timestamp,duration_minutes:t.duration_minutes,symbols_touched:t.symbols_touched,verification:t.verification?.status,review:t.review?{completeness:t.review.completeness,quality:t.review.quality}:null,confidence:t.confidence??null,assessment:t.assessment?t.assessment.verdict:null,assessment_delta:t.assessment_delta??null,tags:t.tags}}function Ho(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function St(t,e,s){return t==="paradigm_captain_brief"?ql(e,s):t==="paradigm_captain_debrief"?Ml(e,s):{handled:false,text:""}}async function ql(t,e){let s=t.taskDescription,n=t.symbols||[],i=t.depth||"standard",r=q.join(e.rootDir,".paradigm"),o$1=q.join(r,".cid-session"),a=q.join(r,".cid-briefed");try{E.existsSync(a)&&E.unlinkSync(a);let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i};E.mkdirSync(r,{recursive:!0}),E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let c=Ll(s),l=[],d=new Set;for(let j of n)if(!d.has(j)){d.add(j);let T=Eo(j);l.push({id:j,type:T,description:"Provided as anchor symbol"});}let u=[];try{for(let j of c.slice(0,3)){let A=j$2(e.index,j).slice(0,5);for(let $ of A)if(!d.has($.symbol)){d.add($.symbol);let F=Wl($.type);l.push({id:$.symbol,type:F,description:$.description||"",file:$.file}),u.push($.symbol);}}}catch{}let g={directories:[],files:[]};try{let j=await on("paradigm_navigate",{intent:"context",task:s,response_format:"concise"},e);if(j.handled){let T=JSON.parse(j.text);if(T.files)for(let A of T.files){let $=typeof A=="string"?A:A.path||A.file||"";$&&g.files.push($);}if(T.directories)for(let A of T.directories){let $=typeof A=="string"?A:A.path||A.directory||"";$&&g.directories.push($);}if(T.symbols)for(let A of T.symbols){let $=typeof A=="string"?A:A.id;$&&!d.has($)&&(d.add($),l.push({id:$,type:Eo($),description:typeof A=="object"&&A.description||""}));}}}catch{}let p=new Set(g.directories);for(let j of g.files){let T=q.dirname(j);T&&T!=="."&&p.add(T);}let m=l.slice(0,i==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(i!=="quick"&&m.length>0)for(let j of m)try{let T=await fn("paradigm_ripple",{symbol:j.id,depth:2,response_format:"concise"},e);if(T.handled){let A=JSON.parse(T.text);if(A.analysis){for(let $ of A.analysis.directlyAffected||[]){let F=$.symbol||$;F&&!f.affectedSymbols.includes(F)&&f.affectedSymbols.push(F);}for(let $ of A.analysis.indirectlyAffected||[])$&&!f.affectedSymbols.includes($)&&f.affectedSymbols.push($);}if(A.affectedFlows?.affectedFlows)for(let $ of A.affectedFlows.affectedFlows){let F=$.flowId||$;F&&!f.affectedFlows.includes(F)&&f.affectedFlows.push(F);}if(A.affectedGates)for(let $ of A.affectedGates){let F=$.gate||$;F&&!f.affectedGates.includes(F)&&f.affectedGates.push(F);}A.impact==="high"&&(f.fragileSymbols.includes(j.id)||f.fragileSymbols.push(j.id));}}catch{}let y=[],b=Gl(s);if(b.length>0)try{let{handleGatesForRoute:j}=await import('./tools-NNPANZRA.js').catch(()=>({handleGatesForRoute:null})),T=q.join(e.rootDir,"portal.yaml");if(E.existsSync(T)){let A=E.readFileSync(T,"utf8");for(let $ of b){let F=A.includes($);y.push({route:$,gate:"^authenticated",declared:F});}}else for(let A of b)y.push({route:A,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let h=[];if(i!=="quick"&&l.length>0)try{let j=l.slice(0,5).map(A=>A.id),T=await sn("paradigm_wisdom_context",{symbols:j,include_global:!0},e);if(T.handled){let A=JSON.parse(T.text);if(A.antipatterns)for(let $ of A.antipatterns.slice(0,3)){let F=$.pattern||$.description||$.text||String($);F&&!h.includes(F)&&h.push(F);}if(A.wisdom?.antipatterns)for(let $ of A.wisdom.antipatterns.slice(0,3)){let F=$.pattern||$.description||String($);F&&!h.includes(F)&&h.push(F);}}}catch{}let v={matched:false};try{let j=await yn("paradigm_protocol_search",{task:s,limit:1},e);if(j.handled){let T=JSON.parse(j.text),A=T.matches||T.protocols||T.results||[];if(A.length>0){let $=A[0];v={matched:!0,id:$.id,name:$.name||$.title,steps:($.steps||[]).slice(0,5).map(F=>typeof F=="string"?F:F.description||String(F))};}}}catch{}let w=[];if(i!=="quick")try{let j=l[0]?.id,T={limit:i==="deep"?5:3};j&&(T.symbol=j);let A=await kt("paradigm_lore_search",T,e);if(A.handled){let F=JSON.parse(A.text).entries||[];for(let G of F.slice(0,3))w.push({id:G.id,summary:(G.summary||G.title||"").slice(0,100),relevance:j?`Related to ${j}`:"Recent project history"});}}catch{}let S=Array.from(p),k=0;for(let j of S){let T=q.join(e.rootDir,j,".purpose");if(E.existsSync(T))try{E.readFileSync(T,"utf8").trim().length>50&&k++;}catch{}}let C=S.length>0?k/S.length:.5,x=Jl(C),_=Ul(C,x,S.length),R=f.affectedSymbols.length+g.files.length,I=R>20?"large":R>8?"medium":R>2?"small":"tiny",P={territory:{directories:S.slice(0,10),files:g.files.slice(0,10),estimatedScope:I},symbols:l.slice(0,10),blastRadius:f,gates:y,protocol:v,warnings:h,coverage:{score:C,label:x,note:_},loreRefs:w,renderedBrief:""};P.renderedBrief=Bl(P);try{let j={timestamp:new Date().toISOString(),taskDescription:s.slice(0,200),depth:i,coverageScore:C};E.writeFileSync(o$1,JSON.stringify(j,null,2),"utf8");}catch{}let D=JSON.stringify(P,null,2);return o(D.length,"paradigm_captain_brief"),{handled:true,text:D}}async function Ml(t,e){let s=t.orchestrationId,n=t.sessionSummary,i=t.touchedFiles||[],r=t.newSymbols||[],o$1=t.notes,a=q.join(e.rootDir,".paradigm"),c=q.join(a,".cid-briefed"),l=q.join(a,".pending-review"),d=new Set;for(let _ of i){let R=q.dirname(_);R&&R!=="."&&d.add(R);}let u=0,g=d.size;for(let _ of d){let R=q.join(e.rootDir,_,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&u++;}catch{}}let p=g>0?u/g:1,m=[],f=[];for(let _ of d){let R=q.join(e.rootDir,_,".purpose"),I=q.join(e.rootDir,_),P=false;if(E.existsSync(R))try{P=E.readFileSync(R,"utf8").trim().length>50;}catch{}if(P){if(i.some(j=>q.dirname(j)===_&&r.length>0)){f.push(_);try{let j=JSON.stringify({path:_,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${s}: ${r.join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,j+`
63
63
  `,"utf8");}catch{}}}else try{if(!E.existsSync(I))continue;let D=q.basename(_),j=zl(D,_,i);E.writeFileSync(R,j,"utf8"),m.push(_),f.push(_);try{let T=JSON.stringify({path:_,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${s}. Files: ${i.filter(A=>q.dirname(A)===_).join(", ")}`,timestamp:new Date().toISOString()});E.appendFileSync(l,T+`
64
64
  `,"utf8");}catch{}}catch{}}let y=0;for(let _ of d){let R=q.join(e.rootDir,_,".purpose");if(E.existsSync(R))try{E.readFileSync(R,"utf8").trim().length>50&&y++;}catch{}}let b=g>0?y/g:1,h="";try{let _=await kt("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${n.slice(0,80)}`,summary:n,symbols_touched:r,files_modified:i,tags:["arc:cid-debrief",`orch:${s}`],meta:{orchestrationId:s,coverageScore:{before:p,after:b},coverageAdded:m,...o$1?{notes:o$1}:{}}},e);if(_.handled){let R=JSON.parse(_.text);h=R.id||R.entry?.id||"";}}catch{}let v=false;try{let _={timestamp:new Date().toISOString(),sessionId:s,touchedFiles:i,coverageScore:b};E.mkdirSync(a,{recursive:!0}),E.writeFileSync(c,JSON.stringify(_,null,2),"utf8"),v=!0;}catch{}let w={taskDescription:n,orchestrationId:s,agentContributions:[],coverageDelta:{before:p,after:b},newSymbols:r,touchedFiles:i,notes:o$1||""};try{let _=q.join(a,"events","session-log.jsonl");if(E.existsSync(_)){let P=E.readFileSync(_,"utf8").split(`
65
65
  `).filter(j=>j.trim().length>0).slice(-50),D=new Map;for(let j of P)try{let T=JSON.parse(j),A=T.agentId||T.agent||T.role||"";if(!A)continue;D.has(A)||D.set(A,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let $=D.get(A),F=T.action||T.event||T.message||"";if(F&&$.contributions.push(String(F).slice(0,120)),Array.isArray(T.symbols))for(let Se of T.symbols)$.symbolsTouched.add(String(Se));let G=T.symbol||"";if(G&&$.symbolsTouched.add(G),Array.isArray(T.patterns))for(let Se of T.patterns)$.patternsObserved.includes(String(Se))||$.patternsObserved.push(String(Se));}catch{}for(let[j,T]of D.entries())w.agentContributions.push({agentId:j,contribution:T.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(T.symbolsTouched).slice(0,10),patternsObserved:T.patternsObserved.slice(0,5)});}}catch{}w.agentContributions.length===0&&w.agentContributions.push({agentId:"session",contribution:n.slice(0,200),symbolsTouched:r.slice(0,10),patternsObserved:[]});let S={coverageAdded:m,delegatedToDocumentor:f,loreEntryId:h,coverageScore:{before:p,after:b,delta:b-p},stopHookCleared:v,sessionInsights:w},k=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
@@ -339,10 +339,10 @@ Examples:
339
339
  - "Fix the login bug" \u2192 quick (greenlight or escalate)
340
340
  - "Add user authentication with JWT" \u2192 plan \u2192 architect + security + builder + tester
341
341
  - "Should I use soft delete or hard delete?" \u2192 plan \u2192 architect only (analysis)
342
- - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","compliance","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Jo(t,e,s){return t==="paradigm_orchestrate_inline"?Kl(e,s):t==="paradigm_agent_prompt"?Xl(e,s):{handled:false,text:""}}async function Kl(t,e){let s=t.task,n=t.mode||"execute",i=t.agents;try{let h=q.join(e.rootDir,".paradigm",".orchestrated");E.writeFileSync(h,new Date().toISOString(),"utf8");}catch{}let r=zo(e.rootDir);if(!r){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let o$1=b$8(e.rootDir);if(o$1&&r.agents){let h={};for(let[v,w]of Object.entries(r.agents))o$1.includes(v)&&(h[v]=w);r.agents=h;}let a=Rt(s),c=[];try{let{processPendingEvents:h,loadNominations:v}=await import('./nomination-engine-A24774W4.js');h(e.rootDir),c=v(e.rootDir,{pending_only:!0,limit:10}).filter(S=>S.urgency==="high"||S.urgency==="critical").map(S=>({agent:S.agent,urgency:S.urgency,brief:S.brief}));}catch{}let l=ad(s);if(n==="quick")return Ql(s,a,l,c,r,e);let d=ed(s,r.agents,i,l,r.orchestration);if(n==="plan"){let h=ld(s,r.agents),v=cd(d,l),w;try{let{loadNotebookEntries:_}=await import('./notebook-loader-CF52PNZC.js'),R=a.map(D=>D.replace(/^[#$^!~@&%?]/,"").toLowerCase()),I={},P=new Set;for(let D of d.stages)for(let j of D.agents){if(P.has(j.name))continue;P.add(j.name);let T=_(j.name,e.rootDir),A=R.length>0?_(j.name,e.rootDir,{concepts:R}):T;T.length>0&&(I[j.name]={totalEntries:T.length,relevantEntries:A.length});}Object.keys(I).length>0&&(w=I);}catch{}let S=d.stages.flatMap(_=>_.agents.map(R=>R.name)),k=Uo(S,r.agents),C=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,x=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:h,costPreview:v,...C?{collaborationGraph:C}:{},...w?{notebookKnowledge:w,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...C?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...w?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(x.length,"paradigm_orchestrate_inline"),{handled:true,text:x}}let u=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:v}=await import('./agent-loader-XS6LIMUG.js'),{loadDecisions:w}=await import('./decision-loader-4KMQVAXZ.js'),{loadJournalEntries:S}=await import('./journal-loader-EELDB4P2.js'),{loadNominations:k}=await import('./nomination-engine-A24774W4.js'),{loadAgentState:C}=await import('./agent-state-L7LCPRC3.js'),{loadNotebookEntries:x}=await import('./notebook-loader-CF52PNZC.js'),_=w(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),R=k(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),I=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let P of d.stages)for(let D of P.agents)if(!u.has(D.name)){let j=h(e.rootDir,D.name);if(j){if(!c$5(D.name,e.rootDir))continue;let T=S(D.name,{transferable:!0,limit:5}).map(G=>({trigger:G.trigger,insight:G.insight.slice(0,150)})),A=C(D.name,e.rootDir),$;try{let G=x(D.name,e.rootDir,I.length>0?{concepts:I}:void 0);if(G.length>0){let Se=G.sort((ue,Ue)=>Ue.confidence-ue.confidence||new Date(Ue.updated).getTime()-new Date(ue.updated).getTime()).slice(0,5);$=Se.map(ue=>({context:ue.context,snippet:ue.snippet,concepts:ue.concepts}));try{let{recordNotebookReference:ue}=await import('./session-work-log-6GKGUQ5C.js');ue(e.rootDir,D.name,Se.map(Ue=>Ue.id));}catch{}try{let{incrementApplied:ue}=await import('./notebook-loader-CF52PNZC.js');for(let Ue of Se)ue(D.name,Ue.id,e.rootDir);}catch{}}}catch{}let F=v(j,a,$,{recentDecisions:_,journalInsights:T,pendingNominations:R},A?{lastSession:A.lastSession,pendingWork:A.pendingWork,recentPatterns:A.recentPatterns,sessionsOnProject:A.sessionsOnProject}:void 0);if(j.permissions){let G=[`
342
+ - "Refactor the payment module" \u2192 plan \u2192 architect + builder`,inputSchema:{type:"object",properties:{task:{type:"string",description:'The task to orchestrate (e.g., "Build @payment-system with Stripe integration")'},mode:{type:"string",enum:["quick","plan","execute"],description:'Mode: "quick" for lightweight pre-check (advocate + reviewer), "plan" returns suggested agents and plan, "execute" returns prompts ready for Task tool'},agents:{type:"array",items:{type:"string"},description:'Optional: Override which agents to use (e.g., ["architect", "builder"])'}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["plan","coordinate","team","multi-agent","orchestrate","agents","spawn agents"]},{name:"paradigm_agent_prompt",description:"Get the complete prompt for a specific agent to execute a task. Use this when you need to spawn an agent via the Task tool with full context.",inputSchema:{type:"object",properties:{agent:{type:"string",enum:["advocate","architect","builder","compliance","tester","reviewer","security","documentor"],description:"The agent role to get prompt for"},task:{type:"string",description:"The specific task for this agent"},handoffContext:{type:"string",description:"Optional: Context passed from a previous agent"},previousAgent:{type:"string",description:"Optional: Name of the agent that handed off"}},required:["agent","task"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Jo(t,e,s){return t==="paradigm_orchestrate_inline"?Kl(e,s):t==="paradigm_agent_prompt"?Xl(e,s):{handled:false,text:""}}async function Kl(t,e){let s=t.task,n=t.mode||"execute",i=t.agents;try{let h=q.join(e.rootDir,".paradigm",".orchestrated");E.writeFileSync(h,new Date().toISOString(),"utf8");}catch{}let r=zo(e.rootDir);if(!r){let h=JSON.stringify({error:"No agents.yaml found",suggestion:"Run `paradigm team init` to set up multi-agent orchestration"},null,2);return o(h.length,"paradigm_orchestrate_inline"),{handled:true,text:h}}let o$1=b$8(e.rootDir);if(o$1&&r.agents){let h={};for(let[v,w]of Object.entries(r.agents))o$1.includes(v)&&(h[v]=w);r.agents=h;}let a=Rt(s),c=[];try{let{processPendingEvents:h,loadNominations:v}=await import('./nomination-engine-KNSOAT4W.js');h(e.rootDir),c=v(e.rootDir,{pending_only:!0,limit:10}).filter(S=>S.urgency==="high"||S.urgency==="critical").map(S=>({agent:S.agent,urgency:S.urgency,brief:S.brief}));}catch{}let l=ad(s);if(n==="quick")return Ql(s,a,l,c,r,e);let d=ed(s,r.agents,i,l,r.orchestration);if(n==="plan"){let h=ld(s,r.agents),v=cd(d,l),w;try{let{loadNotebookEntries:_}=await import('./notebook-loader-CENTDDUJ.js'),R=a.map(D=>D.replace(/^[#$^!~@&%?]/,"").toLowerCase()),I={},P=new Set;for(let D of d.stages)for(let j of D.agents){if(P.has(j.name))continue;P.add(j.name);let T=_(j.name,e.rootDir),A=R.length>0?_(j.name,e.rootDir,{concepts:R}):T;T.length>0&&(I[j.name]={totalEntries:T.length,relevantEntries:A.length});}Object.keys(I).length>0&&(w=I);}catch{}let S=d.stages.flatMap(_=>_.agents.map(R=>R.name)),k=Uo(S,r.agents),C=k.length>0?{edges:k,note:"Shows which agents hand off to which based on agents.yaml handoff_to. Stage ordering was derived from this graph."}:void 0,x=JSON.stringify({task:s,mode:"plan",classification:{type:l.type,complexity:l.complexity,securityRequired:l.securityRequired,costMultiplier:l.costMultiplier},plan:d,suggestedAgents:h,costPreview:v,...C?{collaborationGraph:C}:{},...w?{notebookKnowledge:w,notebookNote:"Agents with relevant notebook entries will have curated knowledge injected into their prompts during execute mode."}:{},...c.length>0?{activeNominations:c,nominationNote:`${c.length} high-urgency agent nomination(s) pending. These agents have been flagged by the system for attention on this project.`}:{},instructions:["Review task classification and cost preview above","Review suggested agents based on task triggers",...C?["Review collaboration graph \u2014 stage ordering was derived from agent handoff_to edges"]:[],...w?["Review notebook knowledge \u2014 agents with relevant entries will receive curated snippets in execute mode"]:[],...c.length>0?["Review active nominations \u2014 agents flagged by the system may need to be included"]:[],'Call again with mode="execute" to get full prompts and execution strategy',"Stages marked canRunParallel: true can be launched simultaneously","After each agent completes, pass handoff context to the next stage"]},null,2);return o(x.length,"paradigm_orchestrate_inline"),{handled:true,text:x}}let u=new Map;try{let{loadAgentProfile:h,buildProfileEnrichment:v}=await import('./agent-loader-RJRVO5GQ.js'),{loadDecisions:w}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:S}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:k}=await import('./nomination-engine-KNSOAT4W.js'),{loadAgentState:C}=await import('./agent-state-KSQ3S7OB.js'),{loadNotebookEntries:x}=await import('./notebook-loader-CENTDDUJ.js'),_=w(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),R=k(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),I=a.map(P=>P.replace(/^[#$^!~@&%?]/,"").toLowerCase());for(let P of d.stages)for(let D of P.agents)if(!u.has(D.name)){let j=h(e.rootDir,D.name);if(j){if(!c$6(D.name,e.rootDir))continue;let T=S(D.name,{transferable:!0,limit:5}).map(G=>({trigger:G.trigger,insight:G.insight.slice(0,150)})),A=C(D.name,e.rootDir),$;try{let G=x(D.name,e.rootDir,I.length>0?{concepts:I}:void 0);if(G.length>0){let Se=G.sort((ue,Ue)=>Ue.confidence-ue.confidence||new Date(Ue.updated).getTime()-new Date(ue.updated).getTime()).slice(0,5);$=Se.map(ue=>({context:ue.context,snippet:ue.snippet,concepts:ue.concepts}));try{let{recordNotebookReference:ue}=await import('./session-work-log-BX434ZLK.js');ue(e.rootDir,D.name,Se.map(Ue=>Ue.id));}catch{}try{let{incrementApplied:ue}=await import('./notebook-loader-CENTDDUJ.js');for(let Ue of Se)ue(D.name,Ue.id,e.rootDir);}catch{}}}catch{}let F=v(j,a,$,{recentDecisions:_,journalInsights:T,pendingNominations:R},A?{lastSession:A.lastSession,pendingWork:A.pendingWork,recentPatterns:A.recentPatterns,sessionsOnProject:A.sessionsOnProject}:void 0);if(j.permissions){let G=[`
343
343
  ## Permission Constraints`];j.permissions.paths?.deny?.length&&G.push(`**Denied paths:** ${j.permissions.paths.deny.join(", ")}`),j.permissions.paths?.write?.length&&G.push(`**Writable paths:** ${j.permissions.paths.write.join(", ")}`),j.permissions.tools?.deny?.length&&G.push(`**Denied tools:** ${j.permissions.tools.deny.join(", ")}`),j.permissions.dangerous_actions?.length&&G.push(`**Requires approval for:** ${j.permissions.dangerous_actions.join(", ")}`),F+=`
344
344
  `+G.join(`
345
- `);}F.trim()&&u.set(D.name,{enrichment:F,nickname:j.nickname});}}}catch{}let g;try{let h=await St("paradigm_captain_brief",{taskDescription:s,symbols:a,depth:"standard"},e);h.handled&&(g=JSON.parse(h.text).renderedBrief);}catch{}let p=[];for(let h of d.stages){let v=[];for(let w of h.agents){let S=r.agents[w.name],k={name:S?.name||w.name,role:S?.role||xt[w.name]||`${w.name} agent`,focus:S?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Go(w.name,e.rootDir,S),triggers:S?.triggers,handoff_to:S?.handoff_to,context:S?.context,protocol:S?.protocol},C=u.get(w.name),x=Bo({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:C?.enrichment,nickname:C?.nickname,captainBrief:g});v.push(x);}p.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:v});}let m=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;dd(e.rootDir,m,s,d);try{let{appendSessionWorkEntry:h}=await import('./session-work-log-6GKGUQ5C.js');for(let v of p)for(let w of v.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-L7LCPRC3.js'),w=(await import('./session-tracker-VSFRNFRL.js')).default?.session?.sessionId||m;for(let S of p)for(let k of S.agents)h(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let f=`thr-orch-${m}`;try{let h=await import('./symphony-loader-RYFZOQJS.js'),v=q.basename(e.rootDir),w=`${v}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:v,role:"orchestrator"});let S=q.join(Fo.homedir(),".paradigm","score","threads"),k=E.readdirSync(S).filter(x=>x.endsWith(".json")).sort(),C=k[k.length-1];if(C){let x=q.join(S,C),_=q.join(S,`${f}.json`),R=JSON.parse(E.readFileSync(x,"utf8"));R.id=f,E.writeFileSync(_,JSON.stringify(R,null,2),"utf8"),x!==_&&E.unlinkSync(x);}for(let x of p)for(let _ of x.agents){let R=h.buildMessage({threadRoot:f,sender:{id:w,name:"Maestro",type:"agent",project:v,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${x.stage}: Assigned to ${_.attribution||_.agent} \u2014 ${_.taskDescription||s}`,symbols:a,metadata:{task:{stage:x.stage,canRunParallel:x.canRunParallel}}});h.routeMessage(R);}}catch{}let y={orchestrationId:m,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:p,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${m} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${m} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:p[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((h,v)=>({stage:v,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(w=>w.task).join(", ")}`,constraint:v===0?"Design/plan only \u2014 do NOT write implementation code":v===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:f,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${f}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${f}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:f,symbols:["#rate-limiter","^authenticated"]}}},b=JSON.stringify(y,null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}async function Ql(t,e,s,n,i,r){let o$1=t.toLowerCase(),a;try{let b=await St("paradigm_captain_brief",{taskDescription:t,symbols:e,depth:"quick"},r);if(b.handled){let h=JSON.parse(b.text);a={coverage:`${h.coverage?.label||"unknown"} (${Math.round((h.coverage?.score||0)*100)}%)`,warnings:h.warnings||[]};}}catch{}let c=[];s.securityRequired&&c.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&c.push(`high complexity task (type: ${s.type})`),e.length>=4&&c.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let l=n.filter(b=>b.urgency==="critical");l.length>0&&c.push(`${l.length} critical agent nomination(s) pending`);let d={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&d.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&d.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&d.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&d.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(d.risks.push("Gate symbols detected \u2014 authorization changes require security review"),c.some(b=>b.includes("security"))||c.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&d.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&d.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&d.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&d.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&d.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||d.questions.push("How will this be tested?"),e.length===0&&d.questions.push("No symbols referenced \u2014 which components are actually affected?");let u={concerns:[],suggestions:[]};for(let b of e){let h=b.replace(/^[#$^!~@&%?]/,"");!i.agents[h]&&b.startsWith("#");}s.costMultiplier.max>1&&u.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let g=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-CF52PNZC.js'),h=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),v=b("advocate",r.rootDir,h.length>0?{concepts:h}:void 0);v.length>0&&(g=v.sort((w,S)=>S.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let m=c.length>=2||c.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",f={mode:"quick",task:t,verdict:m,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...d.assumptions.length>0?{assumptions:d.assumptions}:{},...d.risks.length>0?{risks:d.risks}:{},...d.edgeCases.length>0?{edgeCases:d.edgeCases}:{},...d.questions.length>0?{questions:d.questions}:{},...g.length>0?{notebookInsights:g}:{}},reviewer:{agent:"reviewer",...u.concerns.length>0?{concerns:u.concerns}:{},...u.suggestions.length>0?{suggestions:u.suggestions}:{}},...c.length>0?{escalationSignals:c}:{},...n.length>0?{activeNominations:n}:{},...a?{captainBrief:a}:{},symbols:e,instructions:m==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",d.questions.length>0?`Address Jinx's questions during implementation: ${d.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${c.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(f,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function Xl(t,e){let s=t.agent,n=t.task,i=t.handoffContext,r=t.previousAgent,o$1=zo(e.rootDir),a=b$8(e.rootDir);if(a&&!a.includes(s)){let y=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||xt[s]||xt.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Go(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Rt(n),u,g;try{let{loadAgentProfile:y,buildProfileEnrichment:b}=await import('./agent-loader-XS6LIMUG.js'),{loadDecisions:h}=await import('./decision-loader-4KMQVAXZ.js'),{loadJournalEntries:v}=await import('./journal-loader-EELDB4P2.js'),{loadNominations:w}=await import('./nomination-engine-A24774W4.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CF52PNZC.js'),k=y(e.rootDir,s);if(k){g=k.nickname;let C=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=v(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),_=w(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),R;try{let P=d.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=S(s,e.rootDir,P.length>0?{concepts:P}:void 0);if(D.length>0){let j=D.sort((T,A)=>A.confidence-T.confidence||new Date(A.updated).getTime()-new Date(T.updated).getTime()).slice(0,5);R=j.map(T=>({context:T.context,snippet:T.snippet,concepts:T.concepts}));try{let{recordNotebookReference:T}=await import('./session-work-log-6GKGUQ5C.js');T(e.rootDir,s,j.map(A=>A.id));}catch{}}}catch{}let I=b(k,d,R,{recentDecisions:C,journalInsights:x,pendingNominations:_});if(k.permissions){let P=[`
345
+ `);}F.trim()&&u.set(D.name,{enrichment:F,nickname:j.nickname});}}}catch{}let g;try{let h=await St("paradigm_captain_brief",{taskDescription:s,symbols:a,depth:"standard"},e);h.handled&&(g=JSON.parse(h.text).renderedBrief);}catch{}let p=[];for(let h of d.stages){let v=[];for(let w of h.agents){let S=r.agents[w.name],k={name:S?.name||w.name,role:S?.role||xt[w.name]||`${w.name} agent`,focus:S?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Go(w.name,e.rootDir,S),triggers:S?.triggers,handoff_to:S?.handoff_to,context:S?.context,protocol:S?.protocol},C=u.get(w.name),x=Bo({agent:k,task:w.task,symbols:a,dependsOn:w.dependsOn,profileEnrichment:C?.enrichment,nickname:C?.nickname,captainBrief:g});v.push(x);}p.push({stage:h.stage,canRunParallel:h.canRunParallel,agents:v});}let m=`orch-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`;dd(e.rootDir,m,s,d);try{let{appendSessionWorkEntry:h}=await import('./session-work-log-BX434ZLK.js');for(let v of p)for(let w of v.agents)h(e.rootDir,{timestamp:new Date().toISOString(),type:"agent-contribution",agent:w.agent,contribution:w.taskDescription?.slice(0,200)||s.slice(0,200),attribution:w.attribution,symbols:a});}catch{}try{let{recordAgentSession:h}=await import('./agent-state-KSQ3S7OB.js'),w=(await import('./session-tracker-D2CH7RJF.js')).default?.session?.sessionId||m;for(let S of p)for(let k of S.agents)h(k.agent,e.rootDir,{sessionId:w,summary:`${k.attribution||k.agent}: ${(k.taskDescription||s).slice(0,200)}`,symbolsTouched:a});}catch{}let f=`thr-orch-${m}`;try{let h=await import('./symphony-loader-VA4UREOM.js'),v=q.basename(e.rootDir),w=`${v}/maestro`;try{h.getMyIdentity(e.rootDir)||h.registerAgent(e.rootDir,"maestro","Maestro (orchestrator)");}catch{}h.createThread(`Orchestration: ${s.slice(0,80)}`,{id:w,name:"Maestro",type:"agent",project:v,role:"orchestrator"});let S=q.join(Fo.homedir(),".paradigm","score","threads"),k=E.readdirSync(S).filter(x=>x.endsWith(".json")).sort(),C=k[k.length-1];if(C){let x=q.join(S,C),_=q.join(S,`${f}.json`),R=JSON.parse(E.readFileSync(x,"utf8"));R.id=f,E.writeFileSync(_,JSON.stringify(R,null,2),"utf8"),x!==_&&E.unlinkSync(x);}for(let x of p)for(let _ of x.agents){let R=h.buildMessage({threadRoot:f,sender:{id:w,name:"Maestro",type:"agent",project:v,role:"orchestrator"},intent:"task",text:`[Maestro] Stage ${x.stage}: Assigned to ${_.attribution||_.agent} \u2014 ${_.taskDescription||s}`,symbols:a,metadata:{task:{stage:x.stage,canRunParallel:x.canRunParallel}}});h.routeMessage(R);}}catch{}let y={orchestrationId:m,task:s,mode:"execute",symbols:a,totalAgents:d.estimatedAgents,...c.length>0?{activeNominations:c}:{},stages:p,executionInstructions:["Execute stages in order (stage 0, then stage 1, etc.)","Agents within a stage can be run in parallel if your environment supports it","Pass handoff context between stages",'Present each agent response as an attributed message using the attribution prefix (e.g., "[architect] Rate limiter should go before ^authenticated")',"Do NOT synthesize agent responses \u2014 show them as distinct contributions from each agent","After all agents in a stage complete, reconcile their outputs before proceeding to the next stage"],finalStep:{mandatory:true,description:"FINAL STEPS (mandatory, in order):",steps:[{order:1,action:"Call paradigm_captain_debrief",args:{orchestrationId:`${m} (use the orchestrationId from this response)`,sessionSummary:"(summarize what was accomplished)",touchedFiles:"(list all files modified during this session)",newSymbols:"(optional: list any new symbols registered)"}},{order:2,action:"Take the sessionInsights from the debrief result and call paradigm_ambient_learn_postflight",args:{sessionId:`${m} (use the orchestrationId from this response)`,context:"(pass the sessionInsights object from the debrief result here)"},note:"This is Loid's learning pass \u2014 she processes what the crew learned and ensures it compounds."},{order:3,action:"Session is complete."}],note:"Step 1 closes the session, updates .purpose coverage, records lore, and clears the stop hook. Step 2 runs Loid's learning pass on the session insights. Both steps are required \u2014 the session is NOT complete until both run."},claudeCode:{method:"Task tool",example:{description:p[0]?.agents[0]?.taskDescription||"Agent task",prompt:"(see agent prompts above)",subagent_type:"general-purpose"},parallel:"Launch multiple Task calls in one message for parallel stages"},sequential:{method:"Execute each role in sequence within this session",steps:d.stages.map((h,v)=>({stage:v,rolePrompt:`Adopt the ${h.agents[0]?.name} role. Focus ONLY on: ${h.agents.map(w=>w.task).join(", ")}`,constraint:v===0?"Design/plan only \u2014 do NOT write implementation code":v===d.stages.length-1?"Verify and test \u2014 do NOT change implementation":"Implement following the design from the previous stage"}))},cli:{method:"paradigm team orchestrate",command:`paradigm team orchestrate "${s}"`,note:"Spawns independent agent processes \u2014 works from any terminal"},symphony:{enabled:true,orchestrationThread:f,instructions:["After each agent completes, call paradigm_symphony_send to report progress. This makes the work visible in Conductor.",'Use intent "context" for analysis, "proposal" for recommendations, "decision" for decisions made',`Set threadRoot to "${f}" so all contributions are in one thread`,"Include the symbols array from the agent relay output"],perAgentInstruction:`When each agent finishes, run: paradigm_symphony_send threadId="${f}" intent="task-complete" text="[agentName] Summary of completed work" symbols=[touched symbols]`,exampleCall:{intent:"context",text:"[architect] Rate limiter should be placed before ^authenticated gate to prevent unauthenticated flood",threadRoot:f,symbols:["#rate-limiter","^authenticated"]}}},b=JSON.stringify(y,null,2);return o(b.length,"paradigm_orchestrate_inline"),{handled:true,text:b}}async function Ql(t,e,s,n,i,r){let o$1=t.toLowerCase(),a;try{let b=await St("paradigm_captain_brief",{taskDescription:t,symbols:e,depth:"quick"},r);if(b.handled){let h=JSON.parse(b.text);a={coverage:`${h.coverage?.label||"unknown"} (${Math.round((h.coverage?.score||0)*100)}%)`,warnings:h.warnings||[]};}}catch{}let c=[];s.securityRequired&&c.push("security-adjacent task (auth, gates, permissions detected)"),s.complexity==="high"&&c.push(`high complexity task (type: ${s.type})`),e.length>=4&&c.push(`${e.length} symbols in scope \u2014 cross-cutting change`);let l=n.filter(b=>b.urgency==="critical");l.length>0&&c.push(`${l.length} critical agent nomination(s) pending`);let d={assumptions:[],risks:[],edgeCases:[],questions:[]};(o$1.includes("simple")||o$1.includes("just")||o$1.includes("only"))&&d.assumptions.push("Task framed as simple \u2014 verify no hidden complexity"),(o$1.includes("always")||o$1.includes("never"))&&d.assumptions.push("Absolute language detected \u2014 edge cases likely exist"),!o$1.includes("error")&&!o$1.includes("fail")&&!o$1.includes("invalid")&&d.assumptions.push("No error/failure handling mentioned \u2014 what happens when it fails?"),e.some(b=>b.startsWith("$"))&&d.risks.push("Flow symbols detected \u2014 multi-step changes have ordering/rollback risk"),e.some(b=>b.startsWith("^"))&&(d.risks.push("Gate symbols detected \u2014 authorization changes require security review"),c.some(b=>b.includes("security"))||c.push("gate symbols in scope \u2014 security review recommended")),s.matchedKeywords.some(b=>["migration","database","schema"].includes(b))&&d.risks.push("Data migration risk \u2014 irreversible changes need rollback plan"),s.matchedKeywords.some(b=>["delete","remove","drop"].includes(b))&&d.risks.push("Destructive operation \u2014 verify nothing depends on removed items"),(o$1.includes("add")||o$1.includes("new"))&&d.edgeCases.push("New feature \u2014 how does it interact with existing features?"),(o$1.includes("refactor")||o$1.includes("rename"))&&d.edgeCases.push("Refactor \u2014 all callers updated? Integration tests cover the change?"),(o$1.includes("fix")||o$1.includes("bug"))&&d.edgeCases.push("Bug fix \u2014 does the fix address the root cause or just the symptom?"),o$1.includes("test")||d.questions.push("How will this be tested?"),e.length===0&&d.questions.push("No symbols referenced \u2014 which components are actually affected?");let u={concerns:[],suggestions:[]};for(let b of e){let h=b.replace(/^[#$^!~@&%?]/,"");!i.agents[h]&&b.startsWith("#");}s.costMultiplier.max>1&&u.concerns.push(`Higher-than-average complexity (${s.costMultiplier.min}x-${s.costMultiplier.max}x baseline) \u2014 consider breaking into smaller tasks`);let g=[];try{let{loadNotebookEntries:b}=await import('./notebook-loader-CENTDDUJ.js'),h=e.map(w=>w.replace(/^[#$^!~@&%?]/,"").toLowerCase()),v=b("advocate",r.rootDir,h.length>0?{concepts:h}:void 0);v.length>0&&(g=v.sort((w,S)=>S.confidence-w.confidence).slice(0,3).map(w=>w.snippet));}catch{}let m=c.length>=2||c.some(b=>b.includes("security")||b.includes("critical"))?"escalate":"greenlight",f={mode:"quick",task:t,verdict:m,classification:{type:s.type,complexity:s.complexity,securityRequired:s.securityRequired},advocate:{agent:"Jinx (advocate)",...d.assumptions.length>0?{assumptions:d.assumptions}:{},...d.risks.length>0?{risks:d.risks}:{},...d.edgeCases.length>0?{edgeCases:d.edgeCases}:{},...d.questions.length>0?{questions:d.questions}:{},...g.length>0?{notebookInsights:g}:{}},reviewer:{agent:"reviewer",...u.concerns.length>0?{concerns:u.concerns}:{},...u.suggestions.length>0?{suggestions:u.suggestions}:{}},...c.length>0?{escalationSignals:c}:{},...n.length>0?{activeNominations:n}:{},...a?{captainBrief:a}:{},symbols:e,instructions:m==="greenlight"?["Quick check passed \u2014 proceed with implementation.","Orchestration enforcement is satisfied.",d.questions.length>0?`Address Jinx's questions during implementation: ${d.questions.join("; ")}`:"No open questions from advocate."]:["Quick check recommends full orchestration.",`Escalation reasons: ${c.join("; ")}`,'Call paradigm_orchestrate_inline mode="plan" for full agent planning.',"Orchestration enforcement is satisfied regardless of verdict."]},y=JSON.stringify(f,null,2);return o(y.length,"paradigm_orchestrate_inline"),{handled:true,text:y}}async function Xl(t,e){let s=t.agent,n=t.task,i=t.handoffContext,r=t.previousAgent,o$1=zo(e.rootDir),a=b$8(e.rootDir);if(a&&!a.includes(s)){let y=JSON.stringify({warning:`Agent "${s}" is not on this project's roster`,suggestion:`Run paradigm_agent_activate id="${s}" to add it, or check .paradigm/roster.yaml`,activeRoster:a},null,2);return o(y.length,"paradigm_agent_prompt"),{handled:true,text:y}}let c=o$1?.agents[s],l={name:c?.name||s,role:c?.role||xt[s]||xt.builder,focus:c?.focus||{reads:["**/*"],writes:["**/*"]},defaultModel:Go(s,e.rootDir,c),triggers:c?.triggers,handoff_to:c?.handoff_to,context:c?.context,protocol:c?.protocol},d=Rt(n),u,g;try{let{loadAgentProfile:y,buildProfileEnrichment:b}=await import('./agent-loader-RJRVO5GQ.js'),{loadDecisions:h}=await import('./decision-loader-2XPZE4EZ.js'),{loadJournalEntries:v}=await import('./journal-loader-GLH7XFTK.js'),{loadNominations:w}=await import('./nomination-engine-KNSOAT4W.js'),{loadNotebookEntries:S}=await import('./notebook-loader-CENTDDUJ.js'),k=y(e.rootDir,s);if(k){g=k.nickname;let C=h(e.rootDir,{status:"active",limit:5}).map(P=>({title:P.title,decision:P.decision.slice(0,150)})),x=v(s,{transferable:!0,limit:5}).map(P=>({trigger:P.trigger,insight:P.insight.slice(0,150)})),_=w(e.rootDir,{pending_only:!0,limit:10}).map(P=>({urgency:P.urgency,brief:P.brief})),R;try{let P=d.map(j=>j.replace(/^[#$^!~@&%?]/,"").toLowerCase()),D=S(s,e.rootDir,P.length>0?{concepts:P}:void 0);if(D.length>0){let j=D.sort((T,A)=>A.confidence-T.confidence||new Date(A.updated).getTime()-new Date(T.updated).getTime()).slice(0,5);R=j.map(T=>({context:T.context,snippet:T.snippet,concepts:T.concepts}));try{let{recordNotebookReference:T}=await import('./session-work-log-BX434ZLK.js');T(e.rootDir,s,j.map(A=>A.id));}catch{}}}catch{}let I=b(k,d,R,{recentDecisions:C,journalInsights:x,pendingNominations:_});if(k.permissions){let P=[`
346
346
  ## Permission Constraints`];k.permissions.paths?.deny?.length&&P.push(`**Denied paths:** ${k.permissions.paths.deny.join(", ")}`),k.permissions.paths?.write?.length&&P.push(`**Writable paths:** ${k.permissions.paths.write.join(", ")}`),k.permissions.tools?.deny?.length&&P.push(`**Denied tools:** ${k.permissions.tools.deny.join(", ")}`),k.permissions.dangerous_actions?.length&&P.push(`**Requires approval for:** ${k.permissions.dangerous_actions.join(", ")}`),I+=`
347
347
  `+P.join(`
348
348
  `);}I.trim()&&(u=I);}}catch{}let p=Bo({agent:l,task:n,symbols:d,handoffContext:i,previousAgent:r,profileEnrichment:u,nickname:g}),m={agent:s,model:p.model,prompt:p.prompt,attribution:p.attribution,taskToolParams:{description:p.taskDescription,prompt:p.prompt,subagent_type:p.subagentType,model:p.model},focusAreas:p.focusAreas,usage:"Use the Task tool with the taskToolParams to spawn this agent. Present the response with the attribution prefix."},f=JSON.stringify(m,null,2);return o(f.length,"paradigm_agent_prompt"),{handled:true,text:f}}function Uo(t,e){let s=new Set(t),n=[];for(let i of t){let r=e[i];if(r?.handoff_to)for(let o of r.handoff_to)s.has(o)&&n.push({from:i,to:o});}return n}function Zl(t,e){let s=Uo(t,e);if(s.length===0)return null;let n=new Set,i=new Set(s.map(g=>`${g.from}->${g.to}`));for(let g of s)if(i.has(`${g.to}->${g.from}`)){let p=[g.from,g.to].sort().join(",");n.add(p);}let r=new Map;for(let g of n){let[p,m]=g.split(","),f=r.get(p)||p,y=r.get(m)||m,b=f<y?f:y;for(let[h,v]of r)(v===f||v===y)&&r.set(h,b);r.set(p,b),r.set(m,b);}for(let g of t)r.has(g)||r.set(g,g);let o=[...new Set(r.values())],a=new Map,c=new Map;for(let g of o)a.set(g,0),c.set(g,new Set);for(let g of s){let p=r.get(g.from),m=r.get(g.to);p!==m&&(c.get(p).has(m)||(c.get(p).add(m),a.set(m,(a.get(m)||0)+1)));}let l=new Map,d=[];for(let g of o)(a.get(g)||0)===0&&(d.push(g),l.set(g,0));for(;d.length>0;){let g=d.shift(),p=l.get(g)||0;for(let m of c.get(g)||[]){let f=(a.get(m)||1)-1;a.set(m,f);let y=p+1;l.set(m,Math.max(l.get(m)||0,y)),f===0&&d.push(m);}}if(l.size<o.length)return null;let u=new Map;for(let g of t){let p=r.get(g);u.set(g,l.get(p)||0);}return u}function ed(t,e,s,n,i){let r=Rt(t),o=t.toLowerCase(),a=[],c=[];if(s&&s.length>0)for(let w=0;w<s.length;w++){let S=s[w];e[S]&&c.push({name:S,task:`${S==="architect"?"Design":S==="builder"?"Implement":S==="tester"?"Test":"Process"}: ${t}`,dependsOn:w>0?[s[w-1]]:[],required:true,stage:w});}else {let w=o.includes("design")||o.includes("architect")||o.includes("plan")||o.includes("spec"),S=o.includes("auth")||o.includes("security")||o.includes("gate")||r.some(I=>I.startsWith("^")),k=o.includes("build")||o.includes("implement")||o.includes("create")||o.includes("add")||o.includes("fix"),C=o.includes("review")||o.includes("check"),x=o.includes("test")||o.includes("verify")||o.includes("validate");if(w&&e.architect&&c.push({name:"architect",task:`Design and specify: ${t}`,dependsOn:[],required:true,stage:0}),S&&e.security&&c.push({name:"security",task:`Review security aspects of: ${t}`,dependsOn:[],required:false,stage:0}),k&&e.builder){let I=w&&e.architect?["architect"]:[];c.push({name:"builder",task:`Implement: ${t}`,dependsOn:I,required:true,stage:I.length>0?1:0});}let _=c.some(I=>I.name==="builder"),R=_?2:w?1:0;if(C&&e.reviewer&&c.push({name:"reviewer",task:`Review: ${t}`,dependsOn:_?["builder"]:[],required:false,stage:R}),x&&e.tester&&c.push({name:"tester",task:`Test and validate: ${t}`,dependsOn:_?["builder"]:[],required:false,stage:R}),c.length===0){let I=n?.recommendedAgents||["architect","builder","tester"],P={architect:"Design",security:"Review security of",builder:"Implement",tester:"Test",reviewer:"Review"},D=0,j=null;for(let T of I){if(!e[T])continue;let A=j?[j]:[],$=P[T]||"Process",F=T==="architect"||T==="builder";c.push({name:T,task:`${$}: ${t}`,required:F,stage:D,dependsOn:A}),j=T,D++;}}}let l=c.map(w=>w.name),d=Zl(l,e);if(d)for(let w of c){w.stage=d.get(w.name)||0;let S=[];for(let k of l){if(k===w.name)continue;e[k]?.handoff_to?.includes(w.name)&&(d.get(k)||0)<w.stage&&S.push(k);}S.length>0&&(w.dependsOn=S);}let u=new Map;for(let w of c){let S=u.get(w.stage)||[];S.push(w),u.set(w.stage,S);}let g=Array.from(u.keys()).sort((w,S)=>w-S);for(let w of g){let S=u.get(w)||[];a.push({stage:w,agents:S.map(k=>({name:k.name,task:k.task,dependsOn:k.dependsOn,required:k.required})),canRunParallel:S.length>1});}let p=c.some(w=>w.name==="builder"||w.name==="tester"),f=n?.type==="analysis"||!p,y=false;if(!f){let w=g.length>0?g[g.length-1]+1:0;a.push({stage:w,agents:[{name:"documentor",task:"Review all changes made by previous agents. Update .purpose files, portal.yaml, and symbol registrations using only paradigm_purpose_* and paradigm_portal_* MCP tools. Run paradigm_reindex when done. Do NOT modify source code.",dependsOn:c.map(S=>S.name),required:true}],canRunParallel:false}),y=true;}let b=0,h=0;for(let w of c){let S=Vl[w.name]||{min:5e3,max:2e4};b+=S.min,h+=S.max;}y&&(b+=2e3,h+=8e3);let v=i?.default_mode||"faceted";return {task:t,mode:v,stages:a,symbols:r,estimatedAgents:c.length+(y?1:0),estimatedTokens:{min:b,max:h}}}function Bo(t){let{agent:e,task:s,symbols:n,handoffContext:i,previousAgent:r}=t,o=[];t.profileEnrichment&&(o.push(t.profileEnrichment),o.push("---"),o.push("")),t.captainBrief&&(o.push(t.captainBrief),o.push(""));let a=xt[e.name]||e.role||xt.builder;if(o.push(a),o.push(""),o.push("---"),o.push(""),o.push("## Your Task"),o.push(""),o.push(s),o.push(""),n.length>0){o.push("## Symbols in Scope"),o.push("");for(let u of n){let g=td(u);o.push(`- \`${u}\` (${g})`);}o.push("");}i&&(o.push("## Context from Previous Agent"),r&&o.push(`*Handed off from ${r}:*`),o.push(""),o.push(i),o.push("")),(e.focus?.reads||e.focus?.writes)&&(o.push("## Focus Areas"),o.push(""),o.push(`**Read from:** ${e.focus?.reads?.join(", ")||"**/*"}`),o.push(`**Write to:** ${e.focus?.writes?.join(", ")||"**/*"}`),o.push("")),o.push(`## Output Format
@@ -371,7 +371,7 @@ This structured output helps track progress and pass context between agents.`);l
371
371
  `)[0].trim(),color:d.color,appliesTo:d["applies-to"]}))),(o==="all"||o==="suggested")&&(c.suggested=(a.suggested||[]).map(l=>({tag:l.tag,reason:l.reason,proposedBy:l["proposed-by"],proposedAt:l["proposed-at"]}))),c.summary={coreCount:Object.keys(a.core||{}).length,projectCount:Object.keys(a.project||{}).length,suggestedCount:(a.suggested||[]).length},{handled:true,text:JSON.stringify(c,null,2)}}if(n==="search"){if(!i)return {handled:true,text:JSON.stringify({error:"Query required for search action"})};let c=i.toLowerCase(),l=[];for(let[d,u]of Object.entries(a.core||{}))(d.toLowerCase().includes(c)||u.description?.toLowerCase().includes(c)||u.aliases?.some(g=>g.toLowerCase().includes(c)))&&l.push({tag:d,category:"core",description:u.description?.split(`
372
372
  `)[0].trim()||""});for(let[d,u]of Object.entries(a.project||{}))(d.toLowerCase().includes(c)||u.description?.toLowerCase().includes(c)||u.aliases?.some(g=>g.toLowerCase().includes(c)))&&l.push({tag:d,category:"project",description:u.description?.split(`
373
373
  `)[0].trim()||""});return {handled:true,text:JSON.stringify({query:i,count:l.length,matches:l},null,2)}}if(n==="get"){if(!r)return {handled:true,text:JSON.stringify({error:"Tag name required for get action"})};if(a.core?.[r]){let l=a.core[r];return {handled:true,text:JSON.stringify({tag:r,category:"core",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}if(a.project?.[r]){let l=a.project[r];return {handled:true,text:JSON.stringify({tag:r,category:"project",description:l.description,color:l.color,appliesTo:l["applies-to"],aliases:l.aliases,requiresAspect:l["requires-aspect"]},null,2)}}let c=a.suggested?.find(l=>l.tag===r);return c?{handled:true,text:JSON.stringify({tag:r,category:"suggested",reason:c.reason,proposedBy:c["proposed-by"],proposedAt:c["proposed-at"],appliesTo:c["applies-to"],exampleSymbols:c["example-symbols"],status:"pending approval"},null,2)}:{handled:true,text:JSON.stringify({error:`Tag "${r}" not found`,suggestion:'Use paradigm_tags with action "list" to see available tags'})}}return {handled:true,text:JSON.stringify({error:`Unknown action: ${n}`})}}case "paradigm_tags_suggest":{let{tag:n,description:i,reason:r,appliesTo:o,exampleSymbols:a}=e,c=Yo(s.rootDir);if(!c)return {handled:true,text:JSON.stringify({error:"Tag bank not found",suggestion:"Create .paradigm/tags.yaml first"})};if(c.core?.[n]||c.project?.[n])return {handled:true,text:JSON.stringify({error:`Tag "${n}" already exists`,existing:c.core?.[n]?"core":"project"})};if(c.suggested?.some(d=>d.tag===n))return {handled:true,text:JSON.stringify({error:`Tag "${n}" is already in the suggested queue`,status:"pending approval"})};let l={tag:n,"proposed-by":"claude","proposed-at":new Date().toISOString(),reason:r,"applies-to":o||["#"],"example-symbols":a};return c.suggested||(c.suggested=[]),c.suggested.push(l),pd(s.rootDir,c),{handled:true,text:JSON.stringify({success:true,tag:n,status:"pending approval",message:"Tag suggestion added. Human review required before use.",nextSteps:["Human can approve via Sentinel UI or CLI",'Once approved, tag moves to "project" section',"Then AI can use the tag for classification"]},null,2)}}case "paradigm_aspect_check":{let{aspect:n}=e,i=n.startsWith("~")?n:`~${n}`,r=h(s.index,i);if(!r)return {handled:true,text:JSON.stringify({error:`Aspect "${i}" not found`,suggestion:"Use paradigm_search to find available aspects"})};if(r.type!=="aspect")return {handled:true,text:JSON.stringify({error:`Symbol "${i}" is not an aspect (type: ${r.type})`,note:"Only ~ symbols are aspects"})};let o=r.anchors||[],a=[];for(let m of o){let f=q.isAbsolute(m.path)?m.path:q.join(s.rootDir,m.path),y=E.existsSync(f),b;if(y)try{let v=E.readFileSync(f,"utf-8").split(`
374
- `);typeof m.lines=="number"?b=1:Array.isArray(m.lines)&&m.lines.length===2?b=m.lines[1]-m.lines[0]+1:Array.isArray(m.lines)&&(b=m.lines.length);}catch{}a.push({path:m.path,lines:m.raw.split(":")[1]||"full file",exists:y,lineCount:b});}let c=o.length>0&&a.every(m=>m.exists),l=r.appliesTo||[],d=n$2(s.index),u=[],g=[];for(let m of d)for(let f of l)if(new RegExp("^"+f.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(m.symbol)){u.push(m.symbol),(m.data?.aspects?.includes?.(i)||m.data?.aspects?.includes?.(n))&&g.push(m.symbol);break}let p=u.filter(m=>!g.includes(m));return {handled:true,text:JSON.stringify({aspect:i,valid:c,description:r.description,enforcement:r.enforcement,anchors:a,coverage:{appliesTo:l,matchingSymbols:u.length,symbolsWithAspect:g.length,missing:p.slice(0,10),missingCount:p.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(m=>!m.exists).map(m=>`Anchor file not found: ${m.path}`),...p.length>0?[`${p.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?p.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}var ud=["#","$","^","!","~"];function J(t){return t.length>1&&ud.includes(t[0])?t.slice(1):t}function M(t,e){let s=J(t);return `${e}${s}`}function ae(t,e){let s=q.isAbsolute(t)?t:q.resolve(e,t);return s.endsWith(".purpose")?s:q.join(s,".purpose")}function ce(t){if(!E.existsSync(t))return {};let e=a$9(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function le(t,e){let s=q.dirname(t);E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=b$b(e);E.writeFileSync(t,n,"utf8");}function He(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...i}=s;e[n]=i;}return e}function wn(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t)e[s.name]={description:s.description,steps:s.steps};return e}function Ze(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var gd={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Qo(t,e,s,n){let i=gd[n];if(!i)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let r=J(e),o=J(s),a=M(r,i),c=M(o,i),l=await c$4(t),d=[];for(let u of l){let g=ce(u),p=false,f={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(f&&f!=="flows"){let y=g[f];y&&!Array.isArray(y)&&r in y&&(y[o]=y[r],delete y[r],p=true);}if(i==="#")for(let y of ["features","components"]){let b=g[y];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],p=true);}i==="$"&&g.flows&&!Array.isArray(g.flows)&&r in g.flows&&(g.flows[o]=g.flows[r],delete g.flows[r],p=true);for(let y of ["features","components"]){let b=He(g[y]);for(let[h,v]of Object.entries(b))p=md(v,a,c)||p;p&&Object.keys(b).length>0&&(g[y]=b);}if(g.flows){let y=wn(g.flows);for(let[b,h]of Object.entries(y)){if(h.gates){let v=h.gates.indexOf(a);v!==-1&&(h.gates[v]=c,p=true);}if(h.signals){let v=h.signals.indexOf(a);v!==-1&&(h.signals[v]=c,p=true);}if(h.components){let v=h.components.indexOf(a);v!==-1&&(h.components[v]=c,p=true);}if(h.steps)for(let v of h.steps)typeof v=="object"&&"component"in v&&(v.component===a||v.component===r)&&(v.component=i==="#"?o:c,p=true);}p&&(g.flows=y);}if(g.gates){for(let[y,b]of Object.entries(g.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,p=true);}}if(g.aspects){for(let[y,b]of Object.entries(g.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,p=true);}}p&&(le(u,g),d.push(u));}return d}function md(t,e,s){let n=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=t[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let r=t.aspects.indexOf(e);r!==-1&&(t.aspects[r]=s,n=true);}return n}function kn(t){let e=q.join(t,"portal.yaml");if(!E.existsSync(e))return {data:{version:"1.0.0",gates:{}},filePath:e};let s=E.readFileSync(e,"utf8");return {data:be.load(s)||{version:"1.0.0",gates:{}},filePath:e}}function Zo(t,e){let s=be.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});E.writeFileSync(t,s,"utf8");}function ea(t,e){let{data:s,filePath:n}=kn(t);s.gates||(s.gates={});let i=J(e.id),r=s.gates[i]||{};return r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r,Zo(n,s),n}function ta(t,e){let{data:s,filePath:n}=kn(t);s.routes||(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(o=>`^${J(o)}`);return s.routes[i]=r,Zo(n,s),n}var fd={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},yd={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},hd={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},bd={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},wd={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},vd={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},kd={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Sd={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},_d={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},xd={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},Cd={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Rd={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},Pd={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function sa(){return [fd,yd,hd,bd,wd,vd,kd,Sd,_d,xd,Cd,Rd,Pd]}async function ia(t,e,s,n){switch(t){case "paradigm_purpose_init":return jd(e,s,n);case "paradigm_purpose_add_component":return Td(e,s,n);case "paradigm_purpose_add_aspect":return Dd(e,s,n);case "paradigm_purpose_add_signal":return Od(e,s,n);case "paradigm_purpose_add_flow":return Ad(e,s,n);case "paradigm_purpose_add_gate":return Id(e,s,n);case "paradigm_purpose_add_state":return $d(e,s,n);case "paradigm_purpose_link":return Fd(e,s,n);case "paradigm_purpose_remove":return Nd(e,s,n);case "paradigm_purpose_rename":return Ed(e,s,n);case "paradigm_portal_add_gate":return Hd(e,s,n);case "paradigm_portal_add_route":return qd(e,s,n);case "paradigm_purpose_validate":return Ld(e,s);default:return {handled:false,text:""}}}function Q(t){return {handled:true,text:JSON.stringify(t,null,2)}}function De(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function jd(t,e,s){let{purposeFile:n,name:i,description:r,context:o,version:a}=t,c=ae(n,e.rootDir),l=ce(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),le(c,l),await s(),Q({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function Td(t,e,s){let{purposeFile:n,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:u,gates:g,signals:p,aspects:m,components:f,type:y,parent:b}=t,h=ae(n,e.rootDir),v=ce(h),w=J(i),S=o,k=He(v[S]),C=k[w]||{description:""};return C.description=r,a!==void 0&&(C.file=a),c!==void 0&&(C.status=c),l!==void 0&&(C.endpoints=l),d!==void 0&&(C.tests=d),u!==void 0&&(C.flows=u.map(x=>M(x,"$"))),g!==void 0&&(C.gates=g.map(x=>M(x,"^"))),p!==void 0&&(C.signals=p.map(x=>M(x,"!"))),m!==void 0&&(C.aspects=m.map(x=>M(x,"~"))),f!==void 0&&(C.components=f.map(x=>M(x,"#"))),y!==void 0&&(C.type=y),b!==void 0&&(C.parent=M(b,"#")),k[w]=C,v[S]=k,le(h,v),await s(),Q({action:"add_component",file:h,section:S,id:w,symbol:`#${w}`})}async function Dd(t,e,s){let{purposeFile:n,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return De('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return De(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let u=ae(n,e.rootDir),g=q.dirname(u);for(let f of o){let y=f.replace(/:.*$/,""),b=q.resolve(g,y);if(!E.existsSync(b)){let h=q.resolve(e.rootDir,y);if(E.existsSync(h)){let v=q.relative(g,h),w=o.indexOf(f);o[w]=f.replace(y,v);}else return De(`Anchor file not found: "${y}". Anchors must be relative to the .purpose file directory (${g}).`)}}let p=ce(u);p.aspects||(p.aspects={});let m=J(i);return p.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},le(u,p),await s(),Q({action:"add_aspect",file:u,id:m,symbol:`~${m}`,anchors:o})}async function Od(t,e,s){let{purposeFile:n,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=t,u=ae(n,e.rootDir),g=ce(u);g.signals||(g.signals={});let p=J(i);return g.signals[p]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(m=>M(m,"#"))},...l&&{related:l},...d&&{data:d}},le(u,g),await s(),Q({action:"add_signal",file:u,id:p,symbol:`!${p}`})}async function Ad(t,e,s){let{purposeFile:n,id:i,description:r,gates:o,signals:a,components:c,steps:l}=t,d=ae(n,e.rootDir),u=ce(d),g=wn(u.flows),p=J(i),m={description:r,...o&&{gates:o.map(f=>M(f,"^"))},...a&&{signals:a.map(f=>M(f,"!"))},...c&&{components:c.map(f=>M(f,"#"))},...l&&{steps:l}};return g[p]=m,u.flows=g,le(d,u),await s(),Q({action:"add_flow",file:d,id:p,symbol:`$${p}`})}async function Id(t,e,s){let{purposeFile:n,id:i,description:r,requires:o,keys:a,signals:c}=t,l=ae(n,e.rootDir),d=ce(l);d.gates||(d.gates={});let u=J(i);return d.gates[u]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>M(g,"!"))}},le(l,d),await s(),Q({action:"add_gate",file:l,id:u,symbol:`^${u}`})}async function $d(t,e,s){let{purposeFile:n,id:i,description:r,type:o,default:a,properties:c}=t,l=ae(n,e.rootDir),d=ce(l);d.states||(d.states={});let u=J(i),g={description:r};return o!==void 0&&(g.type=o),a!==void 0&&(g.default=a),c!==void 0&&(g.properties=c),d.states[u]=g,le(l,d),await s(),Q({action:"add_state",file:l,id:u})}async function Fd(t,e,s){let{purposeFile:n,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=t,u=ae(n,e.rootDir),g=ce(u),p=J(i),m=r;if(!m){let h=He(g.components),v=He(g.features);if(p in h)m="components";else if(p in v)m="features";else return De(`Component "${p}" not found in components or features. Specify section explicitly.`)}let f=He(g[m]);if(!(p in f))return De(`Component "${p}" not found in ${m} section.`);let y=f[p];o&&(y.signals=Ze(y.signals,o.map(h=>M(h,"!")))),c&&(y.gates=Ze(y.gates,c.map(h=>M(h,"^")))),l&&(y.flows=Ze(y.flows,l.map(h=>M(h,"$")))),d&&(y.components=Ze(y.components,d.map(h=>M(h,"#")))),a&&(y.aspects=Ze(y.aspects,a.map(h=>M(h,"~")))),f[p]=y,g[m]=f,le(u,g),await s();let b=[];return o&&b.push(`signals: ${o.join(", ")}`),a&&b.push(`aspects: ${a.join(", ")}`),c&&b.push(`gates: ${c.join(", ")}`),l&&b.push(`flows: ${l.join(", ")}`),d&&b.push(`components: ${d.join(", ")}`),Q({action:"link",file:u,componentId:p,section:m,added:b})}async function Nd(t,e,s){let{purposeFile:n,section:i,id:r}=t,o=ae(n,e.rootDir),a=ce(o),c=J(r);if(i==="flows"){let l=wn(a.flows);if(!(c in l))return De(`Flow "${c}" not found in flows section.`);delete l[c],a.flows=l;}else if(i==="components"||i==="features"){let l=He(a[i]);if(!(c in l))return De(`"${c}" not found in ${i} section.`);delete l[c],a[i]=l;}else {let l=a[i];if(!l||!(c in l))return De(`"${c}" not found in ${i} section.`);delete l[c];}return le(o,a),await s(),Q({action:"remove",file:o,section:i,id:c})}async function Ed(t,e,s){let{oldId:n,newId:i,symbolType:r}=t,o=await Qo(e.rootDir,n,i,r);return await s(),Q({action:"rename",oldSymbol:`${r}${J(n)}`,newSymbol:`${r}${J(i)}`,filesModified:o.length,files:o})}async function Hd(t,e,s){let{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:u}=t,g=ea(e.rootDir,{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:u});await s();let p=J(n);return Q({action:"portal_add_gate",file:g,id:p,symbol:`^${p}`})}async function qd(t,e,s){let{route:n,method:i,gates:r}=t,o=ta(e.rootDir,{route:n,method:i,gates:r});return await s(),Q({action:"portal_add_route",file:o,route:`${i} ${n}`,gates:r})}var Md=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function na(t,e){let s=[];function n(r,o){if(typeof r=="string"){let a=r.match(Md);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let i=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&n(a.description,`${r.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let r=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Ld(t,e){let{purposeFile:s,includePortal:n=true}=t,i=[];if(s){let a=ae(s,e.rootDir),c=a$9(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$a(c.data,a);if(c.data.aspects)for(let[u,g]of Object.entries(c.data.aspects))(!g.anchors||g.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),l.valid=false);let d=na(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$4(e.rootDir);for(let c of a){let l=a$9(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(g=>({type:"error",message:g}))});continue}let d=d$a(l.data,c);if(l.data.aspects)for(let[g,p]of Object.entries(l.data.aspects))(!p.anchors||p.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${g}" is missing required anchors`,path:`aspects.${g}`}),d.valid=false);let u=na(l.data);d.issues.push(...u),i.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=kn(e.rootDir),l=[];if(a.gates)for(let[d,u]of Object.entries(a.gates))u.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),u.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return Q({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var ya=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],Bd=30*1e3,Ts=new Map;function ee(t){let e=q.resolve(t),s=Ts.get(e);if(s&&Date.now()-s.loadedAt<Bd)return s.habits;let n=zd(e);return Ts.set(e,{habits:n,loadedAt:Date.now()}),n}function zd(t){let e=new Map;for(let a of ya)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=la(q.join(s,".paradigm","habits.yaml"));n&&da(e,n);let i=pa(q.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=la(q.join(t,".paradigm","habits.yaml"));r&&da(e,r);let o=pa(q.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function la(t){if(!E.existsSync(t))return null;try{let e=E.readFileSync(t,"utf8");return be.load(e)}catch{return null}}function da(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let i=t.get(s);i&&(n.severity!==void 0&&(i.severity=n.severity),n.enabled!==void 0&&(i.enabled=n.enabled));}}function Yd(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function Ds(t){Ts.delete(q.resolve(t));}function pa(t){if(!E.existsSync(t))return [];try{let e=E.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let i=E.readFileSync(q.join(t,n),"utf8"),r=be.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var ua=["discovery","verification","testing","documentation","collaboration","security"],ga=["preflight","postflight","on-commit","on-stop"],ma=["advisory","warn","block"],fa=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],Vd=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Os(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Vd.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!ua.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${ua.join(", ")}`),t.trigger&&!ga.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${ga.join(", ")}`),t.severity&&!ma.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${ma.join(", ")}`),t.check){fa.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${fa.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Kd=new Set(ya.map(t=>t.id));function jn(t){return Kd.has(t)}function As(t,e,s="project"){let n=s==="global"?q.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):q.join(t,".paradigm","habits");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${e.id}.habit`),r=be.dump(e,{lineWidth:120,noRefs:true});return E.writeFileSync(i,r,"utf8"),Ds(t),i}function ha(t,e){if(jn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=q.join(t,".paradigm","habits",`${e}.habit`);if(E.existsSync(s))return E.unlinkSync(s),Ds(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",i=q.join(n,".paradigm","habits",`${e}.habit`);return E.existsSync(i)?(E.unlinkSync(i),Ds(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Is=0;function Dt(t,e,s,n,i){let r=Yd(t,e);n&&(r=r.filter(g=>!g.platforms||g.platforms.includes(n)));let o=0;if(i)try{let{isGraduated:g}=(Pn(),f$5(ca)),p=r.length;r=r.filter(m=>!g(i,m.id)),o=p-r.length;}catch{}Is=o;let a=r.map(g=>Qd(g,s)),c=a.filter(g=>g.result==="followed").length,l=a.filter(g=>g.result==="skipped").length,d=a.filter(g=>g.result==="partial").length,u=a.filter(g=>g.result==="skipped"&&g.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:u},blocksCompletion:u>0}}function Ot(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Qd(t,e){switch(t.check.type){case "tool-called":return Xd(t,e);case "file-exists":return Zd(t,e);case "file-modified":return ip(t,e);case "lore-recorded":return ep(t,e);case "symbols-registered":return tp(t,e);case "gates-declared":return np(t,e);case "tests-exist":return sp(t,e);case "git-clean":return rp(t,e);case "commit-message-format":return op(t,e);case "flow-coverage":return ap(t,e);case "context-checked":return cp(t,e);case "aspect-anchored":return lp(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Xd(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Zd(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function ep(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function tp(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function np(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function sp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function ip(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||q.basename(r)===o));return i.length>0?{habit:t,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(i=>s.some(r=>i.includes(r)||q.basename(i)===r));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function rp(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function op(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function ap(t,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function cp(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function lp(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var dp={"missing-purpose":t=>`${t.target?`"${t.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":t=>`${t.target?`"${t.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":t=>`${t.target?`"${t.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":t=>`${t.target?`"${t.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":t=>`${t.target?`"${t.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":t=>`${t.target?`"${t.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":t=>`${t.target?`"${t.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":t=>`${t.target?`"${t.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function pp(t,e){let s=dp[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function wa(t){let e=[],s=[],n=[];for(let o of t){let a=pp(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let i=e.length+s.length+n.length,r=up(e,s,n);return {gapCount:i,blocking:e,improvement:s,note:n,narrative:r}}function up(t,e,s){let n=[],i=t.length+e.length+s.length;if(i===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${i} gap${i!==1?"s":""} across ${ba(t,e,s)} check type${ba(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of t)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of e)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of s)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}return n.join(`
374
+ `);typeof m.lines=="number"?b=1:Array.isArray(m.lines)&&m.lines.length===2?b=m.lines[1]-m.lines[0]+1:Array.isArray(m.lines)&&(b=m.lines.length);}catch{}a.push({path:m.path,lines:m.raw.split(":")[1]||"full file",exists:y,lineCount:b});}let c=o.length>0&&a.every(m=>m.exists),l=r.appliesTo||[],d=n$2(s.index),u=[],g=[];for(let m of d)for(let f of l)if(new RegExp("^"+f.replace(/\*/g,".*").replace(/\?/g,".")+"$").test(m.symbol)){u.push(m.symbol),(m.data?.aspects?.includes?.(i)||m.data?.aspects?.includes?.(n))&&g.push(m.symbol);break}let p=u.filter(m=>!g.includes(m));return {handled:true,text:JSON.stringify({aspect:i,valid:c,description:r.description,enforcement:r.enforcement,anchors:a,coverage:{appliesTo:l,matchingSymbols:u.length,symbolsWithAspect:g.length,missing:p.slice(0,10),missingCount:p.length},warnings:[...o.length===0?["CRITICAL: Aspect has no anchors - aspects MUST have code anchors"]:[],...a.filter(m=>!m.exists).map(m=>`Anchor file not found: ${m.path}`),...p.length>0?[`${p.length} symbols match applies-to but don't have this aspect`]:[]],recommendation:c?p.length>0?"Aspect is valid but has coverage gaps - consider applying to matching symbols":"Aspect is valid and fully applied":"INVALID: Add code anchors to this aspect"},null,2)}}default:return {handled:false,text:""}}}var ud=["#","$","^","!","~"];function J(t){return t.length>1&&ud.includes(t[0])?t.slice(1):t}function M(t,e){let s=J(t);return `${e}${s}`}function ae(t,e){let s=q.isAbsolute(t)?t:q.resolve(e,t);return s.endsWith(".purpose")?s:q.join(s,".purpose")}function ce(t){if(!E.existsSync(t))return {};let e=a$9(t);if(!e.data)throw new Error(`Failed to parse ${t}: ${e.errors.join(", ")}`);return e.data}function le(t,e){let s=q.dirname(t);E.existsSync(s)||E.mkdirSync(s,{recursive:true});let n=b$b(e);E.writeFileSync(t,n,"utf8");}function He(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t){let{id:n,...i}=s;e[n]=i;}return e}function wn(t){if(!t)return {};if(!Array.isArray(t))return t;let e={};for(let s of t)e[s.name]={description:s.description,steps:s.steps};return e}function Ze(t,e){if(!e||e.length===0)return t;if(!t||t.length===0)return e;let s=new Set(t);for(let n of e)s.add(n);return Array.from(s)}var gd={"#":"#","^":"^","!":"!",$:"$","~":"~"};async function Qo(t,e,s,n){let i=gd[n];if(!i)throw new Error(`Invalid symbol type: ${n}. Expected one of: # ^ ! $ ~`);let r=J(e),o=J(s),a=M(r,i),c=M(o,i),l=await c$5(t),d=[];for(let u of l){let g=ce(u),p=false,f={"#":"components","^":"gates","!":"signals",$:"flows","~":"aspects"}[i];if(f&&f!=="flows"){let y=g[f];y&&!Array.isArray(y)&&r in y&&(y[o]=y[r],delete y[r],p=true);}if(i==="#")for(let y of ["features","components"]){let b=g[y];b&&!Array.isArray(b)&&r in b&&(b[o]=b[r],delete b[r],p=true);}i==="$"&&g.flows&&!Array.isArray(g.flows)&&r in g.flows&&(g.flows[o]=g.flows[r],delete g.flows[r],p=true);for(let y of ["features","components"]){let b=He(g[y]);for(let[h,v]of Object.entries(b))p=md(v,a,c)||p;p&&Object.keys(b).length>0&&(g[y]=b);}if(g.flows){let y=wn(g.flows);for(let[b,h]of Object.entries(y)){if(h.gates){let v=h.gates.indexOf(a);v!==-1&&(h.gates[v]=c,p=true);}if(h.signals){let v=h.signals.indexOf(a);v!==-1&&(h.signals[v]=c,p=true);}if(h.components){let v=h.components.indexOf(a);v!==-1&&(h.components[v]=c,p=true);}if(h.steps)for(let v of h.steps)typeof v=="object"&&"component"in v&&(v.component===a||v.component===r)&&(v.component=i==="#"?o:c,p=true);}p&&(g.flows=y);}if(g.gates){for(let[y,b]of Object.entries(g.gates))if(b.signals){let h=b.signals.indexOf(a);h!==-1&&(b.signals[h]=c,p=true);}}if(g.aspects){for(let[y,b]of Object.entries(g.aspects))if(b["applies-to"]){let h=b["applies-to"].indexOf(a);h!==-1&&(b["applies-to"][h]=c,p=true);}}p&&(le(u,g),d.push(u));}return d}function md(t,e,s){let n=false,i=["signals","gates","flows","components","states"];for(let r of i){let o=t[r];if(o){let a=o.indexOf(e);a!==-1&&(o[a]=s,n=true);}}if(t.aspects&&Array.isArray(t.aspects)){let r=t.aspects.indexOf(e);r!==-1&&(t.aspects[r]=s,n=true);}return n}function kn(t){let e=q.join(t,"portal.yaml");if(!E.existsSync(e))return {data:{version:"1.0.0",gates:{}},filePath:e};let s=E.readFileSync(e,"utf8");return {data:be.load(s)||{version:"1.0.0",gates:{}},filePath:e}}function Zo(t,e){let s=be.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false});E.writeFileSync(t,s,"utf8");}function ea(t,e){let{data:s,filePath:n}=kn(t);s.gates||(s.gates={});let i=J(e.id),r=s.gates[i]||{};return r.description=e.description,e.type!==void 0&&(r.type=e.type),e.location!==void 0&&(r.location=e.location),e.requires!==void 0&&(r.requires=e.requires),e.check!==void 0&&(r.check=e.check),e.grants!==void 0&&(r.grants=e.grants),e.emits!==void 0&&(r.emits=e.emits),e.prizes!==void 0&&(r.prizes=e.prizes),r.prizes||(r.prizes=[]),s.gates[i]=r,Zo(n,s),n}function ta(t,e){let{data:s,filePath:n}=kn(t);s.routes||(s.routes={});let i=`${e.method} ${e.route}`,r=e.gates.map(o=>`^${J(o)}`);return s.routes[i]=r,Zo(n,s),n}var fd={name:"paradigm_purpose_init",description:"Create or update file-level metadata on a .purpose file. Does NOT overwrite existing components/signals/etc \u2014 only touches top-level metadata (name, description, context, version). ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory (relative to project root)"},name:{type:"string",description:"Name/title for this purpose file"},description:{type:"string",description:"Description of what this directory/module does"},context:{type:"array",items:{type:"string"},description:"Context notes for AI agents"},version:{type:"string",description:'Version string (default: "1.0.0")'}},required:["purposeFile","name"]},annotations:{readOnlyHint:false,destructiveHint:false}},yd={name:"paradigm_purpose_add_component",description:"Add or update a component (#) or feature in a .purpose file. Strips # prefix from id automatically. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Component ID (e.g. "payment-service" or "#payment-service")'},description:{type:"string",description:"What this component does"},section:{type:"string",enum:["components","features"],description:'Which section to add to (default: "components")'},file:{type:"string",description:"Source file path for this component"},status:{type:"string",description:'Component status (e.g. "active", "deprecated")'},endpoints:{type:"array",items:{type:"string"},description:'API endpoints (e.g. ["POST /api/payments"])'},tests:{type:"array",items:{type:"string"},description:"Test file paths"},flows:{type:"array",items:{type:"string"},description:'Flow references (e.g. ["$checkout-flow"])'},gates:{type:"array",items:{type:"string"},description:'Gate references (e.g. ["^authenticated"])'},signals:{type:"array",items:{type:"string"},description:'Signal references (e.g. ["!payment-completed"])'},aspects:{type:"array",items:{type:"string"},description:'Aspect references (e.g. ["~audit-required"])'},components:{type:"array",items:{type:"string"},description:'Component references (e.g. ["#stripe-service"])'},type:{type:"string",description:'Component type (e.g., "view", "service", "model", "tool"). Open string per project vocabulary.'},parent:{type:"string",description:'Parent component (e.g., "#payment-page"). Establishes hierarchy.'}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},hd={name:"paradigm_purpose_add_aspect",description:'Add or update an aspect (~) with ENFORCED anchors. Anchors are required and must point to code locations. Strips ~ prefix automatically. This prevents the common "~aspect:name" format error. ~100 tokens.',inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Aspect ID (e.g. "audit-required" or "~audit-required")'},description:{type:"string",description:"What this aspect enforces"},anchors:{type:"array",items:{type:"string"},description:'REQUIRED. Code anchor locations (e.g. ["src/middleware/audit.ts:15-35"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g. ["compliance", "security"])'},appliesTo:{type:"array",items:{type:"string"},description:'Glob patterns for symbols this applies to (e.g. ["#*Service"])'},enforcement:{type:"string",description:'How this aspect is enforced (e.g. "middleware", "decorator")'}},required:["purposeFile","id","description","anchors"]},annotations:{readOnlyHint:false,destructiveHint:false}},bd={name:"paradigm_purpose_add_signal",description:"Add a signal (!) definition. Handles YAML ! quoting automatically. Strips ! prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Signal ID (e.g. "payment-completed" or "!payment-completed")'},description:{type:"string",description:"What this signal represents"},category:{type:"string",description:'Signal category (e.g. "business", "system", "security")'},severity:{type:"string",enum:["info","warn","error"],description:"Severity level"},emitters:{type:"array",items:{type:"string"},description:'Components that emit this signal (e.g. ["#payment-service"])'},related:{type:"array",items:{type:"string"},description:"Related signals or symbols"},data:{type:"object",description:"Schema/shape of data emitted with this signal"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},wd={name:"paradigm_purpose_add_flow",description:"Add a flow ($) definition. Strips $ prefix from id. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Flow ID (e.g. "checkout-flow" or "$checkout-flow")'},description:{type:"string",description:"What this flow does"},gates:{type:"array",items:{type:"string"},description:"Gate references in this flow"},signals:{type:"array",items:{type:"string"},description:"Signals emitted during this flow"},components:{type:"array",items:{type:"string"},description:"Components involved in this flow"},steps:{type:"array",items:{type:"object",properties:{component:{type:"string"},action:{type:"string"},description:{type:"string"}},required:["component","action"]},description:"Ordered steps in the flow"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},vd={name:"paradigm_purpose_add_gate",description:"Add a gate (^) to a .purpose file's gates section. This is for purpose-level gates, NOT portal.yaml. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},requires:{type:"array",items:{type:"string"},description:"Requirements for this gate"},keys:{type:"array",items:{type:"string"},description:"Key expressions for gate evaluation"},signals:{type:"array",items:{type:"string"},description:"Signals emitted by this gate (e.g. on pass/fail)"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},kd={name:"paradigm_purpose_add_state",description:"Add a state definition to a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},id:{type:"string",description:'State ID (e.g. "user-store")'},description:{type:"string",description:"What this state represents"},type:{type:"string",description:'Type of state (e.g. "object", "array", "string")'},default:{description:"Default value for the state"},properties:{type:"object",description:"State properties as {name: {type, description}}"}},required:["purposeFile","id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Sd={name:"paradigm_purpose_link",description:"Add references to an existing component without rewriting all fields. Merges into existing arrays (no clobber). Example: add ~rate-limited to #payment-service's aspects. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},componentId:{type:"string",description:"Component or feature ID to add references to"},section:{type:"string",enum:["components","features"],description:"Which section the component is in (default: auto-detect)"},signals:{type:"array",items:{type:"string"},description:"Signal references to add"},aspects:{type:"array",items:{type:"string"},description:"Aspect references to add"},gates:{type:"array",items:{type:"string"},description:"Gate references to add"},flows:{type:"array",items:{type:"string"},description:"Flow references to add"},components:{type:"array",items:{type:"string"},description:"Component references to add"}},required:["purposeFile","componentId"]},annotations:{readOnlyHint:false,destructiveHint:false}},_d={name:"paradigm_purpose_remove",description:"Remove any element by section + id from a .purpose file. ~100 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Path to .purpose file or parent directory"},section:{type:"string",enum:["components","features","gates","signals","aspects","flows","states"],description:"Which section to remove from"},id:{type:"string",description:"ID of the element to remove"}},required:["purposeFile","section","id"]},annotations:{readOnlyHint:false,destructiveHint:true}},xd={name:"paradigm_purpose_rename",description:"Rename a symbol across ALL .purpose files in the project. Updates both definitions and references. ~200 tokens.",inputSchema:{type:"object",properties:{oldId:{type:"string",description:'Current symbol ID (e.g. "payment-service")'},newId:{type:"string",description:'New symbol ID (e.g. "billing-service")'},symbolType:{type:"string",enum:["#","^","!","$","~"],description:"Symbol type prefix"}},required:["oldId","newId","symbolType"]},annotations:{readOnlyHint:false,destructiveHint:false}},Cd={name:"paradigm_portal_add_gate",description:"Add or update a gate (^) in portal.yaml. Creates portal.yaml if it doesn't exist. Strips ^ prefix. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Gate ID (e.g. "authenticated" or "^authenticated")'},description:{type:"string",description:"What this gate checks"},type:{type:"string",description:'Gate type (e.g. "auth", "role", "ownership")'},location:{type:"string",description:'Where the gate is checked in your code (e.g. "middleware", "route-handler")'},requires:{type:"array",items:{type:"string"},description:"Prerequisite gates"},check:{type:"string",description:'Expression to evaluate (e.g. "req.user != null")'},grants:{type:"array",items:{type:"string"},description:"What passing this gate grants access to"},emits:{type:"array",items:{type:"string"},description:"Signals emitted when gate is checked"},prizes:{type:"array",items:{type:"object",properties:{id:{type:"string"},oneTime:{type:"boolean"}},required:["id"]},description:"Side effects triggered on pass"}},required:["id","description"]},annotations:{readOnlyHint:false,destructiveHint:false}},Rd={name:"paradigm_portal_add_route",description:"Add a route with gates to portal.yaml. Creates routes section if needed. ~100 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:'Route path (e.g. "/api/users/:id")'},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},gates:{type:"array",items:{type:"string"},description:'Gate IDs to apply (e.g. ["^authenticated", "^user-owner"])'}},required:["route","method","gates"]},annotations:{readOnlyHint:false,destructiveHint:false}},Pd={name:"paradigm_purpose_validate",description:"Validate .purpose files and portal.yaml. Returns issues found. If no purposeFile specified, validates all files. ~200 tokens.",inputSchema:{type:"object",properties:{purposeFile:{type:"string",description:"Specific .purpose file to validate (validates all if omitted)"},includePortal:{type:"boolean",description:"Also validate portal.yaml (default: true)"}}},annotations:{readOnlyHint:true,destructiveHint:false}};function sa(){return [fd,yd,hd,bd,wd,vd,kd,Sd,_d,xd,Cd,Rd,Pd]}async function ia(t,e,s,n){switch(t){case "paradigm_purpose_init":return jd(e,s,n);case "paradigm_purpose_add_component":return Td(e,s,n);case "paradigm_purpose_add_aspect":return Dd(e,s,n);case "paradigm_purpose_add_signal":return Od(e,s,n);case "paradigm_purpose_add_flow":return Ad(e,s,n);case "paradigm_purpose_add_gate":return Id(e,s,n);case "paradigm_purpose_add_state":return $d(e,s,n);case "paradigm_purpose_link":return Fd(e,s,n);case "paradigm_purpose_remove":return Nd(e,s,n);case "paradigm_purpose_rename":return Ed(e,s,n);case "paradigm_portal_add_gate":return Hd(e,s,n);case "paradigm_portal_add_route":return qd(e,s,n);case "paradigm_purpose_validate":return Ld(e,s);default:return {handled:false,text:""}}}function Q(t){return {handled:true,text:JSON.stringify(t,null,2)}}function De(t){return {handled:true,text:JSON.stringify({error:t},null,2)}}async function jd(t,e,s){let{purposeFile:n,name:i,description:r,context:o,version:a}=t,c=ae(n,e.rootDir),l=ce(c);return a!==void 0?l.version=a:l.version||(l.version="1.0.0"),r!==void 0?l.description=r:l.description||(l.description=i),o!==void 0&&(l.context=o),le(c,l),await s(),Q({action:"purpose_init",file:c,metadata:{name:i,description:l.description,version:l.version}})}async function Td(t,e,s){let{purposeFile:n,id:i,description:r,section:o="components",file:a,status:c,endpoints:l,tests:d,flows:u,gates:g,signals:p,aspects:m,components:f,type:y,parent:b}=t,h=ae(n,e.rootDir),v=ce(h),w=J(i),S=o,k=He(v[S]),C=k[w]||{description:""};return C.description=r,a!==void 0&&(C.file=a),c!==void 0&&(C.status=c),l!==void 0&&(C.endpoints=l),d!==void 0&&(C.tests=d),u!==void 0&&(C.flows=u.map(x=>M(x,"$"))),g!==void 0&&(C.gates=g.map(x=>M(x,"^"))),p!==void 0&&(C.signals=p.map(x=>M(x,"!"))),m!==void 0&&(C.aspects=m.map(x=>M(x,"~"))),f!==void 0&&(C.components=f.map(x=>M(x,"#"))),y!==void 0&&(C.type=y),b!==void 0&&(C.parent=M(b,"#")),k[w]=C,v[S]=k,le(h,v),await s(),Q({action:"add_component",file:h,section:S,id:w,symbol:`#${w}`})}async function Dd(t,e,s){let{purposeFile:n,id:i,description:r,anchors:o,tags:a,appliesTo:c,enforcement:l}=t;if(!o||o.length===0)return De('Aspects (~) REQUIRE at least one code anchor. Provide anchors like ["src/middleware/audit.ts:15-35"].');let d=/^[^\s:]+:\d+(-\d+)?(,\d+)*$/;for(let f of o)if(!d.test(f))return De(`Invalid anchor format: "${f}". Expected format: "file.ts:15", "file.ts:15-20", or "file.ts:15,25,30".`);let u=ae(n,e.rootDir),g=q.dirname(u);for(let f of o){let y=f.replace(/:.*$/,""),b=q.resolve(g,y);if(!E.existsSync(b)){let h=q.resolve(e.rootDir,y);if(E.existsSync(h)){let v=q.relative(g,h),w=o.indexOf(f);o[w]=f.replace(y,v);}else return De(`Anchor file not found: "${y}". Anchors must be relative to the .purpose file directory (${g}).`)}}let p=ce(u);p.aspects||(p.aspects={});let m=J(i);return p.aspects[m]={description:r,anchors:o,...a&&{tags:a},...c&&{"applies-to":c},...l&&{enforcement:l}},le(u,p),await s(),Q({action:"add_aspect",file:u,id:m,symbol:`~${m}`,anchors:o})}async function Od(t,e,s){let{purposeFile:n,id:i,description:r,category:o,severity:a,emitters:c,related:l,data:d}=t,u=ae(n,e.rootDir),g=ce(u);g.signals||(g.signals={});let p=J(i);return g.signals[p]={description:r,...o&&{category:o},...a&&{severity:a},...c&&{emitters:c.map(m=>M(m,"#"))},...l&&{related:l},...d&&{data:d}},le(u,g),await s(),Q({action:"add_signal",file:u,id:p,symbol:`!${p}`})}async function Ad(t,e,s){let{purposeFile:n,id:i,description:r,gates:o,signals:a,components:c,steps:l}=t,d=ae(n,e.rootDir),u=ce(d),g=wn(u.flows),p=J(i),m={description:r,...o&&{gates:o.map(f=>M(f,"^"))},...a&&{signals:a.map(f=>M(f,"!"))},...c&&{components:c.map(f=>M(f,"#"))},...l&&{steps:l}};return g[p]=m,u.flows=g,le(d,u),await s(),Q({action:"add_flow",file:d,id:p,symbol:`$${p}`})}async function Id(t,e,s){let{purposeFile:n,id:i,description:r,requires:o,keys:a,signals:c}=t,l=ae(n,e.rootDir),d=ce(l);d.gates||(d.gates={});let u=J(i);return d.gates[u]={description:r,...o&&{requires:o},...a&&{keys:a},...c&&{signals:c.map(g=>M(g,"!"))}},le(l,d),await s(),Q({action:"add_gate",file:l,id:u,symbol:`^${u}`})}async function $d(t,e,s){let{purposeFile:n,id:i,description:r,type:o,default:a,properties:c}=t,l=ae(n,e.rootDir),d=ce(l);d.states||(d.states={});let u=J(i),g={description:r};return o!==void 0&&(g.type=o),a!==void 0&&(g.default=a),c!==void 0&&(g.properties=c),d.states[u]=g,le(l,d),await s(),Q({action:"add_state",file:l,id:u})}async function Fd(t,e,s){let{purposeFile:n,componentId:i,section:r,signals:o,aspects:a,gates:c,flows:l,components:d}=t,u=ae(n,e.rootDir),g=ce(u),p=J(i),m=r;if(!m){let h=He(g.components),v=He(g.features);if(p in h)m="components";else if(p in v)m="features";else return De(`Component "${p}" not found in components or features. Specify section explicitly.`)}let f=He(g[m]);if(!(p in f))return De(`Component "${p}" not found in ${m} section.`);let y=f[p];o&&(y.signals=Ze(y.signals,o.map(h=>M(h,"!")))),c&&(y.gates=Ze(y.gates,c.map(h=>M(h,"^")))),l&&(y.flows=Ze(y.flows,l.map(h=>M(h,"$")))),d&&(y.components=Ze(y.components,d.map(h=>M(h,"#")))),a&&(y.aspects=Ze(y.aspects,a.map(h=>M(h,"~")))),f[p]=y,g[m]=f,le(u,g),await s();let b=[];return o&&b.push(`signals: ${o.join(", ")}`),a&&b.push(`aspects: ${a.join(", ")}`),c&&b.push(`gates: ${c.join(", ")}`),l&&b.push(`flows: ${l.join(", ")}`),d&&b.push(`components: ${d.join(", ")}`),Q({action:"link",file:u,componentId:p,section:m,added:b})}async function Nd(t,e,s){let{purposeFile:n,section:i,id:r}=t,o=ae(n,e.rootDir),a=ce(o),c=J(r);if(i==="flows"){let l=wn(a.flows);if(!(c in l))return De(`Flow "${c}" not found in flows section.`);delete l[c],a.flows=l;}else if(i==="components"||i==="features"){let l=He(a[i]);if(!(c in l))return De(`"${c}" not found in ${i} section.`);delete l[c],a[i]=l;}else {let l=a[i];if(!l||!(c in l))return De(`"${c}" not found in ${i} section.`);delete l[c];}return le(o,a),await s(),Q({action:"remove",file:o,section:i,id:c})}async function Ed(t,e,s){let{oldId:n,newId:i,symbolType:r}=t,o=await Qo(e.rootDir,n,i,r);return await s(),Q({action:"rename",oldSymbol:`${r}${J(n)}`,newSymbol:`${r}${J(i)}`,filesModified:o.length,files:o})}async function Hd(t,e,s){let{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:u}=t,g=ea(e.rootDir,{id:n,description:i,type:r,location:o,requires:a,check:c,grants:l,emits:d,prizes:u});await s();let p=J(n);return Q({action:"portal_add_gate",file:g,id:p,symbol:`^${p}`})}async function qd(t,e,s){let{route:n,method:i,gates:r}=t,o=ta(e.rootDir,{route:n,method:i,gates:r});return await s(),Q({action:"portal_add_route",file:o,route:`${i} ${n}`,gates:r})}var Md=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi;function na(t,e){let s=[];function n(r,o){if(typeof r=="string"){let a=r.match(Md);if(a)for(let c of a)s.push({type:"warning",message:`Clarification needed: ${c}`,path:o});}}n(t.description,"description");let i=[{key:"components",items:t.components},{key:"features",items:t.features},{key:"gates",items:t.gates},{key:"signals",items:t.signals},{key:"aspects",items:t.aspects}];for(let r of i)if(r.items&&typeof r.items=="object")for(let[o,a]of Object.entries(r.items))a&&typeof a.description=="string"&&n(a.description,`${r.key}.${o}.description`);if(t.flows&&typeof t.flows=="object"){let r=Array.isArray(t.flows)?[]:Object.entries(t.flows);for(let[o,a]of r)a&&typeof a.description=="string"&&n(a.description,`flows.${o}.description`);}return s}async function Ld(t,e){let{purposeFile:s,includePortal:n=true}=t,i=[];if(s){let a=ae(s,e.rootDir),c=a$9(a);if(!c.data)i.push({file:a,valid:false,issues:c.errors.map(l=>({type:"error",message:l}))});else {let l=d$9(c.data,a);if(c.data.aspects)for(let[u,g]of Object.entries(c.data.aspects))(!g.anchors||g.anchors.length===0)&&(l.issues.push({type:"error",message:`Aspect "${u}" is missing required anchors`,path:`aspects.${u}`}),l.valid=false);let d=na(c.data);l.issues.push(...d),i.push({file:a,valid:l.valid,issues:l.issues});}}else {let a=await c$5(e.rootDir);for(let c of a){let l=a$9(c);if(!l.data){i.push({file:c,valid:false,issues:l.errors.map(g=>({type:"error",message:g}))});continue}let d=d$9(l.data,c);if(l.data.aspects)for(let[g,p]of Object.entries(l.data.aspects))(!p.anchors||p.anchors.length===0)&&(d.issues.push({type:"error",message:`Aspect "${g}" is missing required anchors`,path:`aspects.${g}`}),d.valid=false);let u=na(l.data);d.issues.push(...u),i.push({file:c,valid:d.valid,issues:d.issues});}}if(n){let{data:a,filePath:c}=kn(e.rootDir),l=[];if(a.gates)for(let[d,u]of Object.entries(a.gates))u.description||l.push({type:"warning",message:`Gate "${d}" has no description`,path:`gates.${d}`}),u.prizes||l.push({type:"warning",message:`Gate "${d}" is missing prizes array (v2 requirement)`,path:`gates.${d}`});l.length>0&&i.push({file:c,valid:l.every(d=>d.type!=="error"),issues:l});}let r=i.reduce((a,c)=>a+c.issues.length,0),o=i.every(a=>a.valid);return Q({action:"validate",valid:o,totalFiles:i.length,totalIssues:r,results:i})}var ya=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}],Bd=30*1e3,Ts=new Map;function ee(t){let e=q.resolve(t),s=Ts.get(e);if(s&&Date.now()-s.loadedAt<Bd)return s.habits;let n=zd(e);return Ts.set(e,{habits:n,loadedAt:Date.now()}),n}function zd(t){let e=new Map;for(let a of ya)e.set(a.id,{...a});let s=process.env.HOME||process.env.USERPROFILE||"~",n=la(q.join(s,".paradigm","habits.yaml"));n&&da(e,n);let i=pa(q.join(s,".paradigm","habits"));for(let a of i)e.set(a.id,a);let r=la(q.join(t,".paradigm","habits.yaml"));r&&da(e,r);let o=pa(q.join(t,".paradigm","habits"));for(let a of o)e.set(a.id,a);return Array.from(e.values())}function la(t){if(!E.existsSync(t))return null;try{let e=E.readFileSync(t,"utf8");return be.load(e)}catch{return null}}function da(t,e){if(e.habits)for(let s of e.habits)t.set(s.id,{...s});if(e.overrides)for(let[s,n]of Object.entries(e.overrides)){let i=t.get(s);i&&(n.severity!==void 0&&(i.severity=n.severity),n.enabled!==void 0&&(i.enabled=n.enabled));}}function Yd(t,e){return t.filter(s=>s.enabled&&s.trigger===e)}function Ds(t){Ts.delete(q.resolve(t));}function pa(t){if(!E.existsSync(t))return [];try{let e=E.readdirSync(t).filter(n=>n.endsWith(".habit")).sort(),s=[];for(let n of e)try{let i=E.readFileSync(q.join(t,n),"utf8"),r=be.load(i);r?.id&&r?.name&&s.push(r);}catch{}return s}catch{return []}}var ua=["discovery","verification","testing","documentation","collaboration","security"],ga=["preflight","postflight","on-commit","on-stop"],ma=["advisory","warn","block"],fa=["tool-called","file-exists","file-modified","lore-recorded","symbols-registered","gates-declared","tests-exist","git-clean","commit-message-format","flow-coverage","context-checked","aspect-anchored"],Vd=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Os(t){let e=[];if(t.id||e.push("Missing required field: id"),t.name||e.push("Missing required field: name"),t.description||e.push("Missing required field: description"),t.category||e.push("Missing required field: category"),t.trigger||e.push("Missing required field: trigger"),t.severity||e.push("Missing required field: severity"),t.check||e.push("Missing required field: check"),(t.enabled===void 0||t.enabled===null)&&e.push("Missing required field: enabled"),t.id&&!Vd.test(t.id)&&e.push(`Invalid id format: "${t.id}" \u2014 must be kebab-case (lowercase, hyphens only)`),t.category&&!ua.includes(t.category)&&e.push(`Invalid category: "${t.category}" \u2014 must be one of: ${ua.join(", ")}`),t.trigger&&!ga.includes(t.trigger)&&e.push(`Invalid trigger: "${t.trigger}" \u2014 must be one of: ${ga.join(", ")}`),t.severity&&!ma.includes(t.severity)&&e.push(`Invalid severity: "${t.severity}" \u2014 must be one of: ${ma.join(", ")}`),t.check){fa.includes(t.check.type)||e.push(`Invalid check.type: "${t.check.type}" \u2014 must be one of: ${fa.join(", ")}`);let s=t.check.params||{};switch(t.check.type){case "tool-called":(!s.tools||!Array.isArray(s.tools)||s.tools.length===0)&&e.push('check.type "tool-called" requires check.params.tools[] (non-empty array)');break;case "file-exists":case "file-modified":(!s.patterns||!Array.isArray(s.patterns)||s.patterns.length===0)&&e.push(`check.type "${t.check.type}" requires check.params.patterns[] (non-empty array)`);break;case "commit-message-format":(!s.messagePatterns||!Array.isArray(s.messagePatterns)||s.messagePatterns.length===0)&&e.push('check.type "commit-message-format" requires check.params.messagePatterns[] (non-empty array)');break}}return {valid:e.length===0,errors:e}}var Kd=new Set(ya.map(t=>t.id));function jn(t){return Kd.has(t)}function As(t,e,s="project"){let n=s==="global"?q.join(process.env.HOME||process.env.USERPROFILE||"~",".paradigm","habits"):q.join(t,".paradigm","habits");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${e.id}.habit`),r=be.dump(e,{lineWidth:120,noRefs:true});return E.writeFileSync(i,r,"utf8"),Ds(t),i}function ha(t,e){if(jn(e))return {removed:false,reason:`"${e}" is a seed habit and cannot be removed. Use overrides in habits.yaml to disable it.`};let s=q.join(t,".paradigm","habits",`${e}.habit`);if(E.existsSync(s))return E.unlinkSync(s),Ds(t),{removed:true};let n=process.env.HOME||process.env.USERPROFILE||"~",i=q.join(n,".paradigm","habits",`${e}.habit`);return E.existsSync(i)?(E.unlinkSync(i),Ds(t),{removed:true}):{removed:false,reason:`No .habit file found for "${e}". It may be defined in habits.yaml \u2014 edit that file directly.`}}var Is=0;function Dt(t,e,s,n,i){let r=Yd(t,e);n&&(r=r.filter(g=>!g.platforms||g.platforms.includes(n)));let o=0;if(i)try{let{isGraduated:g}=(Pn(),d$a(ca)),p=r.length;r=r.filter(m=>!g(i,m.id)),o=p-r.length;}catch{}Is=o;let a=r.map(g=>Qd(g,s)),c=a.filter(g=>g.result==="followed").length,l=a.filter(g=>g.result==="skipped").length,d=a.filter(g=>g.result==="partial").length,u=a.filter(g=>g.result==="skipped"&&g.habit.severity==="block").length;return {trigger:e,evaluations:a,summary:{total:a.length,followed:c,skipped:l,partial:d,blockingViolations:u},blocksCompletion:u>0}}function Ot(t){return {toolsCalled:t.toolsCalled||[],filesModified:t.filesModified||[],symbolsTouched:t.symbolsTouched||[],loreRecorded:t.loreRecorded||false,hasPortalRoutes:t.hasPortalRoutes||false,taskAddsRoutes:t.taskAddsRoutes||false,taskDescription:t.taskDescription,gitClean:t.gitClean}}function Qd(t,e){switch(t.check.type){case "tool-called":return Xd(t,e);case "file-exists":return Zd(t,e);case "file-modified":return ip(t,e);case "lore-recorded":return ep(t,e);case "symbols-registered":return tp(t,e);case "gates-declared":return np(t,e);case "tests-exist":return sp(t,e);case "git-clean":return rp(t,e);case "commit-message-format":return op(t,e);case "flow-coverage":return ap(t,e);case "context-checked":return cp(t,e);case "aspect-anchored":return lp(t,e);default:return {habit:t,result:"partial",reason:`Unknown check: ${t.check.type}`}}}function Xd(t,e){let s=t.check.params.tools||[];if(s.length===0)return {habit:t,result:"followed",reason:"No tools required"};let n=s.filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, habit not applicable"}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] were called before modifying code`}}function Zd(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};if(e.filesModified.some(i=>i.endsWith(".purpose")||i.includes(".paradigm/")))return {habit:t,result:"followed",reason:"Purpose files updated"};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return n.length===0?{habit:t,result:"followed",reason:"Only non-source files modified"}:{habit:t,result:"skipped",reason:`${n.length} source file(s) without .purpose updates`,evidence:n.slice(0,5)}}function ep(t,e){let s=e.filesModified.filter(n=>!n.endsWith(".md")&&!n.endsWith(".json")&&!n.endsWith(".yaml")&&!n.endsWith(".yml")&&!n.endsWith(".lock")&&!n.endsWith(".purpose")&&!n.includes(".paradigm/"));return s.length<3?{habit:t,result:"followed",reason:"Session not significant (< 3 source files)"}:e.loreRecorded||e.toolsCalled.includes("paradigm_lore_record")?{habit:t,result:"followed",reason:"Lore recorded"}:{habit:t,result:"skipped",reason:`${s.length} source files modified, no lore entry`,evidence:s.slice(0,5)}}function tp(t,e){if(e.symbolsTouched.length===0)return {habit:t,result:"followed",reason:"No symbols touched"};let n=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Purpose tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"partial",reason:`${e.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function np(t,e){if(!e.taskAddsRoutes)return {habit:t,result:"followed",reason:"No routes added"};if(e.hasPortalRoutes)return {habit:t,result:"followed",reason:"Portal.yaml has routes"};let n=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Gate tools called: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:"Routes added without gate declarations"}}function sp(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=e.filesModified.filter(i=>i.includes(".test.")||i.includes(".spec.")||i.includes("/tests/")||i.includes("/test/")||i.includes("__tests__"));if(s.length>0)return {habit:t,result:"followed",reason:`Test files: ${s.length}`,evidence:s.slice(0,5)};let n=e.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/")&&!i.includes("node_modules/"));return n.length===0?{habit:t,result:"followed",reason:"No source files to test"}:{habit:t,result:"partial",reason:`${n.length} source file(s), no test files updated`,evidence:n.slice(0,5)}}function ip(t,e){if(e.filesModified.length===0)return {habit:t,result:"followed",reason:"No files modified"};let s=t.check.params.patterns||[];if(s.length===0)return {habit:t,result:"followed",reason:"No patterns specified"};if(t.trigger==="on-stop"&&t.severity==="block"){let i=e.filesModified.filter(r=>s.some(o=>r.includes(o)||q.basename(r)===o));return i.length>0?{habit:t,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:t,result:"partial",reason:`None of [${s.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let n=e.filesModified.filter(i=>s.some(r=>i.includes(r)||q.basename(i)===r));return n.length>0?{habit:t,result:"followed",reason:`Matching files: ${n.join(", ")}`,evidence:n}:{habit:t,result:"skipped",reason:`None of [${s.join(", ")}] found in modified files`}}function rp(t,e){return e.filesModified.length===0?{habit:t,result:"followed",reason:"No files modified"}:t.trigger==="on-stop"?{habit:t,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:e.gitClean===void 0?{habit:t,result:"partial",reason:"Git status not available"}:e.gitClean?{habit:t,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:t,result:"skipped",reason:"Uncommitted changes in working tree"}}function op(t,e){if(!e.commitMessage)return {habit:t,result:"followed",reason:"No commit message to check (not a commit trigger)"};let s=t.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],n=s.filter(i=>new RegExp(i,"m").test(e.commitMessage));if(n.length===s.length)return {habit:t,result:"followed",reason:"Commit message matches all required patterns",evidence:n};if(n.length>0){let i=s.filter(r=>!new RegExp(r,"m").test(e.commitMessage));return {habit:t,result:"partial",reason:`Matches ${n.length}/${s.length} patterns. Missing: ${i.join(", ")}`}}return {habit:t,result:"skipped",reason:"Commit message does not match required format patterns"}}function ap(t,e){let s=e.symbolsTouched.filter(r=>r.startsWith("#"));if(s.length<3)return {habit:t,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(e.hasFlowCoverage)return {habit:t,result:"followed",reason:"Flow coverage exists for multi-component changes"};let i=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(r=>e.toolsCalled.includes(r));return i.length>0?{habit:t,result:"followed",reason:`Flow tools called: ${i.join(", ")}`,evidence:i}:{habit:t,result:"skipped",reason:`${s.length} components touched without flow coverage`,evidence:s.slice(0,5)}}function cp(t,e){let n=(t.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(i=>e.toolsCalled.includes(i));return n.length>0?{habit:t,result:"followed",reason:`Context tools called: ${n.join(", ")}`,evidence:n}:e.filesModified.length===0&&e.symbolsTouched.length===0?{habit:t,result:"followed",reason:"No modifications, context check not applicable"}:{habit:t,result:"skipped",reason:"No context/session tools called during session"}}function lp(t,e){let s=e.symbolsTouched.filter(n=>n.startsWith("~"));return s.length===0?{habit:t,result:"followed",reason:"No aspects touched"}:e.aspectAnchorsValid===true?{habit:t,result:"followed",reason:"Aspect anchors validated and valid"}:e.toolsCalled.includes("paradigm_aspect_check")?{habit:t,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:t,result:"skipped",reason:`${s.length} aspect(s) touched without anchor validation`,evidence:s.slice(0,5)}}var dp={"missing-purpose":t=>`${t.target?`"${t.target}"`:"a directory"} is missing a .purpose file. Without it, agents cannot discover what this directory contains or which components live here. The stop hook will block if source files were modified in a directory with no .purpose. Fix: run paradigm_purpose_init for this directory, then add components with paradigm_purpose_add_component.`,"stale-purpose":t=>{let e=t.target?`"${t.target}"`:"a .purpose file",s=t.context?.ageHours!=null?` (${t.context.ageHours}h old)`:"";return `The .purpose file at ${e}${s} has not been updated since the last code change in its directory. Stale purposes mislead agents about what components exist, causing incorrect context injection. Fix: update the .purpose to reflect any added, removed, or changed components, then run paradigm_reindex.`},"missing-gate":t=>`${t.target?`"${t.target}"`:"a route or endpoint"} appears to require authentication or authorization but has no gate declared in portal.yaml. Gates are how Paradigm tracks security enforcement \u2014 missing gates mean agents cannot verify that the route is protected. Fix: add the gate to portal.yaml using paradigm_portal_add_route or paradigm_purpose_add_component with the appropriate gates array.`,"orphan-signal":t=>`${t.target?`"${t.target}"`:"a signal"} is emitted in code but not declared in any .purpose file. Undeclared signals cannot be traced by agents during ripple analysis, meaning downstream effects may be missed when the signal's emitter changes. Fix: add the signal to the nearest .purpose file under its component's signals array (e.g., signals: ["!${t.target||"event-name"}"]). `,"undocumented-flow":t=>`${t.target?`"${t.target}"`:"a multi-step flow"} spans multiple components but has no $flow declaration. Flows with 3 or more steps should be documented so agents can reason about the sequence end-to-end. Without a flow record, agents may implement duplicate logic or miss ordering constraints. Fix: add a flow entry to .paradigm/flows.yaml with the steps and participants.`,"aspect-drift":t=>`${t.target?`"${t.target}"`:"an aspect anchor"} has drifted \u2014 the code at the anchored location no longer matches the fingerprint recorded when the aspect was first applied. This means the aspect may no longer be enforced correctly at that site. Drift is common after refactors that move or rewrite anchored code. Fix: re-anchor the aspect at its new location using paradigm_aspect_anchor, then delete the stale anchor.`,"portal-mismatch":t=>`${t.target?`"${t.target}"`:"a portal.yaml entry"} has a mismatch between what portal.yaml declares and what the code enforces. This could mean a gate is declared but never applied in middleware, or code enforces a check that is not tracked in portal.yaml. Both directions create audit gaps. Fix: reconcile portal.yaml with actual middleware usage \u2014 run paradigm portal check to see specifics.`,"missing-test":t=>`${t.target?`"${t.target}"`:"a component"} has no associated test file. Agents are expected to write tests alongside every implementation. Missing tests increase regression risk and reduce confidence scores for the affected component. Fix: create a test file alongside the implementation (e.g., ${t.target?t.target.replace(/\.[^.]+$/,".test$&"):"component.test.ts"}).`,"uncovered-route":t=>`${t.target?`"${t.target}"`:"a route"} appears in the codebase but is not listed in portal.yaml. All routes \u2014 protected or public \u2014 should be tracked in portal.yaml so the full API surface is visible to agents and reviewers. Uncovered routes are invisible to ripple analysis and gate audits. Fix: add the route to portal.yaml with paradigm_portal_add_route.`,"broken-reference":t=>`${t.target?`"${t.target}"`:"a symbol reference"} references a symbol or file that no longer exists. Broken references in .purpose files cause agents to load stale context and may indicate a renamed or deleted component. Fix: update the reference to the new symbol name, or remove it if the component was deleted. Run paradigm_reindex after fixing to regenerate the scan index.`,"missing-description":t=>`${t.target?`"${t.target}"`:"a component or gate"} has no description. Descriptions are required for agents to understand purpose and context during context injection. Without descriptions, agents may misapply the component or skip it when it would have been relevant. Fix: add a description field to the component or gate entry in its .purpose or portal.yaml file.`,"enforcement-level-violation":t=>{let e=t.target?`"${t.target}"`:"a data category",s=t.context?.ring,n=t.context?.boundary;return `${e} is being transmitted across a boundary (${n||"unknown boundary"}) that exceeds its trust ring${s?` (Ring: ${s})`:""}. Data policy requires project-locked content to never leave the project boundary. This gap could expose internal compliance data externally. Fix: check the data-policy.yaml configuration and ensure the content category is listed in the deny_content for the relevant stream.`},"index-stale":t=>{let e=t.target?`"${t.target}"`:"the scan index",s=t.context?.ageHours,n=s!=null?` (${s} hours old)`:"";return `${e}${n} is stale. The scan index drives context injection, navigator, and ripple analysis. When the index is out of date, agents work from stale symbol maps and may miss recently added components or references. Fix: run paradigm_reindex (or "paradigm index") to regenerate the index.`}};function pp(t,e){let s=dp[t];return s?s({...e,type:t}):`Unknown check type "${t}" \u2014 no narration template available.`}function wa(t){let e=[],s=[],n=[];for(let o of t){let a=pp(o.type,o),c=o.severity??"improvement",l={type:o.type,target:o.target,narration:a,severity:c};c==="blocking"?e.push(l):c==="note"?n.push(l):s.push(l);}let i=e.length+s.length+n.length,r=up(e,s,n);return {gapCount:i,blocking:e,improvement:s,note:n,narrative:r}}function up(t,e,s){let n=[],i=t.length+e.length+s.length;if(i===0)return "No gaps found. All enforcement checks passed.";if(n.push(`Found ${i} gap${i!==1?"s":""} across ${ba(t,e,s)} check type${ba(t,e,s)!==1?"s":""}.`),n.push(""),t.length>0){n.push(`BLOCKING (${t.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of t)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(e.length>0){n.push(`IMPROVEMENTS (${e.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of e)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}if(s.length>0){n.push(`NOTES (${s.length})`),n.push("\u2500\u2500\u2500\u2500\u2500\u2500");for(let r of s)n.push(`[${r.type}]${r.target?` \u2014 ${r.target}`:""}`),n.push(r.narration),n.push("");}return n.join(`
375
375
  `).trimEnd()}function ba(t,e,s){let n=new Set;for(let i of [...t,...e,...s])n.add(i.type);return n.size}var mp=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,fp=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"],yp=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi];function va(){return [{name:"paradigm_pm_preflight",description:`REQUIRED before implementing features. Call with mode="plan" to get the right agents and cost estimate. Skipping this for complex tasks leads to missed security reviews and wasted tokens.
376
376
 
377
377
  Runs pre-flight compliance checks: extracts affected symbols, runs ripple analysis, checks portal.yaml status, and suggests required agents. Returns affected symbols, ripple summary, gate recommendations, and suggested agents. ~300 tokens.`,inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze for compliance requirements"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pm_postflight",description:"Run after completing a task to check compliance. Verifies that new components, routes, and events are properly registered in .purpose files and portal.yaml. Flags unregistered symbols and uncaptured wisdom. Returns compliance checklist with pass/fail status for purpose files, portal.yaml, and wisdom capture. ~200 tokens.",inputSchema:{type:"object",properties:{filesModified:{type:"array",items:{type:"string"},description:"List of files modified during the task"},symbolsTouched:{type:"array",items:{type:"string"},description:'List of symbols (e.g., ["#auth-handler", "^authenticated"]) touched during the task'}},required:["filesModified","symbolsTouched"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ka(t,e,s){switch(t){case "paradigm_pm_preflight":{let{task:n}=e,i=await hp(n,s),r=JSON.stringify(i,null,2);return o(r.length,t),{text:r,handled:true}}case "paradigm_pm_postflight":{let{filesModified:n,symbolsTouched:i}=e,r=wp(n,i,s),o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{text:o$1,handled:true}}default:return {text:"",handled:false}}}async function hp(t,e){let s=t.toLowerCase(),n=t.match(mp)||[],i=[...new Set(n)],r=i.map(g=>{let p=j$2(e.index,g),m=p.length>0?p[0]:null;return {symbol:g,exists:!!m,type:m?.type,description:m?.description}}),o=r.filter(g=>g.exists).map(g=>{let p=k(e.index,g.symbol),m=new Set;for(let b of p){let h=k(e.index,b.symbol);for(let v of h)v.symbol!==g.symbol&&!p.find(w=>w.symbol===v.symbol)&&m.add(v.symbol);}let f=p.length+m.size,y="low";return f>10?y="high":f>3&&(y="medium"),{symbol:g.symbol,directDependents:p.length,indirectDependents:m.size,impact:y}}),a={exists:e.gateConfig!==null,gateCount:0,gates:[],routeCount:0};if(e.gateConfig){let g=Object.keys(e.gateConfig.gates||{});a.gateCount=g.length,a.gates=g.map(p=>p.startsWith("^")?p:`^${p}`),a.routeCount=Object.keys(e.gateConfig.routes||{}).length;}let c=fp.some(g=>s.includes(g)),l=[];r.some(g=>g.exists)&&l.push("ripple-analysis"),c&&l.push("portal-compliance"),i.some(g=>g.startsWith("^"))&&l.push("gate-validation"),i.some(g=>g.startsWith("!"))&&l.push("signal-registration"),l.push("purpose-coverage");let d=null,u=null;try{let g=ee(e.rootDir),m=j$1().getStats(),f=[...new Set(m.toolCalls.map(v=>v.toolName))],y=Ot({toolsCalled:f,filesModified:[],symbolsTouched:i,loreRecorded:!1,hasPortalRoutes:a.exists&&a.routeCount>0,taskAddsRoutes:c,taskDescription:t}),b=Dt(g,"preflight",y,void 0,e.rootDir);d={total:b.summary.total,followed:b.summary.followed,skipped:b.summary.skipped,partial:b.summary.partial,results:b.evaluations.map(v=>({id:v.habit.id,name:v.habit.name,severity:v.habit.severity,result:v.result,reason:v.reason}))};let h=new Date(Date.now()-720*60*60*1e3).toISOString();u=await re(e.rootDir,{dateFrom:h});}catch{}return {task:t.slice(0,100)+(t.length>100?"...":""),affectedSymbols:r,rippleAnalysis:o,portalStatus:a,taskAddsRoutes:c,requiredChecks:l,recommendations:bp(r,o,a,c),habits:{evaluation:d,recentCompliance:u?{rate:u.rate,totalEvents:u.total}:null}}}function bp(t,e,s,n){let i=[],r=t.filter(c=>!c.exists);r.length>0&&i.push(`New symbols detected: ${r.map(c=>c.symbol).join(", ")}. Register in .purpose files after implementation.`);let o=e.filter(c=>c.impact==="high");o.length>0&&i.push(`HIGH IMPACT: ${o.map(c=>c.symbol).join(", ")} \u2014 review all dependents before modifying.`),n&&!s.exists?i.push("Task adds routes but no portal.yaml exists. Create one with appropriate ^gates."):n&&i.push("Task adds routes. Update portal.yaml with gate entries after implementation.");let a=t.filter(c=>c.symbol.startsWith("^")&&!c.exists);return a.length>0&&i.push(`New gates referenced: ${a.map(c=>c.symbol).join(", ")}. Add to portal.yaml.`),i}function wp(t,e,s){let n=[],i$1=s.gateConfig?.routes?Object.keys(s.gateConfig.routes):[];for(let p of t){let m=q.isAbsolute(p)?p:q.join(s.rootDir,p);if(!E.existsSync(m))continue;let f;try{f=E.readFileSync(m,"utf-8");}catch{continue}for(let y of yp){y.lastIndex=0;let b;for(;(b=y.exec(f))!==null;){let h=b[2]||b[0];h&&h.startsWith("/")&&(!i$1.some(w=>w.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===h)&&s.gateConfig?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${h}" in ${q.relative(s.rootDir,m)} not in portal.yaml`,file:q.relative(s.rootDir,m),suggestion:"Add route to portal.yaml with ^gates. Use paradigm_gates_for_route for suggestions."}):!s.gateConfig&&h.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${h}" found but no portal.yaml exists`,file:q.relative(s.rootDir,m),suggestion:"Create portal.yaml to declare gates for API routes."}));}}}for(let p of e)j$2(s.index,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" is not registered in any .purpose file`,suggestion:"Add to nearest .purpose file using paradigm_purpose_add_component or paradigm_purpose_add_signal."});let r=s.gateConfig?Object.keys(s.gateConfig.gates||{}).map(p=>p.startsWith("^")?p.slice(1):p):[];for(let p of e)if(p.startsWith("^")){let m=p.slice(1);r.includes(m)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}let o=i(s.index,"aspect");for(let p of o){let m=p.appliesTo||[];if(m.length!==0){for(let f of m){let y=f.includes("*");for(let b of e){let h=false;if(y?h=new RegExp("^"+f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(b):h=b===f,h){let v=p.anchors||[];if(v.length===0)n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" applies to "${b}" but has no code anchors`,suggestion:`Add anchors to ${p.symbol} in .purpose file. Run paradigm_aspect_check for details.`});else for(let w of v){let S=q.isAbsolute(w.path)?w.path:q.join(s.rootDir,w.path);E.existsSync(S)||n.push({type:"stale-aspect",severity:"warning",message:`Aspect "${p.symbol}" anchor "${w.raw}" points to missing file`,suggestion:`Update anchors for ${p.symbol} in .purpose file.`});}}}}for(let f of e){if(!f.startsWith("#"))continue;(p.data||{}).aspects||[];for(let h of m){if(!h.includes("*"))continue;if(new RegExp("^"+h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(f))break}}}}t.length>=5&&e.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${t.length} files, ${e.length} symbols) \u2014 consider recording decisions`,suggestion:"Use paradigm_wisdom_record to capture architectural decisions or antipatterns."});for(let p of e){let m=j$2(s.index,p);if(m.length===0)continue;let f=m[0];f.parentSymbol&&j$2(s.index,f.parentSymbol).length===0&&n.push({type:"broken-reference",severity:"warning",message:`Symbol "${p}" references parent "${f.parentSymbol}" which does not exist`,suggestion:"Create the parent symbol or update the parent reference in the .purpose file."});}let a=n.filter(p=>p.severity==="error").length,c=n.filter(p=>p.severity==="warning").length,l="pass";a>0?l="violations":c>0&&(l="warnings");let d=null;try{let p=ee(s.rootDir),f=j$1().getStats(),y=[...new Set(f.toolCalls.map(k=>k.toolName))],b=y.includes("paradigm_lore_record"),h;try{h=execSync("git status --porcelain",{cwd:s.rootDir,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let v=Ot({toolsCalled:y,filesModified:t,symbolsTouched:e,loreRecorded:b,hasPortalRoutes:s.gateConfig!==null&&s.gateConfig.routes!=null,taskAddsRoutes:!1,gitClean:h}),w=Dt(p,"postflight",v,void 0,s.rootDir);d={trigger:"postflight",total:w.summary.total,followed:w.summary.followed,skipped:w.summary.skipped,partial:w.summary.partial,blockingViolations:w.summary.blockingViolations,results:w.evaluations.map(k=>({id:k.habit.id,name:k.habit.name,severity:k.habit.severity,result:k.result,reason:k.reason}))};let S=q.join(s.rootDir,".paradigm",".habits-blocking");if(w.blocksCompletion){let k=w.evaluations.filter(C=>C.result==="skipped"&&C.habit.severity==="block").map(C=>`${C.habit.name}: ${C.reason}`);E.writeFileSync(S,k.join(`
@@ -409,8 +409,8 @@ Runs pre-flight compliance checks: extracts affected symbols, runs ripple analys
409
409
  WHERE query_normalized = ? AND aspect_id != ?`,[Ip,n,s]);}catch{}}function $s(t){try{let e=JSON.parse(t);return Array.isArray(e)&&e.length>0?e:void 0}catch{let e=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);return e.length>0?e:void 0}}function Fa(){return [{name:"paradigm_aspect_search",description:"Search aspects using three-tier learning search (learned mappings > FTS5 > fuzzy). Returns ranked results. Call paradigm_aspect_confirm after selecting a result to improve future searches. ~200 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:'Search query (natural language or keyword, e.g., "token expiry", "pricing rule")'},limit:{type:"number",description:"Maximum results to return (default: 10)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_get",description:"Get full detail for a single aspect: description, category, severity, code anchors with snippets, edges, and linked lore entries. ~300 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:'Aspect identifier without ~ prefix (e.g., "token-expiry-24h")'}},required:["aspectId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_graph",description:"Traverse the aspect graph from a symbol to visualize its neighborhood. Returns nodes and edges within N hops (BFS). Useful for understanding how aspects relate to each other. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Starting symbol for graph traversal (e.g., "~token-expiry-24h", "#auth-service")'},hops:{type:"number",description:"Maximum number of hops to traverse (default: 2, max: 5)"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_heatmap",description:"View the most frequently accessed aspects, ranked by total access count. Shows which aspects are queried most often. ~150 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Maximum entries to return (default: 20)"},accessType:{type:"string",enum:["search","ripple","navigate","direct"],description:"Optional: filter by access type"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_suggest_scan",description:"Scan a source file for implicit aspects (magic numbers, hardcoded limits, configuration values) and suggest aspect definitions. ~200 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:"Relative or absolute path to the source file to scan"}},required:["filePath"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_aspect_drift",description:"Smart drift detection for code anchors. Layer 1: normalized hash (ignores formatting). Layer 2: git-aware line mapping (detects shifts, auto-heals .purpose files). ~200 tokens.",inputSchema:{type:"object",properties:{aspectId:{type:"string",description:"Optional: check a specific aspect. If omitted, checks all aspects."},autoHeal:{type:"boolean",description:"Auto-update anchors for high-confidence shifts (default: true)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_aspect_confirm",description:"Confirm a search result to improve future search accuracy. Call this after the user selects or uses a result from paradigm_aspect_search. Reinforces the query-to-aspect mapping. ~50 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"The original search query used"},aspectId:{type:"string",description:"The aspect ID that was selected/confirmed"}},required:["query","aspectId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Na(t,e,s){switch(t){case "paradigm_aspect_search":return Gp(e,s);case "paradigm_aspect_get":return Wp(e,s);case "paradigm_aspect_graph":return Jp(e,s);case "paradigm_aspect_heatmap":return Up(e,s);case "paradigm_aspect_suggest_scan":return Bp(e,s);case "paradigm_aspect_drift":return zp(e,s);case "paradigm_aspect_confirm":return Yp(e,s);default:return {handled:false,text:""}}}async function Gp(t,e){let{query:s,limit:n=10}=t,i=null;try{i=await $(e.rootDir);let r=Aa(i,s,{limit:n});for(let c of r)try{ga$1(i,c.id,"search");}catch{}let o$1={query:s,count:r.length,results:r.map(c=>({id:c.id,description:c.description,category:c.category,severity:c.severity,score:Math.round(c.score*1e3)/1e3,tier:c.tier,tags:c.tags,anchorCount:c.anchorCount})),tip:r.length>0?"Call paradigm_aspect_confirm with the query and selected aspectId to improve future searches.":"No results found. Try broader terms or check that aspects are defined in .purpose files."},a=JSON.stringify(o$1,null,2);return aa$1(i,e.rootDir),i=null,o(a.length,"paradigm_aspect_search"),{handled:!0,text:a}}catch(r){if(i)try{aa$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to search aspects",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_search"),{handled:true,text:o$1}}}async function Wp(t,e){let{aspectId:s}=t,n=s.startsWith("~")?s.slice(1):s,i=null;try{i=await $(e.rootDir);let r=ba$1(i,n);if(r||(r=ba$1(i,`~${n}`)),!r){aa$1(i),i=null;let y=JSON.stringify({error:"Aspect not found",aspectId:n,suggestion:"Use paradigm_aspect_search to find aspects by keyword."},null,2);return o(y.length,"paradigm_aspect_get"),{handled:!0,text:y}}let o$1=r.id,c=ca$1(i,o$1).map(y=>{let b=Vp(e.rootDir,y);return {filePath:y.file_path,startLine:y.start_line,endLine:y.end_line,drifted:y.drifted===1,snippet:b}}),l=da$1(i,o$1),d=ea$1(i,o$1),u=[...l.map(y=>({direction:"outgoing",source:y.source,target:y.target,relation:y.relation,weight:y.weight,origin:y.origin})),...d.map(y=>({direction:"incoming",source:y.source,target:y.target,relation:y.relation,weight:y.weight,origin:y.origin}))],g=[];try{g=await ja$1(i,e.rootDir,o$1);}catch{}try{ga$1(i,o$1,"direct");}catch{}let p;if(r.tags)try{let y=JSON.parse(r.tags);Array.isArray(y)&&(p=y);}catch{p=r.tags.split(",").map(y=>y.trim()).filter(y=>y.length>0);}let m={id:o$1,description:r.description,category:r.category,severity:r.severity,value:r.value,enforcement:r.enforcement,definedIn:r.defined_in,tags:p,createdAt:r.created_at,updatedAt:r.updated_at,anchors:c,edges:u,lore:g},f=JSON.stringify(m,null,2);return aa$1(i,e.rootDir),i=null,o(f.length,"paradigm_aspect_get"),{handled:!0,text:f}}catch(r){if(i)try{aa$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_get"),{handled:true,text:o$1}}}async function Jp(t,e){let{symbol:s,hops:n=2}=t,i=Math.min(Math.max(n,1),5),r=null;try{r=await $(e.rootDir);let o$1=new Set,a=new Map,c=[],l=[{symbol:s,depth:0}];o$1.add(s);let d=ba$1(r,s);for(a.set(s,{aspectId:s,category:d?.category,severity:d?.severity,depth:0});l.length>0;){let m=l.shift();if(m.depth>=i)continue;let f=fa$1(r,m.symbol);for(let y of f){let b=y.source===m.symbol?y.target:y.source;if(c.some(v=>v.source===y.source&&v.target===y.target&&v.relation===y.relation)||c.push({source:y.source,target:y.target,relation:y.relation,weight:y.weight}),!o$1.has(b)){o$1.add(b);let v=ba$1(r,b);a.set(b,{aspectId:b,category:v?.category,severity:v?.severity,depth:m.depth+1}),l.push({symbol:b,depth:m.depth+1});}}}let u=Array.from(a.values()),g={startSymbol:s,maxHops:i,nodeCount:u.length,edgeCount:c.length,nodes:u,edges:c},p=JSON.stringify(g,null,2);return aa$1(r),r=null,o(p.length,"paradigm_aspect_graph"),{handled:!0,text:p}}catch(o$1){if(r)try{aa$1(r);}catch{}let a=JSON.stringify({error:"Failed to traverse aspect graph",details:String(o$1),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(a.length,"paradigm_aspect_graph"),{handled:true,text:a}}}async function Up(t,e){let{limit:s=20,accessType:n}=t,i=null;try{i=await $(e.rootDir);let r=ha$1(i,s*4,n),o$1=new Map;for(let d of r){let u=o$1.get(d.aspect_id);if(!u){let g=ba$1(i,d.aspect_id);u={aspectId:d.aspect_id,description:g?.description,totalCount:0,byType:{},lastAccessed:d.last_accessed},o$1.set(d.aspect_id,u);}u.totalCount+=d.count,u.byType[d.access_type]=d.count,d.last_accessed>u.lastAccessed&&(u.lastAccessed=d.last_accessed);}let a=Array.from(o$1.values()).sort((d,u)=>u.totalCount-d.totalCount).slice(0,s),c={count:a.length,...n?{filteredBy:n}:{},entries:a},l=JSON.stringify(c,null,2);return aa$1(i),i=null,o(l.length,"paradigm_aspect_heatmap"),{handled:!0,text:l}}catch(r){if(i)try{aa$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to get aspect heatmap",details:String(r),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(o$1.length,"paradigm_aspect_heatmap"),{handled:true,text:o$1}}}async function Bp(t,e){let{filePath:s}=t,n=q.isAbsolute(s)?s:q.join(e.rootDir,s);if(!E.existsSync(n)){let i=JSON.stringify({error:"File not found",filePath:n,suggestion:"Provide a valid relative or absolute file path."},null,2);return o(i.length,"paradigm_aspect_suggest_scan"),{handled:true,text:i}}try{let o$1=(await import('../utils/aspect-suggest.js')).suggestAspects(n),a={filePath:n,count:o$1.length,suggestions:o$1.map(l=>({line:l.line,code:l.code,suggestedName:l.suggestedName,category:l.suggestedCategory,description:l.suggestedDescription,confidence:l.confidence,reason:l.reason})),tip:o$1.length>0?"Review suggestions and add confirmed aspects to your .purpose files with ~ prefix and code anchors.":"No implicit aspects detected in this file."},c=JSON.stringify(a,null,2);return o(c.length,"paradigm_aspect_suggest_scan"),{handled:!0,text:c}}catch(i){let r=String(i);if(r.includes("Cannot find module")||r.includes("MODULE_NOT_FOUND")){let a=JSON.stringify({error:"Aspect suggestion engine not available",details:"The aspect-suggest utility has not been implemented yet.",suggestion:"This feature will be available in a future release. For now, manually identify implicit aspects in your code."},null,2);return o(a.length,"paradigm_aspect_suggest_scan"),{handled:true,text:a}}let o$1=JSON.stringify({error:"Failed to scan for aspect suggestions",details:r},null,2);return o(o$1.length,"paradigm_aspect_suggest_scan"),{handled:true,text:o$1}}}async function zp(t,e){let{aspectId:s,autoHeal:n}=t,i=n!==false,r=s?s.startsWith("~")?s.slice(1):s:void 0,o$1=.7,a=.85;try{let l=q.join(e.rootDir,".paradigm","config.yaml");if(E.existsSync(l)){let u=be.load(E.readFileSync(l,"utf-8"))?.drift;typeof u?.["suggest-threshold"]=="number"&&(o$1=u["suggest-threshold"]),typeof u?.["auto-heal-threshold"]=="number"&&(a=u["auto-heal-threshold"]);}}catch{}let c=null;try{c=await $(e.rootDir);let l=ia$1(c,e.rootDir,r,i,o$1,a),d=l.filter(w=>w.status==="clean").length,u=l.filter(w=>w.status==="cosmetic").length,g=l.filter(w=>w.status==="shifted").length,p=l.filter(w=>w.status==="modified").length,m=l.filter(w=>w.status==="missing").length,f=p>0||m>0,y=u>0||g>0,b=f?"drift-detected":y?"clean-with-heals":"clean",h={...r?{aspectId:r}:{scope:"all"},totalAnchors:l.length,clean:d,cosmetic:u,shifted:g,modified:p,missing:m,status:b,results:l.map(w=>({aspectId:w.aspectId,path:w.path,startLine:w.startLine,endLine:w.endLine,status:w.status,resolvedBy:w.resolvedBy,exists:w.exists,...w.status==="shifted"?{suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:w.autoHealed}:{},...w.status==="modified"&&w.currentContent?{currentContent:w.currentContent.slice(0,500)}:{}})),...u>0||g>0?{healed:[u>0?`${u} cosmetic (whitespace/formatting \u2014 hashes updated)`:"",g>0?`${g} shifted (line numbers updated via git diff${i?" \u2014 .purpose files patched":""})`:""].filter(Boolean).join(", ")}:{},...f?{suggestion:"Review drifted anchors to ensure aspects still apply. Run `paradigm scan` to re-materialize after fixing."}:{}},v=JSON.stringify(h,null,2);return aa$1(c,e.rootDir),c=null,o(v.length,"paradigm_aspect_drift"),{handled:!0,text:v}}catch(l){if(c)try{aa$1(c);}catch{}let d=JSON.stringify({error:"Failed to check aspect drift",details:String(l),suggestion:"Run `paradigm scan` to rebuild the aspect graph database."},null,2);return o(d.length,"paradigm_aspect_drift"),{handled:true,text:d}}}async function Yp(t,e){let{query:s,aspectId:n}=t,i=null;try{i=await $(e.rootDir),Ia(i,s,n);let r={confirmed:!0,query:s,aspectId:n,message:`Search mapping reinforced: "${s}" -> ${n}. Future searches for similar queries will rank this aspect higher.`},o$1=JSON.stringify(r,null,2);return aa$1(i,e.rootDir),i=null,o(o$1.length,"paradigm_aspect_confirm"),{handled:!0,text:o$1}}catch(r){if(i)try{aa$1(i);}catch{}let o$1=JSON.stringify({error:"Failed to confirm search",details:String(r)},null,2);return o(o$1.length,"paradigm_aspect_confirm"),{handled:true,text:o$1}}}function Vp(t,e){let s=q.isAbsolute(e.file_path)?e.file_path:q.join(t,e.file_path);if(!E.existsSync(s))return null;try{let i=E.readFileSync(s,"utf8").split(`
410
410
  `),r=Math.max(0,e.start_line-1),o=Math.min(i.length,e.end_line),a=i.slice(r,o).join(`
411
411
  `);return a.length>1e3?a.slice(0,1e3)+`
412
- ... (truncated)`:a}catch{return null}}function Ea(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","done","shelved","all"],description:"Filter by status (default: open)"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ha(t,e,s){switch(t){case "paradigm_task_create":{let n=await c$2(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:i},null,2)}}case "paradigm_task_list":{let n=await a$7(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${n.length} ${i} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
413
- `)}}case "paradigm_task_update":{let n=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$7(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await e$4(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await f$3(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:r},null,2)}}default:return {handled:false,text:""}}}var qa=0;function Ma(){let t=new Date().toISOString().slice(0,10);return qa++,`run_${t}_${String(qa).padStart(3,"0")}`}var La=/\{\{([^}]+)\}\}/g;function nt(t,e){if(typeof t=="string")return t.replace(La,(s,n)=>{let i=Kp(n.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(t))return t.map(s=>nt(s,e));if(t&&typeof t=="object"){let s={};for(let[n,i]of Object.entries(t))s[n]=nt(i,e);return s}return t}function Kp(t,e){let[s,...n]=t.split("."),i=n.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Fs(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Fs(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let i of s){if(n==null||typeof n!="object")return;n=n[i];}return n}function Qp(t,e){let s={};for(let[n,i]of Object.entries(t)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Fs(e,o);a!==void 0&&(s[n]=a);}}return s}function Xp(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,i]of Object.entries(t.body.match)){let r=Fs(s,n);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Zp(t,e,s){let n=Date.now(),i=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let r=i[1],o=i[2],a=nt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?nt(t.headers,s):{}},d=t.payload?nt(t.payload,s):void 0,u={url:c,method:r,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:u,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(g=>[g,`<dry-run:${g}>`])):void 0,duration_ms:Date.now()-n};try{let g={method:r,headers:l};d&&["POST","PUT","PATCH"].includes(r)&&(g.body=JSON.stringify(d));let p=await fetch(c,g),m;(p.headers.get("content-type")||"").includes("application/json")?m=await p.json():m=await p.text();let y={status:p.status,body:m},b=Xp(t.expect,y),h;t.produces&&b.pass&&(h=Qp(t.produces,m));let v;return (p.status===401||p.status===403)&&(v=t.gates[t.gates.length-1]),{id:t.id,status:b.pass?"pass":"fail",route:t.route,gates:t.gates,request:u,response:y,produced:h,expected_status:b.pass?void 0:t.expect.status,failure:b.failure,gate_that_blocked:v,duration_ms:Date.now()-n}}catch(g){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:u,failure:`Request failed: ${g.message}`,duration_ms:Date.now()-n}}}async function Ga(t,e,s){let n=Date.now(),i=await x$1(t,e);return i?Wa(t,i,s):{persona:e,run_id:Ma(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function Wa(t,e,s){let n=Date.now(),i=s.stopOnFailure!==false,r={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let f of e.journey){if(l&&i){if(o.push({id:f.id,status:"skip",route:f.route,gates:f.gates,duration_ms:0}),f.spawns)for(let b of f.spawns)c.push(b.persona);continue}let y=await Zp(f,s,r);if(o.push(y),y.status==="pass"){if(y.produced&&Object.assign(r.produces,y.produced),f.spawns)for(let b of f.spawns)a.push(b.persona);}else if(l=true,f.spawns)for(let b of f.spawns)c.push(b.persona);}let d=o.filter(f=>f.status==="pass").length,u=o.filter(f=>f.status==="fail").length,g=e.journey.length,p=o.find(f=>f.status==="fail"),m;return u===0?m=`${d}/${g} passed. All steps succeeded.`:m=`${d}/${g} passed. Failed at step ${o.indexOf(p)+1} (${p.id}): ${p.failure}`,{persona:e.id,run_id:Ma(),status:u>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function Ja(t,e,s){let n=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!i.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(i.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(f=>f.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],u={},g=s.stopOnFailure!==false;for(let f of c.order){let y=await x$1(t,f.persona);if(!y){if(d.push({persona:f.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${f.persona} not found`,duration_ms:0}),g)break;continue}if(l&&l.overrides[f.persona]){let w=l.overrides[f.persona];if(w.traits&&(y.traits={...y.traits,...w.traits}),w.journey)for(let[S,k]of Object.entries(w.journey)){let C=y.journey.find(x=>x.id===S);C&&(k.payload&&(C.payload={...C.payload,...k.payload}),k.expect&&(C.expect={...C.expect,...k.expect}));}}let b={};if(f.wait_for){let[w,S]=f.wait_for.split("."),k=d.find(x=>x.persona===w);if(k){let x=k.steps.find(_=>_.id===S);x?.produced&&(b=Object.fromEntries(Object.entries(x.produced).map(([_,R])=>[_,String(R)])));}let C=await x$1(t,w);if(C){let x=C.journey.find(_=>_.id===S);if(x?.spawns){let _=x.spawns.find(R=>R.persona===f.persona);if(_?.context){let R=u[w]||{};for(let[I,P]of Object.entries(_.context))b[I]=String(nt(P,{fixtures:{},produces:R,context:{},env:process.env}));}}}}let h=await Wa(t,y,{...s,context:b});d.push(h);let v={};for(let w of h.steps)w.produced&&Object.assign(v,w.produced);if(u[f.persona]=v,h.status==="fail"&&g)break}let p=d.filter(f=>f.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(f=>f.status!=="pass")?"fail":"pass",persona_results:d,summary:`${p}/${m} personas passed.`,duration_ms:Date.now()-n}}function Ua(t){let e=[],s=new Set;for(let n of t.journey){let r=JSON.stringify(n).match(La)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var za="paradigm-personas",eu={id:za,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Ns=false;async function Ba(t){try{let{SentinelStorage:e}=await import('./dist-5IUWRFG6.js'),s=new e;if(!Ns)try{s.registerSchema(eu),Ns=!0;}catch{Ns=!0;}let n=[];if("persona"in t){let i=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,total_steps:i.steps.length}});for(let r of i.steps){let o=r.status==="pass"?"persona.step.complete":`persona.step.${r.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,step_id:r.id,route:r.route,gates:r.gates,gates_traversed:r.gates,status:r.response?.status,body:r.response?.body,signals_fired:[],duration_ms:r.duration_ms,failure:r.failure,gate_that_blocked:r.gate_that_blocked,produced_keys:r.produced?Object.keys(r.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(r=>r.status==="pass").length,failed:i.steps.filter(r=>r.status==="fail").length,skipped:i.steps.filter(r=>r.status==="skip").length,duration_ms:i.duration_ms,spawns_triggered:i.spawns_triggered,spawns_blocked:i.spawns_blocked}});}else {let i=t;for(let r of i.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,chain_id:i.chain_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(o=>o.status==="pass").length,failed:r.steps.filter(o=>o.status==="fail").length,duration_ms:r.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:i.chain_id,status:i.status,personas_run:i.persona_results.length,personas_passed:i.persona_results.filter(r=>r.status==="pass").length,duration_ms:i.duration_ms}});}n.length>0&&s.insertEventBatch(za,"paradigm-personas",n);}catch{}}function Ya(){return [{name:"paradigm_persona_create",description:"Create a persona \u2014 named test actor with traits, trigger, fixtures, and journey steps. Writes a .persona file. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Persona ID (kebab-case, e.g., "alice-admin")'},name:{type:"string",description:'Human-readable name (e.g., "Agency Owner (Annual Billing)")'},description:{type:"string",description:"What this persona represents"},traits:{type:"object",description:"Key-value actor attributes (tier, billing, role, etc.)"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"],description:"How this persona enters the system"},spawned_by:{type:"string",description:"persona-id.step-id (required if type != root)"},context:{type:"object",description:"Data passed from parent spawn"}},required:["type"]},fixtures:{type:"object",description:"Test data for this persona (email, password, API keys, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering"},journey:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case)"},description:{type:"string"},route:{type:"string",description:'METHOD /path (e.g., "POST /api/auth/signup")'},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object",description:"Request body. Supports {{produces.X}} and {{fixtures.X}} interpolation."},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object",properties:{has:{type:"array",items:{type:"string"}},match:{type:"object"}}}},required:["status"]},produces:{type:"object",description:"Values to extract from response for later steps"},spawns:{type:"array",items:{type:"object",properties:{persona:{type:"string"},via:{type:"string"},context:{type:"object"}},required:["persona","via"]}},signals:{type:"array",items:{type:"string"},description:"!signal references expected to fire"}},required:["id","route","gates","expect"]}}},required:["id","name","trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_get",description:"Get full persona detail \u2014 journey, traits, spawn chain, validation status. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_list",description:"List personas with optional filters \u2014 tag, trigger type, gate, flow. ~200 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:"Filter by tag"},trigger_type:{type:"string",enum:["root","invitation","signup","api"],description:"Filter by trigger type"},gate:{type:"string",description:"Filter by gate (show personas that traverse this gate)"},flow:{type:"string",description:"Filter by flow (show personas that exercise this flow)"},limit:{type:"number",description:"Maximum results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_update",description:"Update persona fields \u2014 traits, fixtures, journey steps, tags. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"},name:{type:"string"},description:{type:"string"},traits:{type:"object"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"]},spawned_by:{type:"string"},context:{type:"object"}}},fixtures:{type:"object"},tags:{type:"array",items:{type:"string"}},journey:{type:"array",description:"Replace entire journey. Use paradigm_persona_add_step for surgical edits."}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_delete",description:"Delete a persona. Warns if other personas spawn from it. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_add_step",description:"Add a journey step to a persona. Validates gates, route format, and produce/consume chains. ~150 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case, unique within persona)"},description:{type:"string"},route:{type:"string",description:"METHOD /path"},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object"},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object"}},required:["status"]},produces:{type:"object"},spawns:{type:"array"},signals:{type:"array",items:{type:"string"}}},required:["id","route","gates","expect"]},after:{type:"string",description:"Insert after this step ID. Omit to append."}},required:["persona_id","step"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_remove_step",description:"Remove a journey step. Warns if it produces data consumed by later steps or spawns other personas. ~100 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step_id:{type:"string",description:"Step ID to remove"}},required:["persona_id","step_id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_validate",description:"Full persona validation \u2014 schema + cross-refs + Sentinel event matching with exact assertion results. Compares expected journey outcomes against actual Sentinel events. ~300 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Validate one persona. Omit for all."},deep:{type:"boolean",description:"Include cross-reference and coverage analysis (default: false)"},sentinel:{type:"boolean",description:"Compare against Sentinel events (default: true when available)"},run_id:{type:"string",description:"Validate against a specific run. Omit for latest."},chain_id:{type:"string",description:"Validate against a specific chain execution."},environment:{type:"string",description:"Filter Sentinel events by environment (dev, staging, prod, ci)."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_coverage",description:"Coverage report \u2014 which routes/gates/flows have persona coverage, which don't. Compares against portal.yaml. ~250 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_affected",description:"Given a symbol (^gate, $flow, route), return affected personas and their steps. Used by ripple. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to check (e.g., "^authenticated", "$checkout-flow", "POST /api/orders")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_run",description:"Execute a persona journey or chain against a running server. Interpolates templates, sends requests step-by-step, validates responses. Supports dry-run mode. ~500 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Run a single persona journey"},chain_id:{type:"string",description:"Run a named chain (overrides persona_id)"},base_url:{type:"string",description:'Server base URL (e.g., "http://localhost:3000")'},dry_run:{type:"boolean",description:"Validate and interpolate without making requests (default: false)"},stop_on_failure:{type:"boolean",description:"Stop on first failing step (default: true)"},permutation:{type:"string",description:"Permutation ID from chain definition"}},required:["base_url"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Va(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await y$1(s.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),i=await x$1(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:i},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,i=await x$1(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let r=await D(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let n=await w(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=n.map(r=>({id:r.id,name:r.name,trigger:r.trigger.type,steps:r.journey.length,gates:[...new Set(r.journey.flatMap(o=>o.gates))],tags:r.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:i},null,2)}}case "paradigm_persona_update":{let n=e.id,i={};if(e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),e.traits!==void 0&&(i.traits=e.traits),e.trigger!==void 0&&(i.trigger=e.trigger),e.fixtures!==void 0&&(i.fixtures=e.fixtures),e.tags!==void 0&&(i.tags=e.tags),e.journey!==void 0&&(i.journey=e.journey),!await z$1(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await x$1(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,i=await A$1(s.rootDir,n);return i.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:i.warnings,hint:i.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await B(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let i=await x$1(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:i?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await C(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let n=e.deep??false,i=e.sentinel??true,r={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await x$1(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let u=await D(s.rootDir,d,n);if(i)try{let g=await G(d,r);u.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(u.valid=!1);}catch{}return {handled:true,text:JSON.stringify(u,null,2)}}let o=await w(s.rootDir),a=await Promise.all(o.map(async d=>{let u=await D(s.rootDir,d,n);if(i)try{let g=await G(d,r);u.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(u.valid=!1);}catch{}return u})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await E$1(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,i=await F(s.rootDir,n);return i.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:i},null,2)}}case "paradigm_persona_run":{let n=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await Ja(s.rootDir,e.chain_id,{baseUrl:n,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await Ba(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await x$1(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Ua(o);if(!a.valid&&!i)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await Ga(s.rootDir,e.persona_id,{baseUrl:n,dryRun:i,stopOnFailure:r});return i||await Ba(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var tu=".paradigm/graphs",qs={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Es=200,Hs=60,st=20,Dn=40,Ka=50,nu=60;function Xa(){return [{name:"paradigm_graph_generate",description:"Generate a named GraphState JSON file for the Paradigm Symbol Graph UI. Writes to .paradigm/graphs/{name}.graph.json. View saved graphs with `paradigm graph` CLI. Returns a summary with node/edge counts and file path. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Graph name (kebab-case). Used as filename: {name}.graph.json. E.g. "auth-flow", "full-project", "checkout-subsystem".'},symbols:{type:"array",items:{type:"string"},description:'Symbol names to include (e.g. ["#auth-middleware", "^authenticated"]). Omit to include all from scan-index.'},groups:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"Group display label"},symbols:{type:"array",items:{type:"string"},description:"Symbol names belonging to this group"}},required:["label","symbols"]},description:"Optional groupings of symbols."},links:{type:"array",items:{type:"object",properties:{source:{type:"string",description:"Source group label"},target:{type:"string",description:"Target group label"},label:{type:"string",description:"Edge label"}},required:["source","target"]},description:"Edges between groups (by label name)."}},required:["name"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Za(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",i=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=ru(s.rootDir,e.symbols,e.groups,e.links,n),o$1=JSON.stringify(r,null,2),a=q.join(s.rootDir,tu);E.existsSync(a)||E.mkdirSync(a,{recursive:!0});let c=q.join(a,`${i}.graph.json`);E.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:n,slug:i,nodes:r.nodes.length,edges:r.edges.length,size:`${(o$1.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return o(l.length,t),{handled:!0,text:l}}catch(n){let i=JSON.stringify({error:n.message},null,2);return o(i.length,t),{handled:true,text:i}}}var su={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function iu(t){let e=q.join(t,".paradigm","scan-index.json");if(!E.existsSync(e))return [];let s=JSON.parse(E.readFileSync(e,"utf8")),n=[];for(let[i,r]of Object.entries(su)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:r,prefix:qs[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function Qa(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function ru(t,e,s,n,i="Generated Graph"){let r=iu(t),o;e&&e.length>0?o=e.map(p=>Qa(p,r)).filter(Boolean):o=r;let a=[],c=[],l=new Map,d=new Set,u=0;if(s&&s.length>0)for(let p of s){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(p.label,m);let f=p.symbols.map(k=>Qa(k,o)).filter(Boolean),y=Math.ceil(Math.sqrt(f.length)),b=Math.ceil(f.length/y);for(let k=0;k<f.length;k++){let C=f[k],x=k%y,_=Math.floor(k/y),R=qs[C.category]||"#";a.push({id:`sym-${C.id}`,type:"symbolNode",position:{x:Dn+x*(Es+st),y:Ka+Dn+_*(Hs+st)},parentId:m,data:{type:"symbol",symbol:C,label:`${R}${C.name}`}}),d.add(C.id);}let h=Math.max(y,1),v=Math.max(b,1),w=Dn*2+h*Es+(h-1)*st,S=Ka+Dn*2+v*Hs+(v-1)*st;a.unshift({id:m,type:"groupNode",position:{x:u,y:0},style:{width:w,height:S},data:{type:"group",label:p.label}}),u+=w+nu;}let g=o.filter(p=>!d.has(p.id));if(g.length>0){let p=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(g.length));for(let f=0;f<g.length;f++){let y=g[f],b=f%m,h=Math.floor(f/m),v=qs[y.category]||"#";a.push({id:`sym-${y.id}`,type:"symbolNode",position:{x:b*(Es+st),y:p+h*(Hs+st)},data:{type:"symbol",symbol:y,label:`${v}${y.name}`}});}}if(n&&n.length>0)for(let p of n){let m=l.get(p.source),f=l.get(p.target);m&&f&&c.push({id:`e-${m}-${f}`,source:m,target:f,type:"default",label:p.label,data:{label:p.label}});}return {version:"1.0",name:i,projectId:q.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var pe=["specify","plan","task","implement","validate"],$t=".paradigm/pipeline",ec={"add-feature":{gates:{specify:"manual",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Standard feature addition with manual spec/plan review"},"bug-fix":{gates:{specify:"auto",plan:"auto",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Quick bug fix with automated gates except validation"},"security-change":{gates:{specify:"manual",plan:"manual",task:"manual",implement:"manual",validate:"manual"},description:"Security-sensitive change with all-manual gates"},refactor:{gates:{specify:"auto",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Code refactoring with manual plan review"}};function On(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function At(t,e){let s=On(e),n=q.join(t,$t,`${s}.yaml`);return E.existsSync(n)?be.load(E.readFileSync(n,"utf8")):null}function It(t,e){let s=On(e.feature),n=q.join(t,$t);E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${s}.yaml`);return E.writeFileSync(i,be.dump(e,{lineWidth:120}),"utf8"),i}function tc(t){let e=q.join(t,$t);return E.existsSync(e)?E.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return be.load(E.readFileSync(q.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function ou(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:On(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function au(t){let e=pe.indexOf(t);return e<pe.length-1?pe[e+1]:null}function nc(t,e){let s=On(e.feature),n=q.join(t,$t,"completed");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${s}.yaml`);E.writeFileSync(i,be.dump(e,{lineWidth:120}),"utf8");let r=q.join(t,$t,`${s}.yaml`);E.existsSync(r)&&E.unlinkSync(r);}function sc(){return [{name:"paradigm_pipeline_start",description:"Create a new spec pipeline for a feature. Uses templates (add-feature, bug-fix, security-change, refactor) or custom gate config. Returns pipeline state. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name or description (will be slugified)"},template:{type:"string",enum:["add-feature","bug-fix","security-change","refactor"],description:"Pipeline template (default: add-feature)"},gates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Custom gate config (overrides template)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_status",description:"Get pipeline status \u2014 current stage, progress, gate config. Pass feature name for specific pipeline, or omit for all active pipelines. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name (omit to list all active pipelines)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pipeline_advance",description:"Advance pipeline past the current gate. Marks current stage as approved and moves to the next stage. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},approved_by:{type:"string",description:"Who approved this gate (default: agent)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_configure",description:"Change gate modes on an active pipeline. Use to escalate or relax gates during development. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},updates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Stage-to-gate-mode updates"},reason:{type:"string",description:"Reason for the configuration change"}},required:["feature","updates","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_escalate",description:"Flag a pipeline stage for user input. Use when a gate requires a decision the agent cannot make autonomously. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},stage:{type:"string",enum:["specify","plan","task","implement","validate"],description:"Stage to escalate"},question:{type:"string",description:"Question for the user"},options:{type:"array",items:{type:"string"},description:"Available options for the user"},context:{type:"object",description:"Additional context for the decision"}},required:["feature","stage","question","options"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_abort",description:"Cancel and archive an active pipeline. Use when a feature is abandoned or no longer needed. ~100 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_pipeline_list",description:"List all active pipelines with current stages and progress. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ic(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,i=e.template||"add-feature",r=e.gates,o;if(r)o={specify:r.specify||"manual",plan:r.plan||"manual",task:r.task||"auto",implement:r.implement||"sentinel",validate:r.validate||"sentinel"};else {let l=ec[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(ec)})};o=l.gates;}let a=ou(n,o,i),c=It(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let r=At(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=pe.filter(a=>r.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:r.feature,created:r.created,template:r.template,current_stage:r.current_stage,progress:`${o}/${pe.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=tc(s.rootDir);return i.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines. Use paradigm_pipeline_start to create one."})}:{handled:true,text:JSON.stringify({count:i.length,pipelines:i.map(r=>{let o=pe.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${pe.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,i=e.approved_by||"agent",r=At(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=r.current_stage,a=r.gate_config[o],c=au(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",It(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(It(s.rootDir,r),nc(s.rootDir,r),{handled:true,text:JSON.stringify({completed:true,feature:r.feature,message:`Pipeline '${r.feature}' completed and archived.`,stages:r.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,i=e.updates,r=e.reason,o=At(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(i))if(pe.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:pe,valid_modes:["auto","manual","sentinel"]})}:(It(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=At(s.rootDir,n);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,It(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,i=At(s.rootDir,n);return i?(nc(s.rootDir,i),{handled:true,text:JSON.stringify({aborted:true,feature:i.feature,message:`Pipeline '${i.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=tc(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(i=>{let r=pe.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${pe.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var cu=q.join(Fo.homedir(),".conductor"),ot=q.join(cu,"sessions");function oc(){E.existsSync(ot)||E.mkdirSync(ot,{recursive:true});}function Ls(t){oc();let e={...t,registeredAt:new Date().toISOString()},s=q.join(ot,`${t.pid}.json`);return E.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function An(t){let e=q.join(ot,`${t}.json`);return E.existsSync(e)?(E.unlinkSync(e),true):false}function Gs(){oc();let t=E.readdirSync(ot).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=E.readFileSync(q.join(ot,s),"utf-8"),i=JSON.parse(n);e.push(i);}catch{}return e}function ac(){let t=Gs(),e=0;for(let s of t)lu(s.pid)||(An(s.pid),e++);return e}function lu(t){try{return process.kill(t,0),!0}catch{return false}}function Ws(){try{return execSync(`osascript -e '
412
+ ... (truncated)`:a}catch{return null}}function Ea(){return [{name:"paradigm_task_create",description:"Create a task (persistent scratch-pad item that survives context windows). Returns the created task ID. ~100 tokens.",inputSchema:{type:"object",properties:{blurb:{type:"string",description:"One-line task description"},priority:{type:"string",enum:["high","medium","low"],description:"Priority level (default: medium)"},tags:{type:"array",items:{type:"string"},description:"Tags \u2014 symbols (#component), freeform labels, etc."},related_lore:{type:"array",items:{type:"string"},description:"Linked lore entry IDs"}},required:["blurb"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_list",description:"List/filter tasks by status, priority, tags, or symbols. Returns task list sorted by priority then date. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["open","done","shelved","all"],description:"Filter by status (default: open)"},priority:{type:"string",enum:["high","medium","low"],description:"Filter by priority"},tag:{type:"string",description:"Filter by tag (symbol or freeform)"},limit:{type:"number",description:"Maximum results (default: 20)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_task_update",description:"Update a task (blurb, priority, status, tags). Returns updated task. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Task ID (e.g., "T-2026-02-26-001")'},blurb:{type:"string",description:"New description"},priority:{type:"string",enum:["high","medium","low"]},status:{type:"string",enum:["open","done","shelved"]},tags:{type:"array",items:{type:"string"},description:"Replace tags"},related_lore:{type:"array",items:{type:"string"},description:"Related lore entry IDs (includes former assessment entries)"},related_assessments:{type:"array",items:{type:"string"},description:"(Deprecated \u2014 use related_lore) Alias for related_lore"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_done",description:"Mark a task as done. Shorthand for update with status=done. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_task_shelve",description:"Shelve a task (not now, not never). Shorthand for update with status=shelved. Returns confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Task ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Ha(t,e,s){switch(t){case "paradigm_task_create":{let n=await c$3(s.rootDir,{blurb:e.blurb,priority:e.priority,tags:e.tags,related_lore:e.related_lore}),i=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({created:n,task:i},null,2)}}case "paradigm_task_list":{let n=await a$7(s.rootDir,{status:e.status||"open",priority:e.priority,tag:e.tag,limit:e.limit||20}),i=e.status||"open",r=[`${n.length} ${i} task(s):`];for(let o of n){let a=o.tags.length>0?` [${o.tags.join(", ")}]`:"";r.push(` [${o.priority}] ${o.id}: ${o.blurb}${a}`);}return {handled:true,text:r.join(`
413
+ `)}}case "paradigm_task_update":{let n=e.id,i={};if(e.blurb!==void 0&&(i.blurb=e.blurb),e.priority!==void 0&&(i.priority=e.priority),e.status!==void 0&&(i.status=e.status),e.tags!==void 0&&(i.tags=e.tags),e.related_lore!==void 0&&(i.related_lore=e.related_lore),e.related_assessments!==void 0&&(i.related_assessments=e.related_assessments),!await d$6(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let o=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,task:o},null,2)}}case "paradigm_task_done":{let n=e.id;if(!await e$4(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({completed:n,task:r,hint:"Consider recording a lore entry with arc:* tags if this was a significant milestone."},null,2)}}case "paradigm_task_shelve":{let n=e.id;if(!await f$3(s.rootDir,n))return {handled:true,text:JSON.stringify({error:`Task ${n} not found`})};let r=await b$7(s.rootDir,n);return {handled:true,text:JSON.stringify({shelved:n,task:r},null,2)}}default:return {handled:false,text:""}}}var qa=0;function Ma(){let t=new Date().toISOString().slice(0,10);return qa++,`run_${t}_${String(qa).padStart(3,"0")}`}var La=/\{\{([^}]+)\}\}/g;function nt(t,e){if(typeof t=="string")return t.replace(La,(s,n)=>{let i=Kp(n.trim(),e);return i!==void 0?String(i):s});if(Array.isArray(t))return t.map(s=>nt(s,e));if(t&&typeof t=="object"){let s={};for(let[n,i]of Object.entries(t))s[n]=nt(i,e);return s}return t}function Kp(t,e){let[s,...n]=t.split("."),i=n.join(".");switch(s){case "fixtures":return e.fixtures[i];case "produces":return Fs(e.produces,i);case "context":case "parent":return e.context[i];case "env":return e.env[i]??process.env[i];default:return}}function Fs(t,e){let s=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let i of s){if(n==null||typeof n!="object")return;n=n[i];}return n}function Qp(t,e){let s={};for(let[n,i]of Object.entries(t)){let r=i.match(/\{\{response\.(.+)\}\}/);if(r){let o=r[1],a=Fs(e,o);a!==void 0&&(s[n]=a);}}return s}function Xp(t,e){if(e.status!==t.status)return {pass:false,failure:`Status mismatch: expected ${t.status}, got ${e.status}`};if(t.body){let s=e.body;if(t.body.has){for(let n of t.body.has)if(s===null||typeof s!="object"||!(n in s))return {pass:false,failure:`Expected body to have key "${n}"`}}if(t.body.match)for(let[n,i]of Object.entries(t.body.match)){let r=Fs(s,n);if(JSON.stringify(r)!==JSON.stringify(i))return {pass:false,failure:`Body mismatch at "${n}": expected ${JSON.stringify(i)}, got ${JSON.stringify(r)}`}}}return {pass:true}}async function Zp(t,e,s){let n=Date.now(),i=t.route.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(.*)/);if(!i)return {id:t.id,status:"fail",route:t.route,gates:t.gates,failure:`Invalid route format: ${t.route}`,duration_ms:Date.now()-n};let r=i[1],o=i[2],a=nt(o,s),c=`${e.baseUrl.replace(/\/$/,"")}${a}`,l={"Content-Type":"application/json",...t.headers?nt(t.headers,s):{}},d=t.payload?nt(t.payload,s):void 0,u={url:c,method:r,headers:t.headers?l:void 0,payload:d};if(e.dryRun)return {id:t.id,status:"pass",route:t.route,gates:t.gates,request:u,produced:t.produces?Object.fromEntries(Object.keys(t.produces).map(g=>[g,`<dry-run:${g}>`])):void 0,duration_ms:Date.now()-n};try{let g={method:r,headers:l};d&&["POST","PUT","PATCH"].includes(r)&&(g.body=JSON.stringify(d));let p=await fetch(c,g),m;(p.headers.get("content-type")||"").includes("application/json")?m=await p.json():m=await p.text();let y={status:p.status,body:m},b=Xp(t.expect,y),h;t.produces&&b.pass&&(h=Qp(t.produces,m));let v;return (p.status===401||p.status===403)&&(v=t.gates[t.gates.length-1]),{id:t.id,status:b.pass?"pass":"fail",route:t.route,gates:t.gates,request:u,response:y,produced:h,expected_status:b.pass?void 0:t.expect.status,failure:b.failure,gate_that_blocked:v,duration_ms:Date.now()-n}}catch(g){return {id:t.id,status:"fail",route:t.route,gates:t.gates,request:u,failure:`Request failed: ${g.message}`,duration_ms:Date.now()-n}}}async function Ga(t,e,s){let n=Date.now(),i=await x$1(t,e);return i?Wa(t,i,s):{persona:e,run_id:Ma(),status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${e} not found`,duration_ms:Date.now()-n}}async function Wa(t,e,s){let n=Date.now(),i=s.stopOnFailure!==false,r={fixtures:e.fixtures||{},produces:{},context:s.context||{},env:process.env},o=[],a=[],c=[],l=false;for(let f of e.journey){if(l&&i){if(o.push({id:f.id,status:"skip",route:f.route,gates:f.gates,duration_ms:0}),f.spawns)for(let b of f.spawns)c.push(b.persona);continue}let y=await Zp(f,s,r);if(o.push(y),y.status==="pass"){if(y.produced&&Object.assign(r.produces,y.produced),f.spawns)for(let b of f.spawns)a.push(b.persona);}else if(l=true,f.spawns)for(let b of f.spawns)c.push(b.persona);}let d=o.filter(f=>f.status==="pass").length,u=o.filter(f=>f.status==="fail").length,g=e.journey.length,p=o.find(f=>f.status==="fail"),m;return u===0?m=`${d}/${g} passed. All steps succeeded.`:m=`${d}/${g} passed. Failed at step ${o.indexOf(p)+1} (${p.id}): ${p.failure}`,{persona:e.id,run_id:Ma(),status:u>0?"fail":"pass",steps:o,spawns_triggered:a,spawns_blocked:c,summary:m,duration_ms:Date.now()-n}}async function Ja(t,e,s){let n=Date.now(),i=await import('fs'),r=await import('path'),o=await import('js-yaml'),a=r.join(t,".paradigm","personas","chains",`${e}.yaml`);if(!i.existsSync(a))return {chain_id:e,status:"error",persona_results:[],summary:`Chain ${e} not found`,duration_ms:Date.now()-n};let c=o.load(i.readFileSync(a,"utf8")),l;if(s.permutation&&c.permutations&&(l=c.permutations.find(f=>f.id===s.permutation),!l))return {chain_id:e,status:"error",persona_results:[],summary:`Permutation ${s.permutation} not found in chain ${e}`,duration_ms:Date.now()-n};let d=[],u={},g=s.stopOnFailure!==false;for(let f of c.order){let y=await x$1(t,f.persona);if(!y){if(d.push({persona:f.persona,status:"error",steps:[],spawns_triggered:[],spawns_blocked:[],summary:`Persona ${f.persona} not found`,duration_ms:0}),g)break;continue}if(l&&l.overrides[f.persona]){let w=l.overrides[f.persona];if(w.traits&&(y.traits={...y.traits,...w.traits}),w.journey)for(let[S,k]of Object.entries(w.journey)){let C=y.journey.find(x=>x.id===S);C&&(k.payload&&(C.payload={...C.payload,...k.payload}),k.expect&&(C.expect={...C.expect,...k.expect}));}}let b={};if(f.wait_for){let[w,S]=f.wait_for.split("."),k=d.find(x=>x.persona===w);if(k){let x=k.steps.find(_=>_.id===S);x?.produced&&(b=Object.fromEntries(Object.entries(x.produced).map(([_,R])=>[_,String(R)])));}let C=await x$1(t,w);if(C){let x=C.journey.find(_=>_.id===S);if(x?.spawns){let _=x.spawns.find(R=>R.persona===f.persona);if(_?.context){let R=u[w]||{};for(let[I,P]of Object.entries(_.context))b[I]=String(nt(P,{fixtures:{},produces:R,context:{},env:process.env}));}}}}let h=await Wa(t,y,{...s,context:b});d.push(h);let v={};for(let w of h.steps)w.produced&&Object.assign(v,w.produced);if(u[f.persona]=v,h.status==="fail"&&g)break}let p=d.filter(f=>f.status==="pass").length,m=c.order.length;return {chain_id:e,status:d.some(f=>f.status!=="pass")?"fail":"pass",persona_results:d,summary:`${p}/${m} personas passed.`,duration_ms:Date.now()-n}}function Ua(t){let e=[],s=new Set;for(let n of t.journey){let r=JSON.stringify(n).match(La)||[];for(let o of r){let a=o.replace("{{","").replace("}}","").trim(),[c,...l]=a.split("."),d=l.join(".");switch(c){case "fixtures":!t.fixtures||d in t.fixtures;break;case "produces":s.has(d)||e.push({step:n.id,template:o,error:`{{produces.${d}}} used but not produced by a prior step`});break;case "context":case "parent":break;case "env":break;case "response":break;default:e.push({step:n.id,template:o,error:`Unknown namespace "${c}" in ${o}`});}}if(n.produces)for(let o of Object.keys(n.produces))s.add(o);}return {valid:e.length===0,errors:e}}var za="paradigm-personas",eu={id:za,version:"1.0",name:"Paradigm Personas",description:"Events from persona journey and chain execution",scope:{key:"persona_id",label:"Persona"},eventTypes:{"persona.run.start":{category:"lifecycle",severity:"info"},"persona.step.pass":{category:"assertion",severity:"info"},"persona.step.fail":{category:"assertion",severity:"warning"},"persona.step.skip":{category:"lifecycle",severity:"info"},"persona.run.complete":{category:"lifecycle",severity:"info"},"persona.chain.complete":{category:"lifecycle",severity:"info"},"persona.coverage.report":{category:"analysis",severity:"info"}}},Ns=false;async function Ba(t){try{let{SentinelStorage:e}=await import('./dist-W3XCATBJ.js'),s=new e;if(!Ns)try{s.registerSchema(eu),Ns=!0;}catch{Ns=!0;}let n=[];if("persona"in t){let i=t;n.push({type:"persona.run.start",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,total_steps:i.steps.length}});for(let r of i.steps){let o=r.status==="pass"?"persona.step.complete":`persona.step.${r.status}`;n.push({type:o,timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,step_id:r.id,route:r.route,gates:r.gates,gates_traversed:r.gates,status:r.response?.status,body:r.response?.body,signals_fired:[],duration_ms:r.duration_ms,failure:r.failure,gate_that_blocked:r.gate_that_blocked,produced_keys:r.produced?Object.keys(r.produced):[]}});}n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:i.persona,data:{persona_id:i.persona,run_id:i.run_id,status:i.status,total_steps:i.steps.length,passed:i.steps.filter(r=>r.status==="pass").length,failed:i.steps.filter(r=>r.status==="fail").length,skipped:i.steps.filter(r=>r.status==="skip").length,duration_ms:i.duration_ms,spawns_triggered:i.spawns_triggered,spawns_blocked:i.spawns_blocked}});}else {let i=t;for(let r of i.persona_results)n.push({type:"persona.run.complete",timestamp:new Date().toISOString(),scopeValue:r.persona,data:{persona_id:r.persona,run_id:r.run_id,chain_id:i.chain_id,status:r.status,total_steps:r.steps.length,passed:r.steps.filter(o=>o.status==="pass").length,failed:r.steps.filter(o=>o.status==="fail").length,duration_ms:r.duration_ms}});n.push({type:"persona.chain.complete",timestamp:new Date().toISOString(),data:{chain_id:i.chain_id,status:i.status,personas_run:i.persona_results.length,personas_passed:i.persona_results.filter(r=>r.status==="pass").length,duration_ms:i.duration_ms}});}n.length>0&&s.insertEventBatch(za,"paradigm-personas",n);}catch{}}function Ya(){return [{name:"paradigm_persona_create",description:"Create a persona \u2014 named test actor with traits, trigger, fixtures, and journey steps. Writes a .persona file. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Persona ID (kebab-case, e.g., "alice-admin")'},name:{type:"string",description:'Human-readable name (e.g., "Agency Owner (Annual Billing)")'},description:{type:"string",description:"What this persona represents"},traits:{type:"object",description:"Key-value actor attributes (tier, billing, role, etc.)"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"],description:"How this persona enters the system"},spawned_by:{type:"string",description:"persona-id.step-id (required if type != root)"},context:{type:"object",description:"Data passed from parent spawn"}},required:["type"]},fixtures:{type:"object",description:"Test data for this persona (email, password, API keys, etc.)"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering"},journey:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case)"},description:{type:"string"},route:{type:"string",description:'METHOD /path (e.g., "POST /api/auth/signup")'},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object",description:"Request body. Supports {{produces.X}} and {{fixtures.X}} interpolation."},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object",properties:{has:{type:"array",items:{type:"string"}},match:{type:"object"}}}},required:["status"]},produces:{type:"object",description:"Values to extract from response for later steps"},spawns:{type:"array",items:{type:"object",properties:{persona:{type:"string"},via:{type:"string"},context:{type:"object"}},required:["persona","via"]}},signals:{type:"array",items:{type:"string"},description:"!signal references expected to fire"}},required:["id","route","gates","expect"]}}},required:["id","name","trigger"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_get",description:"Get full persona detail \u2014 journey, traits, spawn chain, validation status. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_list",description:"List personas with optional filters \u2014 tag, trigger type, gate, flow. ~200 tokens.",inputSchema:{type:"object",properties:{tag:{type:"string",description:"Filter by tag"},trigger_type:{type:"string",enum:["root","invitation","signup","api"],description:"Filter by trigger type"},gate:{type:"string",description:"Filter by gate (show personas that traverse this gate)"},flow:{type:"string",description:"Filter by flow (show personas that exercise this flow)"},limit:{type:"number",description:"Maximum results (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_update",description:"Update persona fields \u2014 traits, fixtures, journey steps, tags. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"},name:{type:"string"},description:{type:"string"},traits:{type:"object"},trigger:{type:"object",properties:{type:{type:"string",enum:["root","invitation","signup","api"]},spawned_by:{type:"string"},context:{type:"object"}}},fixtures:{type:"object"},tags:{type:"array",items:{type:"string"}},journey:{type:"array",description:"Replace entire journey. Use paradigm_persona_add_step for surgical edits."}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_delete",description:"Delete a persona. Warns if other personas spawn from it. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Persona ID"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_add_step",description:"Add a journey step to a persona. Validates gates, route format, and produce/consume chains. ~150 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step:{type:"object",properties:{id:{type:"string",description:"Step ID (kebab-case, unique within persona)"},description:{type:"string"},route:{type:"string",description:"METHOD /path"},flow:{type:"string",description:"$flow reference"},gates:{type:"array",items:{type:"string"},description:"^gate references"},headers:{type:"object"},payload:{type:"object"},expect:{type:"object",properties:{status:{type:"number"},body:{type:"object"}},required:["status"]},produces:{type:"object"},spawns:{type:"array"},signals:{type:"array",items:{type:"string"}}},required:["id","route","gates","expect"]},after:{type:"string",description:"Insert after this step ID. Omit to append."}},required:["persona_id","step"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_persona_remove_step",description:"Remove a journey step. Warns if it produces data consumed by later steps or spawns other personas. ~100 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Persona ID"},step_id:{type:"string",description:"Step ID to remove"}},required:["persona_id","step_id"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_persona_validate",description:"Full persona validation \u2014 schema + cross-refs + Sentinel event matching with exact assertion results. Compares expected journey outcomes against actual Sentinel events. ~300 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Validate one persona. Omit for all."},deep:{type:"boolean",description:"Include cross-reference and coverage analysis (default: false)"},sentinel:{type:"boolean",description:"Compare against Sentinel events (default: true when available)"},run_id:{type:"string",description:"Validate against a specific run. Omit for latest."},chain_id:{type:"string",description:"Validate against a specific chain execution."},environment:{type:"string",description:"Filter Sentinel events by environment (dev, staging, prod, ci)."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_coverage",description:"Coverage report \u2014 which routes/gates/flows have persona coverage, which don't. Compares against portal.yaml. ~250 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_affected",description:"Given a symbol (^gate, $flow, route), return affected personas and their steps. Used by ripple. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to check (e.g., "^authenticated", "$checkout-flow", "POST /api/orders")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_persona_run",description:"Execute a persona journey or chain against a running server. Interpolates templates, sends requests step-by-step, validates responses. Supports dry-run mode. ~500 tokens.",inputSchema:{type:"object",properties:{persona_id:{type:"string",description:"Run a single persona journey"},chain_id:{type:"string",description:"Run a named chain (overrides persona_id)"},base_url:{type:"string",description:'Server base URL (e.g., "http://localhost:3000")'},dry_run:{type:"boolean",description:"Validate and interpolate without making requests (default: false)"},stop_on_failure:{type:"boolean",description:"Stop on first failing step (default: true)"},permutation:{type:"string",description:"Permutation ID from chain definition"}},required:["base_url"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Va(t,e,s){switch(t){case "paradigm_persona_create":try{let n=await y$1(s.rootDir,{id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags,journey:e.journey}),i=await x$1(s.rootDir,n);return {handled:!0,text:JSON.stringify({created:n,persona:i},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_get":{let n=e.id,i=await x$1(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let r=await D(s.rootDir,i);return {handled:true,text:JSON.stringify({persona:i,validation:r},null,2)}}case "paradigm_persona_list":{let n=await w(s.rootDir,{tag:e.tag,trigger_type:e.trigger_type,gate:e.gate,flow:e.flow,limit:e.limit||50}),i=n.map(r=>({id:r.id,name:r.name,trigger:r.trigger.type,steps:r.journey.length,gates:[...new Set(r.journey.flatMap(o=>o.gates))],tags:r.tags||[]}));return {handled:true,text:JSON.stringify({count:n.length,personas:i},null,2)}}case "paradigm_persona_update":{let n=e.id,i={};if(e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),e.traits!==void 0&&(i.traits=e.traits),e.trigger!==void 0&&(i.trigger=e.trigger),e.fixtures!==void 0&&(i.fixtures=e.fixtures),e.tags!==void 0&&(i.tags=e.tags),e.journey!==void 0&&(i.journey=e.journey),!await z$1(s.rootDir,n,i))return {handled:true,text:JSON.stringify({error:`Persona ${n} not found`})};let o=await x$1(s.rootDir,n);return {handled:true,text:JSON.stringify({updated:n,persona:o},null,2)}}case "paradigm_persona_delete":{let n=e.id,i=await A$1(s.rootDir,n);return i.deleted?{handled:true,text:JSON.stringify({deleted:n,warnings:i.warnings,hint:i.warnings.length>0?"Other personas reference this one. Update or delete them to avoid broken spawn chains.":void 0},null,2)}:{handled:true,text:JSON.stringify({error:`Persona ${n} not found`})}}case "paradigm_persona_add_step":try{if(!await B(s.rootDir,e.persona_id,e.step,e.after))return {handled:!0,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let i=await x$1(s.rootDir,e.persona_id);return {handled:!0,text:JSON.stringify({added:e.step.id,persona_id:e.persona_id,total_steps:i?.journey.length},null,2)}}catch(n){return {handled:true,text:JSON.stringify({error:n.message})}}case "paradigm_persona_remove_step":{let n=await C(s.rootDir,e.persona_id,e.step_id);return n.removed?{handled:true,text:JSON.stringify({removed:e.step_id,persona_id:e.persona_id,warnings:n.warnings},null,2)}:{handled:true,text:JSON.stringify({error:`Step ${e.step_id} not found in persona ${e.persona_id}`})}}case "paradigm_persona_validate":{let n=e.deep??false,i=e.sentinel??true,r={run_id:e.run_id,chain_id:e.chain_id,environment:e.environment};if(e.persona_id){let d=await x$1(s.rootDir,e.persona_id);if(!d)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let u=await D(s.rootDir,d,n);if(i)try{let g=await G(d,r);u.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(u.valid=!1);}catch{}return {handled:true,text:JSON.stringify(u,null,2)}}let o=await w(s.rootDir),a=await Promise.all(o.map(async d=>{let u=await D(s.rootDir,d,n);if(i)try{let g=await G(d,r);u.sentinel_assertions=g,(g.summary.failed>0||g.summary.unmatched>0)&&(u.valid=!1);}catch{}return u})),c=a.filter(d=>d.valid).length,l=a.filter(d=>!d.valid).length;return {handled:true,text:JSON.stringify({total:a.length,valid:c,invalid:l,results:a.filter(d=>!d.valid||d.warnings.length>0||d.sentinel_assertions)},null,2)}}case "paradigm_persona_coverage":{let n=await E$1(s.rootDir);return {handled:true,text:JSON.stringify(n,null,2)}}case "paradigm_persona_affected":{let n=e.symbol,i=await F(s.rootDir,n);return i.length===0?{handled:true,text:JSON.stringify({symbol:n,affected:[],note:"No personas reference this symbol."})}:{handled:true,text:JSON.stringify({symbol:n,affected:i},null,2)}}case "paradigm_persona_run":{let n=e.base_url,i=e.dry_run??false,r=e.stop_on_failure??true;if(e.chain_id){let o=await Ja(s.rootDir,e.chain_id,{baseUrl:n,dryRun:i,stopOnFailure:r,permutation:e.permutation});return i||await Ba(o),{handled:true,text:JSON.stringify(o,null,2)}}if(e.persona_id){let o=await x$1(s.rootDir,e.persona_id);if(!o)return {handled:true,text:JSON.stringify({error:`Persona ${e.persona_id} not found`})};let a=Ua(o);if(!a.valid&&!i)return {handled:true,text:JSON.stringify({error:"Template interpolation errors \u2014 fix before running",errors:a.errors,hint:"Use dry_run: true to see interpolated values without executing requests"},null,2)};let c=await Ga(s.rootDir,e.persona_id,{baseUrl:n,dryRun:i,stopOnFailure:r});return i||await Ba(c),{handled:true,text:JSON.stringify(c,null,2)}}return {handled:true,text:JSON.stringify({error:"Either persona_id or chain_id is required"})}}default:return {handled:false,text:""}}}var tu=".paradigm/graphs",qs={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Es=200,Hs=60,st=20,Dn=40,Ka=50,nu=60;function Xa(){return [{name:"paradigm_graph_generate",description:"Generate a named GraphState JSON file for the Paradigm Symbol Graph UI. Writes to .paradigm/graphs/{name}.graph.json. View saved graphs with `paradigm graph` CLI. Returns a summary with node/edge counts and file path. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Graph name (kebab-case). Used as filename: {name}.graph.json. E.g. "auth-flow", "full-project", "checkout-subsystem".'},symbols:{type:"array",items:{type:"string"},description:'Symbol names to include (e.g. ["#auth-middleware", "^authenticated"]). Omit to include all from scan-index.'},groups:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"Group display label"},symbols:{type:"array",items:{type:"string"},description:"Symbol names belonging to this group"}},required:["label","symbols"]},description:"Optional groupings of symbols."},links:{type:"array",items:{type:"object",properties:{source:{type:"string",description:"Source group label"},target:{type:"string",description:"Target group label"},label:{type:"string",description:"Edge label"}},required:["source","target"]},description:"Edges between groups (by label name)."}},required:["name"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Za(t,e,s){if(t!=="paradigm_graph_generate")return {handled:false,text:""};try{let n=e.name||"untitled",i=n.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=ru(s.rootDir,e.symbols,e.groups,e.links,n),o$1=JSON.stringify(r,null,2),a=q.join(s.rootDir,tu);E.existsSync(a)||E.mkdirSync(a,{recursive:!0});let c=q.join(a,`${i}.graph.json`);E.writeFileSync(c,o$1,"utf8");let l=JSON.stringify({file:c,name:n,slug:i,nodes:r.nodes.length,edges:r.edges.length,size:`${(o$1.length/1024).toFixed(1)} KB`,hint:"Graph saved. Run `paradigm graph` to view in browser."},null,2);return o(l.length,t),{handled:!0,text:l}}catch(n){let i=JSON.stringify({error:n.message},null,2);return o(i.length,t),{handled:true,text:i}}}var su={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function iu(t){let e=q.join(t,".paradigm","scan-index.json");if(!E.existsSync(e))return [];let s=JSON.parse(E.readFileSync(e,"utf8")),n=[];for(let[i,r]of Object.entries(su)){let o=s[i];if(!(!o||typeof o!="object"))for(let[a,c]of Object.entries(o)){let l=c;n.push({id:a,name:a,category:r,prefix:qs[r]||"#",description:l.description,path:l.path,tags:l.tags});}}return n}function Qa(t,e){let s=t.replace(/^[#$^!~]/,"");return e.find(n=>n.id===s||n.name===s||n.id===t||n.name===t)}function ru(t,e,s,n,i="Generated Graph"){let r=iu(t),o;e&&e.length>0?o=e.map(p=>Qa(p,r)).filter(Boolean):o=r;let a=[],c=[],l=new Map,d=new Set,u=0;if(s&&s.length>0)for(let p of s){let m=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;l.set(p.label,m);let f=p.symbols.map(k=>Qa(k,o)).filter(Boolean),y=Math.ceil(Math.sqrt(f.length)),b=Math.ceil(f.length/y);for(let k=0;k<f.length;k++){let C=f[k],x=k%y,_=Math.floor(k/y),R=qs[C.category]||"#";a.push({id:`sym-${C.id}`,type:"symbolNode",position:{x:Dn+x*(Es+st),y:Ka+Dn+_*(Hs+st)},parentId:m,data:{type:"symbol",symbol:C,label:`${R}${C.name}`}}),d.add(C.id);}let h=Math.max(y,1),v=Math.max(b,1),w=Dn*2+h*Es+(h-1)*st,S=Ka+Dn*2+v*Hs+(v-1)*st;a.unshift({id:m,type:"groupNode",position:{x:u,y:0},style:{width:w,height:S},data:{type:"group",label:p.label}}),u+=w+nu;}let g=o.filter(p=>!d.has(p.id));if(g.length>0){let p=s&&s.length>0?400:0,m=Math.ceil(Math.sqrt(g.length));for(let f=0;f<g.length;f++){let y=g[f],b=f%m,h=Math.floor(f/m),v=qs[y.category]||"#";a.push({id:`sym-${y.id}`,type:"symbolNode",position:{x:b*(Es+st),y:p+h*(Hs+st)},data:{type:"symbol",symbol:y,label:`${v}${y.name}`}});}}if(n&&n.length>0)for(let p of n){let m=l.get(p.source),f=l.get(p.target);m&&f&&c.push({id:`e-${m}-${f}`,source:m,target:f,type:"default",label:p.label,data:{label:p.label}});}return {version:"1.0",name:i,projectId:q.basename(t),lastModified:new Date().toISOString(),nodes:a,edges:c}}var pe=["specify","plan","task","implement","validate"],$t=".paradigm/pipeline",ec={"add-feature":{gates:{specify:"manual",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Standard feature addition with manual spec/plan review"},"bug-fix":{gates:{specify:"auto",plan:"auto",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Quick bug fix with automated gates except validation"},"security-change":{gates:{specify:"manual",plan:"manual",task:"manual",implement:"manual",validate:"manual"},description:"Security-sensitive change with all-manual gates"},refactor:{gates:{specify:"auto",plan:"manual",task:"auto",implement:"sentinel",validate:"sentinel"},description:"Code refactoring with manual plan review"}};function On(t){return t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function At(t,e){let s=On(e),n=q.join(t,$t,`${s}.yaml`);return E.existsSync(n)?be.load(E.readFileSync(n,"utf8")):null}function It(t,e){let s=On(e.feature),n=q.join(t,$t);E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${s}.yaml`);return E.writeFileSync(i,be.dump(e,{lineWidth:120}),"utf8"),i}function tc(t){let e=q.join(t,$t);return E.existsSync(e)?E.readdirSync(e).filter(s=>s.endsWith(".yaml")&&!s.startsWith("completed")).map(s=>{try{return be.load(E.readFileSync(q.join(e,s),"utf8"))}catch{return null}}).filter(Boolean):[]}function ou(t,e,s){let n={specify:{status:"pending"},plan:{status:"pending"},task:{status:"pending"},implement:{status:"pending"},validate:{status:"pending"}};return n.specify.status="in-progress",{version:"1.0",feature:On(t),created:new Date().toISOString(),current_stage:"specify",gate_config:e,template:s,stages:n}}function au(t){let e=pe.indexOf(t);return e<pe.length-1?pe[e+1]:null}function nc(t,e){let s=On(e.feature),n=q.join(t,$t,"completed");E.existsSync(n)||E.mkdirSync(n,{recursive:true});let i=q.join(n,`${s}.yaml`);E.writeFileSync(i,be.dump(e,{lineWidth:120}),"utf8");let r=q.join(t,$t,`${s}.yaml`);E.existsSync(r)&&E.unlinkSync(r);}function sc(){return [{name:"paradigm_pipeline_start",description:"Create a new spec pipeline for a feature. Uses templates (add-feature, bug-fix, security-change, refactor) or custom gate config. Returns pipeline state. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name or description (will be slugified)"},template:{type:"string",enum:["add-feature","bug-fix","security-change","refactor"],description:"Pipeline template (default: add-feature)"},gates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Custom gate config (overrides template)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_status",description:"Get pipeline status \u2014 current stage, progress, gate config. Pass feature name for specific pipeline, or omit for all active pipelines. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name (omit to list all active pipelines)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_pipeline_advance",description:"Advance pipeline past the current gate. Marks current stage as approved and moves to the next stage. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},approved_by:{type:"string",description:"Who approved this gate (default: agent)"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_configure",description:"Change gate modes on an active pipeline. Use to escalate or relax gates during development. ~150 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},updates:{type:"object",properties:{specify:{type:"string",enum:["auto","manual","sentinel"]},plan:{type:"string",enum:["auto","manual","sentinel"]},task:{type:"string",enum:["auto","manual","sentinel"]},implement:{type:"string",enum:["auto","manual","sentinel"]},validate:{type:"string",enum:["auto","manual","sentinel"]}},description:"Stage-to-gate-mode updates"},reason:{type:"string",description:"Reason for the configuration change"}},required:["feature","updates","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_escalate",description:"Flag a pipeline stage for user input. Use when a gate requires a decision the agent cannot make autonomously. ~200 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"},stage:{type:"string",enum:["specify","plan","task","implement","validate"],description:"Stage to escalate"},question:{type:"string",description:"Question for the user"},options:{type:"array",items:{type:"string"},description:"Available options for the user"},context:{type:"object",description:"Additional context for the decision"}},required:["feature","stage","question","options"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_pipeline_abort",description:"Cancel and archive an active pipeline. Use when a feature is abandoned or no longer needed. ~100 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:"Feature name"}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_pipeline_list",description:"List all active pipelines with current stages and progress. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ic(t,e,s){switch(t){case "paradigm_pipeline_start":{let n=e.feature,i=e.template||"add-feature",r=e.gates,o;if(r)o={specify:r.specify||"manual",plan:r.plan||"manual",task:r.task||"auto",implement:r.implement||"sentinel",validate:r.validate||"sentinel"};else {let l=ec[i];if(!l)return {handled:true,text:JSON.stringify({error:`Unknown template: ${i}`,available:Object.keys(ec)})};o=l.gates;}let a=ou(n,o,i),c=It(s.rootDir,a);return {handled:true,text:JSON.stringify({created:true,feature:a.feature,template:i,file:c,current_stage:a.current_stage,gate_config:a.gate_config,stages:a.stages,hint:`Pipeline '${a.feature}' started at 'specify' stage. Create your spec, then call paradigm_pipeline_advance to move to 'plan'.`},null,2)}}case "paradigm_pipeline_status":{let n=e.feature;if(n){let r=At(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=pe.filter(a=>r.stages[a].status==="approved").length;return {handled:true,text:JSON.stringify({feature:r.feature,created:r.created,template:r.template,current_stage:r.current_stage,progress:`${o}/${pe.length}`,gate_config:r.gate_config,stages:r.stages},null,2)}}let i=tc(s.rootDir);return i.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines. Use paradigm_pipeline_start to create one."})}:{handled:true,text:JSON.stringify({count:i.length,pipelines:i.map(r=>{let o=pe.filter(a=>r.stages[a].status==="approved").length;return {feature:r.feature,current_stage:r.current_stage,progress:`${o}/${pe.length}`,template:r.template,created:r.created}})},null,2)}}case "paradigm_pipeline_advance":{let n=e.feature,i=e.approved_by||"agent",r=At(s.rootDir,n);if(!r)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let o=r.current_stage,a=r.gate_config[o],c=au(o);return r.stages[o].status="approved",r.stages[o].approved_by=i,r.stages[o].approved_at=new Date().toISOString(),a==="auto"&&(r.stages[o].auto_passed_at=new Date().toISOString()),c?(r.current_stage=c,r.stages[c].status="in-progress",It(s.rootDir,r),{handled:true,text:JSON.stringify({advanced:true,from:o,to:c,gate_mode:a,approved_by:i,pipeline:{feature:r.feature,current_stage:r.current_stage,stages:r.stages}},null,2)}):(It(s.rootDir,r),nc(s.rootDir,r),{handled:true,text:JSON.stringify({completed:true,feature:r.feature,message:`Pipeline '${r.feature}' completed and archived.`,stages:r.stages},null,2)})}case "paradigm_pipeline_configure":{let n=e.feature,i=e.updates,r=e.reason,o=At(s.rootDir,n);if(!o)return {handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})};let a=[];for(let[c,l]of Object.entries(i))if(pe.includes(c)&&["auto","manual","sentinel"].includes(l)){let d=o.gate_config[c];o.gate_config[c]=l,a.push({stage:c,from:d,to:l});}return a.length===0?{handled:true,text:JSON.stringify({error:"No valid gate updates provided",valid_stages:pe,valid_modes:["auto","manual","sentinel"]})}:(It(s.rootDir,o),{handled:true,text:JSON.stringify({configured:true,feature:o.feature,changes:a,reason:r,gate_config:o.gate_config},null,2)})}case "paradigm_pipeline_escalate":{let n=e.feature,i=e.stage,r=e.question,o=e.options,a=e.context,c=At(s.rootDir,n);return c?(c.stages[i].status="blocked",c.stages[i].block_reason=r,It(s.rootDir,c),{handled:true,text:JSON.stringify({escalated:true,feature:c.feature,stage:i,question:r,options:o,context:a||{},current_gate:c.gate_config[i],instruction:"This pipeline stage requires user input. Present the question and options to the user, then use paradigm_pipeline_advance or paradigm_pipeline_configure based on their response."},null,2)}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_abort":{let n=e.feature,i=At(s.rootDir,n);return i?(nc(s.rootDir,i),{handled:true,text:JSON.stringify({aborted:true,feature:i.feature,message:`Pipeline '${i.feature}' aborted and archived.`})}):{handled:true,text:JSON.stringify({error:`Pipeline not found: ${n}`})}}case "paradigm_pipeline_list":{let n=tc(s.rootDir);return n.length===0?{handled:true,text:JSON.stringify({count:0,message:"No active pipelines."})}:{handled:true,text:JSON.stringify({count:n.length,pipelines:n.map(i=>{let r=pe.filter(o=>i.stages[o].status==="approved").length;return {feature:i.feature,current_stage:i.current_stage,progress:`${r}/${pe.length}`,template:i.template,created:i.created}})},null,2)}}default:return {handled:false,text:""}}}b$1();var cu=q.join(Fo.homedir(),".conductor"),ot=q.join(cu,"sessions");function oc(){E.existsSync(ot)||E.mkdirSync(ot,{recursive:true});}function Ls(t){oc();let e={...t,registeredAt:new Date().toISOString()},s=q.join(ot,`${t.pid}.json`);return E.writeFileSync(s,JSON.stringify(e,null,2),"utf-8"),e}function An(t){let e=q.join(ot,`${t}.json`);return E.existsSync(e)?(E.unlinkSync(e),true):false}function Gs(){oc();let t=E.readdirSync(ot).filter(s=>s.endsWith(".json")),e=[];for(let s of t)try{let n=E.readFileSync(q.join(ot,s),"utf-8"),i=JSON.parse(n);e.push(i);}catch{}return e}function ac(){let t=Gs(),e=0;for(let s of t)lu(s.pid)||(An(s.pid),e++);return e}function lu(t){try{return process.kill(t,0),!0}catch{return false}}function Ws(){try{return execSync(`osascript -e '
414
414
  tell application "System Events"
415
415
  set frontApp to first application process whose frontmost is true
416
416
  return bundle identifier of frontApp
@@ -421,7 +421,7 @@ This session is no longer visible in the Conductor overlay.`,handled:true}:{text
421
421
  Use paradigm_conductor_register or /conduct to register.`,handled:true};let i=[`${n.length} session(s) registered with Conductor:
422
422
  `];for(let r of n){let o=[` PID ${r.pid}`];r.label&&o.push(`"${r.label}"`),o.push(`\u2014 ${r.projectDir}`),r.branch&&o.push(`(${r.branch})`),i.push(o.join(" "));}return e.clean&&i.push(`
423
423
  (Stale sessions cleaned)`),{text:i.join(`
424
- `),handled:true}}default:return {text:"",handled:false}}}function pc(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function uc(t,e,s){let n=n$3(s.rootDir);switch(n||(n=j$4(s.rootDir)),t){case "paradigm_symphony_peek":{let i=e.status;o$3(n.id,i);let{hasNew:r}=s$2(n.id),o=r?N("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let i=e.status;o$3(n.id,i);let r=v$2(n.id);if(r.length>0){let c=r[r.length-1].id;z$2(n.id,c),t$2(n.id);}B$1(n.id);let o=N("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:pu(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,u=e.decision,g=false;if(!a&&!o){let y=r.length>60?r.slice(0,60)+"...":r;a=C$1(y,Ft(n)).id,g=true;}let p;if(c&&c.length>0){let y=l$2();p=c.map(b=>{let h=y.find(v=>v.id===b);return h?Ft(h):{id:b,name:b,type:"agent"}});}let m=I({sender:Ft(n),recipients:p,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:u}),f=J$1(m);if(yu(m).catch(()=>{}),g&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${Us}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:g,deliveredTo:f,intent:i})}}case "paradigm_symphony_status":{m$2();let i=l$2(),r=E$2("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-LWBUQ3T4.js');c=l().filter(u=>!u.revoked).map(u=>({id:u.id,address:u.address,agents:u.agents?.length??0,lastSeen:u.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:n.id,project:n.project,role:n.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=D$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=H(i).slice(0,r),c=[],l=new Set,d=new Set;for(let u of a){u.content.decision&&c.push(u.content.decision),u.intent==="decision"&&u.content.text&&c.push(u.content.text);for(let g of u.symbols)l.add(g);if(u.attachments)for(let g of u.attachments)g.type==="file"&&d.add(g.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(u=>({id:u.id,sender:u.sender.name,intent:u.intent,text:u.content.text,timestamp:u.timestamp,symbols:u.symbols,hasDiff:!!u.content.diff,hasDecision:!!u.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=K();if(Q$1(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L({filePath:i,requester:Ft(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:Ft(n),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
424
+ `),handled:true}}default:return {text:"",handled:false}}}function pc(){return [{name:"paradigm_symphony_peek",description:"Ultra-cheap inbox check \u2014 file stat only, no parsing. Returns { hasNew: true/false }. Use with /loop 10s for near-free monitoring. When hasNew is true, call paradigm_symphony_poll to read messages. ~15 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:"Short status blurb (same as poll). Updates heartbeat."}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_poll",description:"Read inbox notes and process them. Call when paradigm_symphony_peek returns hasNew: true, or directly via /loop for continuous messaging. Returns unread notes formatted as markdown with thread context and suggested actions. Updates heartbeat and optional status blurb. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",description:'Short status blurb describing what you are currently working on (e.g., "Implementing auth middleware \u2014 3 files modified"). Visible to humans and other agents in the Network view.'}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_send",description:"Send a note to other agents or broadcast. Auto-creates thread if no threadRoot provided. Supports intents: question, context, proposal, decision, action, etc. ~100 tokens.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:["question","context","clarification","proposal","verification","action","decision","alert","approval","rejection","reference","handoff","task","task-ack","progress","approval-request","approval-response","task-complete","task-failed"],description:"Message intent (what kind of message this is). Task protocol intents: task (assignment), task-ack, progress, approval-request, approval-response, task-complete, task-failed."},text:{type:"string",description:"Message text content"},parentId:{type:"string",description:"ID of message being replied to"},threadRoot:{type:"string",description:"Thread ID to post in (auto-created if omitted)"},recipients:{type:"array",items:{type:"string"},description:"Agent IDs to send to (omit for broadcast)"},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols referenced (e.g., ["#auth-service", "$login-flow"])'},diff:{type:"string",description:"Code diff to include with the message"},decision:{type:"string",description:"Decision text to record (for intent=decision)"}},required:["intent","text"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_status",description:"Show Symphony network status: linked agents (with awake/asleep detection), active threads, unread count, pending file requests. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_thread",description:"Get full thread context: all notes in order, participants, extracted decisions, and referenced symbols. ~200 tokens.",inputSchema:{type:"object",properties:{threadId:{type:"string",description:"Thread ID (thr-XXXXXXXX format)"},depth:{type:"number",description:"Maximum messages to return (default: 50)"}},required:["threadId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_symphony_request_file",description:"Request a file from another agent's project. Human approval required (unless auto-approved in trust config). Files matching hard-deny patterns (.env, *.key, etc.) are always blocked. ~100 tokens.",inputSchema:{type:"object",properties:{filePath:{type:"string",description:'Relative file path to request (e.g., "src/auth/middleware.ts")'},from:{type:"string",description:'Agent ID to request file from (e.g., "backend/core")'},reason:{type:"string",description:"Why this file is needed"},snippet:{type:"string",description:'Specific function or line range needed (e.g., "validateToken function" or "lines 50-100")'}},required:["filePath","from","reason"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_symphony_approve_file",description:'Approve or deny a pending file request. Use action "approve" to send file, "deny" to reject, or "approve-redacted" to send with secrets stripped. ~100 tokens.',inputSchema:{type:"object",properties:{requestId:{type:"string",description:"File request ID (freq-XXXXXXXX format)"},action:{type:"string",enum:["approve","deny","approve-redacted"],description:"Approve, deny, or approve with redaction"},reason:{type:"string",description:"Reason for denial (required for deny action)"}},required:["requestId","action"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function uc(t,e,s){let n=n$3(s.rootDir);switch(n||(n=j$4(s.rootDir)),t){case "paradigm_symphony_peek":{let i=e.status;o$3(n.id,i);let{hasNew:r}=s$2(n.id),o=r?N("pending").length:0;return {handled:true,text:JSON.stringify(r?{hasNew:true,pendingFileRequests:o,action:"call paradigm_symphony_poll to read"}:{hasNew:false})}}case "paradigm_symphony_poll":{m$2(),S();let i=e.status;o$3(n.id,i);let r=v$2(n.id);if(r.length>0){let c=r[r.length-1].id;z$2(n.id,c),t$2(n.id);}B$1(n.id);let o=N("pending");return r.length===0&&o.length===0?{handled:true,text:JSON.stringify({messages:0,note:"No new notes. Score is quiet.",identity:n.id})}:{handled:true,text:pu(r,o)}}case "paradigm_symphony_send":{let i=e.intent,r=e.text,o=e.parentId,a=e.threadRoot,c=e.recipients,l=e.symbols,d=e.diff,u=e.decision,g=false;if(!a&&!o){let y=r.length>60?r.slice(0,60)+"...":r;a=C$1(y,Ft(n)).id,g=true;}let p;if(c&&c.length>0){let y=l$2();p=c.map(b=>{let h=y.find(v=>v.id===b);return h?Ft(h):{id:b,name:b,type:"agent"}});}let m=I({sender:Ft(n),recipients:p,intent:i,text:r,parentId:o,threadRoot:a,symbols:l,diff:d,decision:u}),f=J$1(m);if(yu(m).catch(()=>{}),g&&a){({timestamp:m.timestamp,sender:m.sender,content:{text:`Thread created: ${m.content.text.slice(0,60)}`}});fetch(`${Us}/api/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaId:"paradigm-symphony",eventType:"thread:created",category:"lifecycle",timestamp:m.timestamp,scopeValue:a,service:m.sender.project||"symphony",severity:"info",data:{topic:m.content.text.slice(0,60),initiator:m.sender.name,threadId:a}})}).catch(()=>{});}return {handled:true,text:JSON.stringify({sent:true,messageId:m.id,threadId:a,threadCreated:g,deliveredTo:f,intent:i})}}case "paradigm_symphony_status":{m$2();let i=l$2(),r=E$2("active"),o=v$2(n.id),a=N("pending"),c=[];try{let{loadPeers:l}=await import('./symphony-peers-U4KHMKGI.js');c=l().filter(u=>!u.revoked).map(u=>({id:u.id,address:u.address,agents:u.agents?.length??0,lastSeen:u.lastSeen}));}catch{}return {handled:true,text:JSON.stringify({identity:{id:n.id,project:n.project,role:n.role},agents:i.map(l=>({id:l.id,name:l.name,project:l.project,role:l.role,status:q$3(l)?"asleep":"awake",lastPoll:l.lastPoll,statusBlurb:l.statusBlurb})),peers:c,activeThreads:r.map(l=>({id:l.id,topic:l.topic,participants:l.participants.length,messageCount:l.messageCount,lastActivity:l.lastActivity})),unreadCount:o.length,pendingFileRequests:a.length},null,2)}}case "paradigm_symphony_thread":{let i=e.threadId,r=e.depth||50,o=D$1(i);if(!o)return {handled:true,text:JSON.stringify({error:`Thread not found: ${i}`})};let a=H(i).slice(0,r),c=[],l=new Set,d=new Set;for(let u of a){u.content.decision&&c.push(u.content.decision),u.intent==="decision"&&u.content.text&&c.push(u.content.text);for(let g of u.symbols)l.add(g);if(u.attachments)for(let g of u.attachments)g.type==="file"&&d.add(g.name);}return {handled:true,text:JSON.stringify({thread:{id:o.id,topic:o.topic,status:o.status,createdAt:o.createdAt,decision:o.decision},participants:o.participants,messages:a.map(u=>({id:u.id,sender:u.sender.name,intent:u.intent,text:u.content.text,timestamp:u.timestamp,symbols:u.symbols,hasDiff:!!u.content.diff,hasDecision:!!u.content.decision})),decisions:c,symbolsDiscussed:[...l],filesReferenced:[...d]},null,2)}}case "paradigm_symphony_request_file":{let i=e.filePath,r=e.from,o=e.reason,a=e.snippet,c=K();if(Q$1(i,c))return {handled:true,text:JSON.stringify({error:`File path "${i}" is on the hard-deny list and cannot be requested.`,deniedPatterns:c.defaults.neverApprove})};let l=L({filePath:i,requester:Ft(n),reason:o,snippet:a,threadRoot:void 0}),d=I({sender:Ft(n),recipients:[{id:r,name:r,type:"agent"}],intent:"fileRequest",text:`Requesting file: ${i}
425
425
  Reason: ${o}${a?`
426
426
  Snippet: ${a}`:""}`,symbols:[]});return J$1(d),{handled:true,text:JSON.stringify({requestId:l.request.requestId,status:"pending",filePath:i,from:r,message:`File request created. The owning agent's human must approve via "paradigm symphony approve ${l.request.requestId}" or "paradigm_symphony_approve_file".`})}}case "paradigm_symphony_approve_file":{let i=e.requestId,r=e.action,o=e.reason;if(r==="deny"){let l=P(i,o);return {handled:true,text:JSON.stringify({success:l,requestId:i,action:"denied",reason:o||"No reason provided"})}}let a=r==="approve-redacted",c=O(i,s.rootDir,a);return c.success?{handled:true,text:JSON.stringify({success:true,requestId:i,action:a?"approved-redacted":"approved",filePath:c.delivery?.filePath,size:c.delivery?.size,hash:c.delivery?.hash})}:{handled:true,text:JSON.stringify({success:false,requestId:i,error:c.error})}}default:return {handled:false,text:""}}}function Ft(t){return {id:t.id,name:t.name,type:t.type||"agent",project:t.project,role:t.role}}function pu(t,e){let s=[],n=new Map;for(let i of t){let r=i.threadRoot||"direct";n.has(r)||n.set(r,[]),n.get(r).push(i);}for(let[i,r]of n){let o=i;if(i!=="direct"){let a=D$1(i);a&&(o=a.topic);}s.push(`## Symphony: ${r.length} new note${r.length!==1?"s":""} in "${o}"
427
427
  `);for(let a=0;a<r.length;a++){let c=r[a],l=new Date(c.timestamp).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),d=`${c.sender.name}${c.sender.project?` (${c.sender.project})`:""}`;s.push(`### ${a+1}. ${d} \u2014 ${gu(c.intent)} (${l})`),s.push(`> ${c.content.text.split(`
@@ -438,18 +438,18 @@ ${c.content.diff}
438
438
  ### Connected Agents (${a.length})`);for(let c of a)o.push(`- \`${c.agentId}\` (since ${c.connectedAt})`);}if(e.detail==="full"){let c=i.highlights,l=i.annotations;c?.length&&o.push(`
439
439
  ### Active Highlights: ${c.length}`),l?.length&&o.push(`
440
440
  ### Active Annotations: ${l.length}`);}return {handled:true,text:o.join(`
441
- `)}}case "paradigm_platform_clear":{let n=await dt(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z();function vc(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function kc(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$3(s.rootDir),i=b$8(s.rootDir);if(n.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let r=i?n.filter(l=>i.includes(l.id)):n,o=i?n.length-r.length:0,a=i$4(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:n.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((u,g)=>g.confidence-u.confidence).slice(0,5).map(u=>({symbol:u.symbol,confidence:parseFloat(u.confidence.toFixed(2)),sessions:u.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,i=e.response_format,r=l$3(s.rootDir,n);return i==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,i=h$3(s.rootDir,n);if(!i){let o=i$3(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let r=y$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let n=e.id,i=h$3(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o?o=o.filter(a=>a!==r):o=e$5().filter(a=>a!==r),d$8(s.rootDir,o),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${i.nickname||r} (${r}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,i=h$3(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o&&(o.includes(r)||(o.push(r),d$8(s.rootDir,o))),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${i.nickname||r} (${r}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}g();function Sc(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function _c(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$9(n,i,s.rootDir):c=a$8(n,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,u=e.lineageType,g={context:i,snippet:r,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...d?{parentId:d}:{},...u?{lineageType:u}:{}},p=c$3(n,g,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:p.entry.id,agentId:n,scope:l,filePath:p.filePath,concepts:p.entry.concepts,...d?{parentId:d}:{},...u?{lineageType:u}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await d$9(n,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:i,scope:r,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var vu=".paradigm/scan-index.json",ku=".paradigm/flow-index.json",Su=".paradigm/config.yaml",_u="portal.yaml",xu=".paradigm/university/index.yaml",te={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function ut(t){let e=q.join(t,Su);if(!E.existsSync(e))return {...te};try{let s=E.readFileSync(e,"utf8"),n=be.load(s);if(!n||!n.docs)return {...te};let i=n.docs;return {enabled:i.enabled??te.enabled,title:i.title??te.title,theme:i.theme??te.theme,customCss:i.customCss??te.customCss,customContent:i.customContent??te.customContent,exclude:{tags:i.exclude?.tags??te.exclude.tags,patterns:i.exclude?.patterns??te.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??te.sidebar.collapsed},output:i.output??te.output}}catch{return {...te}}}function In(t){let e=q.join(t,vu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Vs(t){let e=q.join(t,ku);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function $n(t){let e=q.join(t,_u);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch{return null}}function Cc(t){let e=q.join(t,xu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch{return null}}function Rc(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:be.load(e[1]),body:e[2].trim()}}catch{return null}}function Pc(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[i,r]of Object.entries(n))e.set(i,r);return e}function Cu(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function pt(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function jc(t,e){let s=q.join(t,e);if(!E.existsSync(s))return [];let n=[];try{let i=E.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=E.readFileSync(q.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=Rc(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),n}function Tc(t,e,s){let n=s||ut(t),i=q.join(t,n.customContent),r=q.join(i,`${e}.md`);if(!E.existsSync(r))return null;try{let o=E.readFileSync(r,"utf8"),a=Rc(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function Dc(t,e){let s=e||ut(t),n=In(t),i=Vs(t),r=$n(t),o=jc(t,s.customContent),a=Cc(t),c=n?.$meta?.project||q.basename(t),l=s.title||`${c} Docs`,d=[],u={},g=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(p=>({id:p.slug,label:p.title,kind:"custom",description:p.description}))}),a&&a.entries.length>0){let p=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);p.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:p.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let p=Object.values(n.components||{}).filter(k=>!pt(k,s));if(p.length>0){let k=new Map;for(let _ of p){let R=_.componentType||"other";k.has(R)||k.set(R,[]),k.get(R).push(_);}let x=[...k.entries()].sort((_,R)=>R[1].length-_[1].length).map(([_,R])=>({id:`components-${_}`,label:`${_.charAt(0).toUpperCase()+_.slice(1)} (${R.length})`,collapsed:s.sidebar.collapsed.includes(`components-${_}`),items:R.sort((I,P)=>I.name.localeCompare(P.name)).map(I=>({id:I.id,label:I.name,kind:"component",description:I.description,badge:I.componentType}))}));d.push({id:"components",label:`Components (${p.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:x}),u.components=p.length,g+=p.length;}let m=Object.values(n.features||{}).filter(k=>!pt(k,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"component",description:k.description}))}),u.features=m.length,g+=m.length);let f=Object.values(n.flows||{}).filter(k=>!pt(k,s)),y=new Set(f.map(k=>k.id)),b=[];if(i)for(let[k,C]of Object.entries(i.flows)){let x=k.replace(/^\$/,"");y.has(x)||b.push({id:x,label:C.name||x,kind:"flow",description:C.description});}let h=[...f.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"flow",description:k.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),u.flows=h.length,g+=h.length);let v=Object.values(n.gates||{}).filter(k=>!pt(k,s));v.length>0&&(d.push({id:"gates",label:`Gates (${v.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:v.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"gate",description:k.description}))}),u.gates=v.length,g+=v.length);let w=Object.values(n.signals||{}).filter(k=>!pt(k,s));w.length>0&&(d.push({id:"signals",label:`Signals (${w.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:w.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"signal",description:k.description}))}),u.signals=w.length,g+=w.length);let S=Object.values(n.aspects||{}).filter(k=>!pt(k,s));S.length>0&&(d.push({id:"aspects",label:`Aspects (${S.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:S.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"aspect",description:k.description}))}),u.aspects=S.length,g+=S.length);}if(r){let p=Object.keys(r.routes||{}).length,m=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${p} routes`,badge:`${p} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:g,symbolCounts:u}}function Oc(t,e){let s=In(t);if(!s)return null;let n=Pc(s),i=n.get(e);if(!i)return null;let r=[];for(let[y,b]of n)y!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=Vs(t);if(c)for(let[y,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(v=>v.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:y.replace(/^\$/,""),name:b.name||y});}if(s.flows)for(let[y,b]of Object.entries(s.flows)){if(a.some(v=>v.id===y))continue;let h=(b.steps||[]).map(v=>v.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:y,name:b.name});}let l=[],d=$n(t);if(d&&i.category==="gates"){let y=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);y&&l.push({id:y.replace(/^\^/,""),description:d.gates[y].description});}else if(d){let y=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let v of h){let w=v.replace(/^\^/,"");if(y.has(v)||y.has(`^${w}`)){let S=d.gates[v]||d.gates[`^${w}`]||d.gates[w];S&&!l.some(k=>k.id===w)&&l.push({id:w,description:S.description});}}}let u=[];if(s.aspects)for(let[y,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&u.push(b.symbol);for(let y of i.related||[])y.startsWith("~")&&!u.includes(y)&&u.push(y);let g=[],p=Cc(t);if(p)for(let y of p.entries)y.symbols.includes(i.symbol)&&g.push({id:y.id,title:y.title});let m=i.parent||void 0,f=[];if(s.components)for(let y of Object.values(s.components))y.parent===i.symbol&&f.push(y.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:u,guides:g,parent:m,children:f}}function Ac(t,e){let s=Vs(t),n=In(t);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(n?.flows){let i=e.replace(/^\$/,""),r=n.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function Ic(t){let e=$n(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let n=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let u=d.replace(/^\^/,""),g=e.gates[d]||e.gates[`^${u}`]||e.gates[u];return {symbol:`^${u}`,description:g?.description}})}});return {version:e.version||"1.0",gates:n,routes:i}}function $c(t,e,s){let n=s||20,i=[],r=e.toLowerCase(),o=In(t);if(o){let d=Pc(o);for(let[u,g]of d){let p=Ys(g.name,g.description||"",g.visualTags||[],r);p>0&&i.push({id:g.id,kind:Cu(g.category),label:g.name,description:g.description||"",matchContext:xc(g.name,g.description||"",r),score:p});}}let a=ut(t),c=jc(t,a.customContent);for(let d of c){let u=d.body.substring(0,200),g=Ys(d.title,u,[],r);g>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||u.substring(0,100),matchContext:xc(d.title,d.body,r),score:g});}let l=$n(t);if(l)for(let[d,u]of Object.entries(l.gates||{})){let g=d.replace(/^\^/,""),p=Ys(g,u.description,[],r);p>0&&i.push({id:g,kind:"portal",label:`^${g}`,description:u.description,score:p});}return i.sort((d,u)=>u.score-d.score||d.label.localeCompare(u.label)),i.slice(0,n)}function Ys(t,e,s,n){let i=t.toLowerCase(),r=e.toLowerCase();return i===n?1:i.startsWith(n)?.8:i.includes(n)?.6:r.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function xc(t,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return t.toLowerCase().includes(s)?t:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Fc(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Nc(t,e,s){if(t==="paradigm_docs_manifest"){let n=ut(s.rootDir),i=Dc(s.rootDir,n),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(t==="paradigm_docs_page"){if(e.portal){let i=Ic(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(e.flow){let i=e.flow,r=Ac(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.slug){let i=ut(s.rootDir),r=Tc(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.symbol){let i=Oc(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,t),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=$c(s.rootDir,n,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,t),{handled:true,text:r}}return {handled:false,text:""}}g$1();e();function Ec(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Hc(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_work_log_record":{let i=c$1(s.rootDir),{filtered:r}=d$4(e.summary,i,"work_log"),o=a$5(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$6(s.rootDir,7);return {text:n(r),handled:true}}let i=b$6(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$1(s.rootDir),{filtered:r}=d$4(e.insight,i,"learning_journal"),o=a$4(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$3(e.agent);return {text:n(r),handled:true}}let i=e.agent?b$5(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$5({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$1(s.rootDir),{filtered:r}=d$4(e.decision,i,"team_decisions"),{filtered:o}=d$4(e.rationale,i,"team_decisions"),a=a$3(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags});return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=g$5(s.rootDir);return {text:n(r),handled:true}}let i=d$3(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}v();b$2();z();g$1();n();function qc(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ru(t){let e=Date.now(),s=t.match(/^(\d+)(m|h|d)$/);if(s){let n=parseInt(s[1],10),i=s[2],r=i==="m"?n*6e4:i==="h"?n*36e5:n*864e5;return new Date(e-r).toISOString()}return t}async function Mc(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$1(s.rootDir);a=u$1(a,c).slice(0,o);let l=q.join(s.rootDir,".paradigm/events/nominations.jsonl");if(E.existsSync(l))try{let u=E.readFileSync(l,"utf8"),g=new Set(a.map(m=>m.id)),p=u.trim().split(`
441
+ `)}}case "paradigm_platform_clear":{let n=await dt(s.projectDir,"clear",{target:e.target});return n.ok?{handled:true,text:`Cleared ${n.data.target} agent effects`}:{handled:true,text:`**Clear failed:** ${n.error}`}}default:return {handled:false,text:""}}}z();function vc(){return [{name:"paradigm_agent_list",description:"List all agent identity profiles with top expertise areas. Shows agents from both global (~/.paradigm/agents/) and project (.paradigm/agents/) scopes. Returns profile summaries with personality and top symbols. ~150 tokens.",inputSchema:{type:"object",properties:{scope:{type:"string",enum:["all","global","project"],description:"Filter by scope (default: all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_expertise",description:"Find which agents are best qualified to work on a specific symbol. Returns agents ranked by confidence score from their expertise history. Use for symbol-to-agent routing. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to query (e.g., "#auth-middleware", "$checkout-flow")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns only top agent (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_get",description:"Get full agent profile including personality, expertise table, transferable patterns, and per-project contexts. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID or nickname (e.g., "architect", "Apex", "Jinx")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_agent_bench",description:"Bench an agent \u2014 Maestro will skip this agent during orchestration and nomination scoring. Use when an agent is noisy or unhelpful. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to bench (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_agent_activate",description:"Activate a benched agent \u2014 restore it to active Maestro orchestration. ~50 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Agent ID to activate (e.g., "architect")'}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function kc(t,e,s){switch(t){case "paradigm_agent_list":{let n=i$3(s.rootDir),i=b$8(s.rootDir);if(n.length===0)return {handled:true,text:JSON.stringify({count:0,agents:[],note:"No .agent profiles found. Create one with `paradigm agent create <id> --global` or via paradigm_agent_create."},null,2)};let r=i?n.filter(l=>i.includes(l.id)):n,o=i?n.length-r.length:0,a=i$4(s.rootDir),c=new Map(a.map(l=>[l.id,l]));return {handled:true,text:JSON.stringify({count:r.length,totalAvailable:n.length,...i?{rosterActive:true,inactiveCount:o}:{rosterActive:false},agents:r.map(l=>{let d=c.get(l.id);return {id:l.id,role:l.role,nickname:l.nickname,personality:l.personality,...d?{lastSession:d.lastSession?.summary?.slice(0,100),lastSessionAge:d.lastSession?.date,pendingWork:d.pendingWork?.length||0,sessionsOnProject:d.sessionsOnProject||0}:{},topExpertise:(l.expertise||[]).sort((u,g)=>g.confidence-u.confidence).slice(0,5).map(u=>({symbol:u.symbol,confidence:parseFloat(u.confidence.toFixed(2)),sessions:u.sessions})),projectContexts:Object.keys(l.contexts||{}),transferableCount:(l.transferable||[]).length,...l.attention?.threshold!=null?{threshold:l.attention.threshold}:{}}})},null,2)}}case "paradigm_agent_expertise":{let n=e.symbol,i=e.response_format,r=l$3(s.rootDir,n);return i==="concise"?{handled:true,text:JSON.stringify({symbol:n,topAgent:r.length>0?{id:r[0].agentId,confidence:parseFloat(r[0].entry.confidence.toFixed(2))}:null},null,2)}:{handled:true,text:JSON.stringify({symbol:n,agents:r.map(o=>({agentId:o.agentId,confidence:parseFloat(o.entry.confidence.toFixed(2)),sessions:o.entry.sessions,lastTouch:o.entry.lastTouch})),count:r.length,...r.length===0?{note:`No agents have recorded expertise on ${n}. Run \`paradigm agent sync\` to bootstrap from lore history.`}:{}},null,2)}}case "paradigm_agent_get":{let n=e.id,i=h$3(s.rootDir,n);if(!i){let o=i$3(s.rootDir),a=n.toLowerCase(),c=o.filter(l=>l.nickname?.toLowerCase().includes(a)||l.id.includes(a));return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found by ID or nickname`,...c.length>0?{didYouMean:c.map(l=>({id:l.id,nickname:l.nickname}))}:{suggestion:`Create with \`paradigm agent create ${n} --global\``}},null,2)}}let r=y$2(i);return {handled:true,text:JSON.stringify({id:i.id,role:i.role,description:i.description,version:i.version,personality:i.personality,expertise:(i.expertise||[]).sort((o,a)=>a.confidence-o.confidence).map(o=>({symbol:o.symbol,confidence:parseFloat(o.confidence.toFixed(2)),sessions:o.sessions,lastTouch:o.lastTouch})),transferable:(i.transferable||[]).map(o=>({id:o.id,description:o.description,learnedIn:o.learnedIn,appliedIn:o.appliedIn,successRate:o.successRate})),contexts:i.contexts,created:i.created,updated:i.updated,...i.permissions?{permissions:i.permissions}:{},integrity:r},null,2)}}case "paradigm_agent_bench":{let n=e.id,i=h$3(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o?o=o.filter(a=>a!==r):o=e$5().filter(a=>a!==r),d$7(s.rootDir,o),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},removedFromRoster:true,rosterCount:o.length,note:`${i.nickname||r} (${r}) removed from this project's roster. Still available globally.`},null,2)}}case "paradigm_agent_activate":{let n=e.id,i=h$3(s.rootDir,n);if(!i)return {handled:true,text:JSON.stringify({error:`Agent "${n}" not found`},null,2)};let r=i.id,o=b$8(s.rootDir);return o&&(o.includes(r)||(o.push(r),d$7(s.rootDir,o))),{handled:true,text:JSON.stringify({id:r,...i.nickname?{nickname:i.nickname}:{},addedToRoster:true,rosterCount:o?.length??"all (no roster)",note:`${i.nickname||r} (${r}) is active on this project's roster.`},null,2)}}default:return {handled:false,text:""}}}g();function Sc(){return [{name:"paradigm_notebook_search",description:"Search agent notebook entries by concept, tag, or keyword. Notebooks are curated snippet libraries distilled from lore for reuse in orchestration. ~150 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:'Agent ID to search notebooks for (e.g., "architect", "builder")'},query:{type:"string",description:"Search query \u2014 matches concepts, tags, context, and snippet content"},concepts:{type:"array",items:{type:"string"},description:'Filter by concept tags (e.g., ["auth", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Filter by classification tags"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level (default: "detailed")'}},required:["agentId"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_notebook_add",description:"Add a new entry to an agent's notebook. Use for curated, reusable snippets that should be available across sessions. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add notebook entry for"},context:{type:"string",description:"When to apply this snippet \u2014 the retrieval context"},snippet:{type:"string",description:"The reusable code/knowledge snippet"},concepts:{type:"array",items:{type:"string"},description:'Concept tags for retrieval (e.g., ["auth", "jwt", "middleware"])'},tags:{type:"array",items:{type:"string"},description:"Classification tags"},confidence:{type:"number",description:"Confidence score 0.0-1.0 (default: 0.7)"},scope:{type:"string",enum:["global","project"],description:'Where to store: global travels across projects (default: "global")'},parentId:{type:"string",description:"Optional: ID of the parent notebook entry this was derived from (soft provenance, no validation)"},lineageType:{type:"string",enum:["fix","derive","capture","promote"],description:"Optional: relationship to parent \u2014 fix (corrects parent), derive (modified from parent), capture (new observation), promote (promoted from lower confidence)"}},required:["agentId","context","snippet","concepts"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_notebook_promote",description:"Extract a lore entry into a notebook entry. Distills the lore into a reusable snippet with provenance linking. ~100 tokens.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Agent ID to add the promoted entry to"},loreEntryId:{type:"string",description:'Lore entry ID to promote (e.g., "L-2026-03-15-...")'},scope:{type:"string",enum:["global","project"],description:'Where to store (default: "global")'}},required:["agentId","loreEntryId"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function _c(t,e,s){switch(t){case "paradigm_notebook_search":{let n=e.agentId,i=e.query,r=e.concepts,o=e.tags,a=e.response_format,c;return i?c=b$9(n,i,s.rootDir):c=a$8(n,s.rootDir,{concepts:r,tags:o}),a==="concise"?{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,concepts:l.concepts}))},null,2)}:{handled:true,text:JSON.stringify({agentId:n,count:c.length,entries:c.map(l=>({id:l.id,context:l.context,snippet:l.snippet.length>500?l.snippet.slice(0,500)+"...":l.snippet,concepts:l.concepts,tags:l.tags,appliedCount:l.appliedCount,confidence:l.confidence,provenance:l.provenance}))},null,2)}}case "paradigm_notebook_add":{let n=e.agentId,i=e.context,r=e.snippet,o=e.concepts||[],a=e.tags||[],c=e.confidence??.7,l=e.scope||(s.rootDir?"project":"global"),d=e.parentId,u=e.lineageType,g={context:i,snippet:r,provenance:{source:"manual",createdBy:n},confidence:c,concepts:o,tags:a,...d?{parentId:d}:{},...u?{lineageType:u}:{}},p=c$4(n,g,l,s.rootDir);return {handled:true,text:JSON.stringify({action:"notebook_add",id:p.entry.id,agentId:n,scope:l,filePath:p.filePath,concepts:p.entry.concepts,...d?{parentId:d}:{},...u?{lineageType:u}:{}},null,2)}}case "paradigm_notebook_promote":{let n=e.agentId,i=e.loreEntryId,r=e.scope||(s.rootDir?"project":"global"),o=await d$8(n,i,s.rootDir,r);return o?{handled:true,text:JSON.stringify({action:"notebook_promote",id:o.entry.id,agentId:n,loreEntryId:i,scope:r,filePath:o.filePath,concepts:o.entry.concepts,confidence:o.entry.confidence},null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry "${i}" not found`,suggestion:"Check the lore entry ID with paradigm_lore_search"},null,2)}}default:return {handled:false,text:""}}}var vu=".paradigm/scan-index.json",ku=".paradigm/flow-index.json",Su=".paradigm/config.yaml",_u="portal.yaml",xu=".paradigm/university/index.yaml",te={enabled:true,title:null,theme:"dark",customCss:null,customContent:"docs/",exclude:{tags:[],patterns:[]},sidebar:{collapsed:[]},output:".paradigm/docs-site"};function ut(t){let e=q.join(t,Su);if(!E.existsSync(e))return {...te};try{let s=E.readFileSync(e,"utf8"),n=be.load(s);if(!n||!n.docs)return {...te};let i=n.docs;return {enabled:i.enabled??te.enabled,title:i.title??te.title,theme:i.theme??te.theme,customCss:i.customCss??te.customCss,customContent:i.customContent??te.customContent,exclude:{tags:i.exclude?.tags??te.exclude.tags,patterns:i.exclude?.patterns??te.exclude.patterns},sidebar:{collapsed:i.sidebar?.collapsed??te.sidebar.collapsed},output:i.output??te.output}}catch{return {...te}}}function In(t){let e=q.join(t,vu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function Vs(t){let e=q.join(t,ku);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return JSON.parse(s)}catch{return null}}function $n(t){let e=q.join(t,_u);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch{return null}}function Cc(t){let e=q.join(t,xu);if(!E.existsSync(e))return null;try{let s=E.readFileSync(e,"utf8");return be.load(s)}catch{return null}}function Rc(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:be.load(e[1]),body:e[2].trim()}}catch{return null}}function Pc(t){let e=new Map,s=[t.components,t.features,t.flows,t.state,t.gates,t.signals,t.aspects];for(let n of s)if(n)for(let[i,r]of Object.entries(n))e.set(i,r);return e}function Cu(t){return {components:"component",features:"component",flows:"flow",state:"component",gates:"gate",signals:"signal",aspects:"aspect"}[t]||"component"}function pt(t,e){if(e.exclude.tags.length>0&&t.visualTags){for(let s of t.visualTags)if(e.exclude.tags.includes(s))return true}if(e.exclude.patterns.length>0&&t.path){for(let s of e.exclude.patterns)if(s.endsWith("*")){let n=s.slice(0,-1);if(t.path.includes(n))return true}else if(t.path.includes(s))return true}return false}function jc(t,e){let s=q.join(t,e);if(!E.existsSync(s))return [];let n=[];try{let i=E.readdirSync(s).filter(r=>r.endsWith(".md"));for(let r of i)try{let o=E.readFileSync(q.join(s,r),"utf8"),a=r.replace(/\.md$/,""),c=Rc(o);c?n.push({slug:a,title:c.frontmatter.title||a,body:c.body,order:typeof c.frontmatter.order=="number"?c.frontmatter.order:void 0,description:c.frontmatter.description||void 0}):n.push({slug:a,title:a,body:o.trim()});}catch{}}catch{}return n.sort((i,r)=>i.order!=null&&r.order!=null?i.order-r.order:i.order!=null?-1:r.order!=null?1:i.title.localeCompare(r.title)),n}function Tc(t,e,s){let n=s||ut(t),i=q.join(t,n.customContent),r=q.join(i,`${e}.md`);if(!E.existsSync(r))return null;try{let o=E.readFileSync(r,"utf8"),a=Rc(o);return a?{slug:e,title:a.frontmatter.title||e,body:a.body,order:typeof a.frontmatter.order=="number"?a.frontmatter.order:void 0,description:a.frontmatter.description||void 0}:{slug:e,title:e,body:o.trim()}}catch{return null}}function Dc(t,e){let s=e||ut(t),n=In(t),i=Vs(t),r=$n(t),o=jc(t,s.customContent),a=Cc(t),c=n?.$meta?.project||q.basename(t),l=s.title||`${c} Docs`,d=[],u={},g=0;if(o.length>0&&d.push({id:"custom-pages",label:"Pages",collapsed:s.sidebar.collapsed.includes("custom-pages"),items:o.map(p=>({id:p.slug,label:p.title,kind:"custom",description:p.description}))}),a&&a.entries.length>0){let p=a.entries.filter(m=>(m.type==="note"||m.type==="policy")&&m.symbols.length>0);p.length>0&&d.push({id:"guides",label:"Guides",collapsed:s.sidebar.collapsed.includes("guides"),items:p.map(m=>({id:m.id,label:m.title,kind:"guide",description:void 0,badge:m.symbols.length>0?`${m.symbols.length} symbols`:void 0}))});}if(n){let p=Object.values(n.components||{}).filter(k=>!pt(k,s));if(p.length>0){let k=new Map;for(let _ of p){let R=_.componentType||"other";k.has(R)||k.set(R,[]),k.get(R).push(_);}let x=[...k.entries()].sort((_,R)=>R[1].length-_[1].length).map(([_,R])=>({id:`components-${_}`,label:`${_.charAt(0).toUpperCase()+_.slice(1)} (${R.length})`,collapsed:s.sidebar.collapsed.includes(`components-${_}`),items:R.sort((I,P)=>I.name.localeCompare(P.name)).map(I=>({id:I.id,label:I.name,kind:"component",description:I.description,badge:I.componentType}))}));d.push({id:"components",label:`Components (${p.length})`,collapsed:s.sidebar.collapsed.includes("components"),items:[],subgroups:x}),u.components=p.length,g+=p.length;}let m=Object.values(n.features||{}).filter(k=>!pt(k,s));m.length>0&&(d.push({id:"features",label:`Features (${m.length})`,collapsed:s.sidebar.collapsed.includes("features"),items:m.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"component",description:k.description}))}),u.features=m.length,g+=m.length);let f=Object.values(n.flows||{}).filter(k=>!pt(k,s)),y=new Set(f.map(k=>k.id)),b=[];if(i)for(let[k,C]of Object.entries(i.flows)){let x=k.replace(/^\$/,"");y.has(x)||b.push({id:x,label:C.name||x,kind:"flow",description:C.description});}let h=[...f.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"flow",description:k.description})),...b];h.length>0&&(d.push({id:"flows",label:`Flows (${h.length})`,collapsed:s.sidebar.collapsed.includes("flows"),items:h}),u.flows=h.length,g+=h.length);let v=Object.values(n.gates||{}).filter(k=>!pt(k,s));v.length>0&&(d.push({id:"gates",label:`Gates (${v.length})`,collapsed:s.sidebar.collapsed.includes("gates"),items:v.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"gate",description:k.description}))}),u.gates=v.length,g+=v.length);let w=Object.values(n.signals||{}).filter(k=>!pt(k,s));w.length>0&&(d.push({id:"signals",label:`Signals (${w.length})`,collapsed:s.sidebar.collapsed.includes("signals"),items:w.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"signal",description:k.description}))}),u.signals=w.length,g+=w.length);let S=Object.values(n.aspects||{}).filter(k=>!pt(k,s));S.length>0&&(d.push({id:"aspects",label:`Aspects (${S.length})`,collapsed:s.sidebar.collapsed.includes("aspects"),items:S.sort((k,C)=>k.name.localeCompare(C.name)).map(k=>({id:k.id,label:k.name,kind:"aspect",description:k.description}))}),u.aspects=S.length,g+=S.length);}if(r){let p=Object.keys(r.routes||{}).length,m=Object.keys(r.gates||{}).length;d.push({id:"portal",label:"Portal",collapsed:s.sidebar.collapsed.includes("portal"),items:[{id:"portal-overview",label:"Authorization Overview",kind:"portal",description:`${m} gates, ${p} routes`,badge:`${p} routes`}]});}return {title:l,project:c,generatedAt:new Date().toISOString(),groups:d,totalSymbols:g,symbolCounts:u}}function Oc(t,e){let s=In(t);if(!s)return null;let n=Pc(s),i=n.get(e);if(!i)return null;let r=[];for(let[y,b]of n)y!==e&&b.related&&b.related.includes(i.symbol)&&r.push(b.symbol);let o=(i.related||[]).slice(),a=[],c=Vs(t);if(c)for(let[y,b]of Object.entries(c.flows)){let h=(b.steps||[]).map(v=>v.symbol);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:y.replace(/^\$/,""),name:b.name||y});}if(s.flows)for(let[y,b]of Object.entries(s.flows)){if(a.some(v=>v.id===y))continue;let h=(b.steps||[]).map(v=>v.symbol).filter(Boolean);(h.includes(i.symbol)||h.includes(`#${e}`))&&a.push({id:y,name:b.name});}let l=[],d=$n(t);if(d&&i.category==="gates"){let y=Object.keys(d.gates||{}).find(b=>b.replace(/^\^/,"")===e);y&&l.push({id:y.replace(/^\^/,""),description:d.gates[y].description});}else if(d){let y=new Set((i.related||[]).filter(b=>b.startsWith("^")));for(let[b,h]of Object.entries(d.routes||{}))for(let v of h){let w=v.replace(/^\^/,"");if(y.has(v)||y.has(`^${w}`)){let S=d.gates[v]||d.gates[`^${w}`]||d.gates[w];S&&!l.some(k=>k.id===w)&&l.push({id:w,description:S.description});}}}let u=[];if(s.aspects)for(let[y,b]of Object.entries(s.aspects))b.related&&b.related.includes(i.symbol)&&u.push(b.symbol);for(let y of i.related||[])y.startsWith("~")&&!u.includes(y)&&u.push(y);let g=[],p=Cc(t);if(p)for(let y of p.entries)y.symbols.includes(i.symbol)&&g.push({id:y.id,title:y.title});let m=i.parent||void 0,f=[];if(s.components)for(let y of Object.values(s.components))y.parent===i.symbol&&f.push(y.symbol);return {id:i.id,symbol:i.symbol,name:i.name,description:i.description||"",category:i.category||"components",componentType:i.componentType,tags:i.visualTags||[],path:i.path||"",related:i.related||[],referencedBy:r,references:o,flows:a,gates:l,aspects:u,guides:g,parent:m,children:f}}function Ac(t,e){let s=Vs(t),n=In(t);if(s){let i=s.flows[`$${e}`]?`$${e}`:e,r=s.flows[i];if(r){let o=(r.steps||[]).map(c=>({type:c.type||"action",symbol:c.symbol||"",description:c.description})),a=n?.flows?.[e.replace(/^\$/,"")];return {id:e.replace(/^\$/,""),symbol:`$${e.replace(/^\$/,"")}`,name:r.name||e,description:r.description,trigger:r.trigger,steps:o,successSignal:r.successSignal,errorSignal:r.errorSignal,tags:a?.visualTags||[],path:a?.path||r.definedIn||""}}}if(n?.flows){let i=e.replace(/^\$/,""),r=n.flows[i];if(r){let o=(r.steps||[]).map(a=>({type:"action",symbol:a.symbol||"",description:a.action||a.name}));return {id:i,symbol:`$${i}`,name:r.name,description:r.description,steps:o,tags:r.visualTags||[],path:r.path||""}}}return null}function Ic(t){let e=$n(t);if(!e)return {version:"0",gates:[],routes:[]};let s=new Map;for(let[r,o]of Object.entries(e.routes||{}))for(let a of o){let c=a.replace(/^\^/,"");s.has(c)||s.set(c,[]),s.get(c).push(r);}let n=Object.entries(e.gates||{}).map(([r,o])=>{let a=r.replace(/^\^/,"");return {symbol:`^${a}`,description:o.description,check:o.check,routes:s.get(a)||[]}}),i=Object.entries(e.routes||{}).map(([r,o])=>{let a=r.indexOf(" "),c=a>0?r.substring(0,a):"GET";return {route:a>0?r.substring(a+1):r,method:c,gates:o.map(d=>{let u=d.replace(/^\^/,""),g=e.gates[d]||e.gates[`^${u}`]||e.gates[u];return {symbol:`^${u}`,description:g?.description}})}});return {version:e.version||"1.0",gates:n,routes:i}}function $c(t,e,s){let n=s||20,i=[],r=e.toLowerCase(),o=In(t);if(o){let d=Pc(o);for(let[u,g]of d){let p=Ys(g.name,g.description||"",g.visualTags||[],r);p>0&&i.push({id:g.id,kind:Cu(g.category),label:g.name,description:g.description||"",matchContext:xc(g.name,g.description||"",r),score:p});}}let a=ut(t),c=jc(t,a.customContent);for(let d of c){let u=d.body.substring(0,200),g=Ys(d.title,u,[],r);g>0&&i.push({id:d.slug,kind:"custom",label:d.title,description:d.description||u.substring(0,100),matchContext:xc(d.title,d.body,r),score:g});}let l=$n(t);if(l)for(let[d,u]of Object.entries(l.gates||{})){let g=d.replace(/^\^/,""),p=Ys(g,u.description,[],r);p>0&&i.push({id:g,kind:"portal",label:`^${g}`,description:u.description,score:p});}return i.sort((d,u)=>u.score-d.score||d.label.localeCompare(u.label)),i.slice(0,n)}function Ys(t,e,s,n){let i=t.toLowerCase(),r=e.toLowerCase();return i===n?1:i.startsWith(n)?.8:i.includes(n)?.6:r.includes(n)?.5:s.some(o=>o.toLowerCase().includes(n))?.3:0}function xc(t,e,s){let i=e.toLowerCase().indexOf(s);if(i<0)return t.toLowerCase().includes(s)?t:void 0;let r=Math.max(0,i-40),o=Math.min(e.length,i+s.length+40),a=e.substring(r,o).trim();return r>0&&(a=`...${a}`),o<e.length&&(a=`${a}...`),a}function Fc(){return [{name:"paradigm_docs_manifest",description:"Get the documentation sidebar manifest \u2014 all symbols grouped by type with counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_page",description:"Get page data for a symbol, flow, portal, or custom docs page. Returns structured data for rendering. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol ID (e.g., "cli-commands", "checkout-flow", "authenticated"). Do not include the prefix (#, $, ^, !, ~).'},flow:{type:"string",description:'Flow ID (e.g., "$init-flow"). Include the $ prefix.'},portal:{type:"boolean",description:"Set to true to get the portal overview page (gates + routes)."},slug:{type:"string",description:'Custom page slug (e.g., "getting-started").'}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_docs_search",description:"Search across all documentation content \u2014 symbols, descriptions, tags, custom pages. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query string"},limit:{type:"number",description:"Maximum results (default: 20)"}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Nc(t,e,s){if(t==="paradigm_docs_manifest"){let n=ut(s.rootDir),i=Dc(s.rootDir,n),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(t==="paradigm_docs_page"){if(e.portal){let i=Ic(s.rootDir),r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}if(e.flow){let i=e.flow,r=Ac(s.rootDir,i);if(!r){let a=JSON.stringify({error:`Flow "${i}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.slug){let i=ut(s.rootDir),r=Tc(s.rootDir,e.slug,i);if(!r){let a=JSON.stringify({error:`Page "${e.slug}" not found`});return o(a.length,t),{handled:true,text:a}}let o$1=JSON.stringify(r,null,2);return o(o$1.length,t),{handled:true,text:o$1}}if(e.symbol){let i=Oc(s.rootDir,e.symbol);if(!i){let o$1=JSON.stringify({error:`Symbol "${e.symbol}" not found`});return o(o$1.length,t),{handled:true,text:o$1}}let r=JSON.stringify(i,null,2);return o(r.length,t),{handled:true,text:r}}let n=JSON.stringify({error:"Provide one of: symbol, flow, portal, or slug"});return o(n.length,t),{handled:true,text:n}}if(t==="paradigm_docs_search"){let n=e.query;if(!n)return {handled:true,text:JSON.stringify({error:"query is required"})};let i=$c(s.rootDir,n,e.limit),r=JSON.stringify({count:i.length,results:i},null,2);return o(r.length,t),{handled:true,text:r}}return {handled:false,text:""}}g$1();e();function Ec(){return [{name:"paradigm_work_log_record",description:"Record a work log entry \u2014 what got done. Auto-attached to sprint boards and standup summaries. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent that did the work (e.g., "builder")'},summary:{type:"string",description:"What was done"},outcome:{type:"string",enum:["pass","fail","partial","blocked"],description:"How it went"},task_ref:{type:"string",description:'Ticket/issue reference (e.g., "ENG-142")'},files_modified:{type:"array",items:{type:"string"},description:"Files that were modified"},symbols_touched:{type:"array",items:{type:"string"},description:"Paradigm symbols touched"},next_steps:{type:"array",items:{type:"string"},description:"What's left to do"},blockers:{type:"array",items:{type:"string"},description:"What's blocking progress"},duration_minutes:{type:"number",description:"How long it took"},commit:{type:"string",description:"Git commit hash"}},required:["agent","summary","outcome"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_work_log_search",description:"Search work log entries \u2014 what got done. Returns recent work, filterable by agent, outcome, symbol, date. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent"},outcome:{type:"string",enum:["pass","fail","partial","blocked"]},task_ref:{type:"string",description:"Filter by ticket reference"},symbol:{type:"string",description:"Filter by symbol touched"},dateFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},dateTo:{type:"string",description:"End date (YYYY-MM-DD)"},limit:{type:"number",description:"Max entries to return (default 20)"},summary:{type:"boolean",description:"Return aggregate summary instead of entries"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_journal_record",description:"Record a learning journal entry \u2014 what an agent learned. Agent-private, travels across projects. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:'Agent who learned this (e.g., "security")'},trigger:{type:"string",enum:["correction_received","confidence_miss","pattern_discovered","debate_loss","failure_analysis","human_feedback","self_reflection"],description:"What triggered this learning moment"},insight:{type:"string",description:"The insight itself"},project:{type:"string",description:"Project where this happened"},transferable:{type:"boolean",description:"Whether this applies to other projects"},confidence_before:{type:"number",description:"Confidence before (0.0-1.0)"},confidence_after:{type:"number",description:"Confidence after (0.0-1.0)"},pattern:{type:"object",properties:{id:{type:"string"},applies_when:{type:"string"},correct_approach:{type:"string"}}},linked_work_log:{type:"string",description:"Work log entry that prompted this"},tags:{type:"array",items:{type:"string"}}},required:["agent","trigger","insight","project","transferable"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_journal_search",description:"Search learning journal entries \u2014 what agents learned. Can search across all agents or a specific one. ~200 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Filter by agent (omit for all agents)"},trigger:{type:"string",description:"Filter by trigger type"},project:{type:"string",description:"Filter by project"},transferable:{type:"boolean",description:"Only show transferable insights"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},stats:{type:"boolean",description:"Return stats instead of entries (requires agent)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_decision_record",description:"Record a team decision \u2014 what we decided and why. Institutional memory with rationale and alternatives. ~100 tokens.",inputSchema:{type:"object",properties:{title:{type:"string",description:"Decision title"},decision:{type:"string",description:"The decision itself"},rationale:{type:"string",description:"Why this was chosen"},participants:{type:"array",items:{type:"object",properties:{id:{type:"string"},role:{type:"string",enum:["human","agent"]},stance:{type:"string",enum:["proposed","supported","dissented","abstained","neutral"]}},required:["id","role","stance"]}},alternatives_considered:{type:"array",items:{type:"object",properties:{option:{type:"string"},rejected_because:{type:"string"}}}},symbols_affected:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","proposed"],description:"Decision status (default: active)"},tags:{type:"array",items:{type:"string"}}},required:["title","decision","rationale","participants"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_decision_search",description:"Search team decisions \u2014 what we decided. Find active decisions by symbol, participant, status. ~200 tokens.",inputSchema:{type:"object",properties:{status:{type:"string",enum:["active","superseded","deprecated","proposed","rejected"]},participant:{type:"string",description:"Filter by participant ID"},symbol:{type:"string",description:"Filter by affected symbol"},tag:{type:"string",description:"Filter by tag prefix"},dateFrom:{type:"string"},dateTo:{type:"string"},limit:{type:"number",description:"Max entries (default 20)"},summary:{type:"boolean",description:"Return aggregate summary"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function Hc(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_work_log_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.summary,i,"work_log"),o=a$5(s.rootDir,{agent:e.agent,summary:r,outcome:e.outcome,task_ref:e.task_ref,files_modified:e.files_modified,symbols_touched:e.symbols_touched,next_steps:e.next_steps,blockers:e.blockers,duration_minutes:e.duration_minutes,commit:e.commit});return {text:n({recorded:true,id:o.id,timestamp:o.timestamp}),handled:true}}case "paradigm_work_log_search":{if(e.summary){let r=d$5(s.rootDir,7);return {text:n(r),handled:true}}let i=b$6(s.rootDir,{agent:e.agent,outcome:e.outcome,task_ref:e.task_ref,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,summary:r.summary,outcome:r.outcome,timestamp:r.timestamp,symbols_touched:r.symbols_touched,task_ref:r.task_ref}))}),handled:true}}case "paradigm_journal_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.insight,i,"learning_journal"),o=a$4(e.agent,{trigger:e.trigger,insight:r,project:e.project,transferable:e.transferable,confidence_before:e.confidence_before,confidence_after:e.confidence_after,pattern:e.pattern,linked_work_log:e.linked_work_log,tags:e.tags});return {text:n({recorded:true,id:o.id,agent:o.agent,timestamp:o.timestamp}),handled:true}}case "paradigm_journal_search":{if(e.stats&&e.agent){let r=e$3(e.agent);return {text:n(r),handled:true}}let i=e.agent?b$5(e.agent,{trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20}):d$4({trigger:e.trigger,project:e.project,transferable:e.transferable,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,agent:r.agent,trigger:r.trigger,insight:r.insight.slice(0,200),project:r.project,transferable:r.transferable,timestamp:r.timestamp}))}),handled:true}}case "paradigm_decision_record":{let i=c$2(s.rootDir),{filtered:r}=d$3(e.decision,i,"team_decisions"),{filtered:o}=d$3(e.rationale,i,"team_decisions"),a=a$3(s.rootDir,{title:e.title,decision:r,rationale:o,participants:e.participants,alternatives_considered:e.alternatives_considered,symbols_affected:e.symbols_affected,status:e.status||"active",tags:e.tags});return {text:n({recorded:true,id:a.id,title:a.title,timestamp:a.timestamp}),handled:true}}case "paradigm_decision_search":{if(e.summary){let r=g$5(s.rootDir);return {text:n(r),handled:true}}let i=d$2(s.rootDir,{status:e.status,participant:e.participant,symbol:e.symbol,tag:e.tag,dateFrom:e.dateFrom,dateTo:e.dateTo,limit:e.limit||20});return {text:n({count:i.length,entries:i.map(r=>({id:r.id,title:r.title,status:r.status,decision:r.decision.slice(0,200),participants:r.participants.map(o=>`${o.id} (${o.stance})`),symbols_affected:r.symbols_affected,timestamp:r.timestamp}))}),handled:true}}default:return {text:`Unknown streams tool: ${t}`,handled:false}}}v();b$2();z();g$1();n();function qc(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ru(t){let e=Date.now(),s=t.match(/^(\d+)(m|h|d)$/);if(s){let n=parseInt(s[1],10),i=s[2],r=i==="m"?n*6e4:i==="h"?n*36e5:n*864e5;return new Date(e-r).toISOString()}return t}async function Mc(t,e,s){let n=i=>JSON.stringify(i,null,2);switch(t){case "paradigm_ambient_nominations":{m$1(s.rootDir);let r=e.pending_only!==false,o=e.limit||20,a=i$2(s.rootDir,{agent:e.agent,urgency:e.urgency,pending_only:r,limit:o+20}),c=t$1(s.rootDir);a=u$1(a,c).slice(0,o);let l=q.join(s.rootDir,".paradigm/events/nominations.jsonl");if(E.existsSync(l))try{let u=E.readFileSync(l,"utf8"),g=new Set(a.map(m=>m.id)),p=u.trim().split(`
442
442
  `).map(m=>{try{let f=JSON.parse(m);return g.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});E.writeFileSync(l,p.join(`
443
443
  `)+`
444
- `,"utf8");}catch{}let d={count:a.length,nominations:a.map(u=>({id:u.id,agent:u.agent,urgency:u.urgency,type:u.type,brief:u.brief,relevance:u.relevance,timestamp:u.timestamp,engaged:u.engaged,response:u.response}))};if(e.include_debates){let g=j$3(s.rootDir).filter(p=>!p.resolution);d.debates=g.map(p=>({id:p.id,topic:p.topic,type:p.type,nominations:p.nominations})),d.debate_count=g.length;}return {text:n(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?Ru(e.since):void 0,r=e.limit||50,o=a$6(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:n({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l}=await import('./session-work-log-6GKGUQ5C.js'),u=i$2(s.rootDir,{limit:500}).find(g=>g.id===i);l(s.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:i,verdict:r,reason:o});}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:n({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,u=f$2(s.rootDir,i);if(!u)return {text:n({error:`Agent profile not found: ${i}`}),handled:true};let g=[],p=p$1(u,r);if(p.trim()&&g.push(p),a){let m=d$3(s.rootDir,{status:"active",limit:l});if(m.length>0){g.push("## Recent Team Decisions");for(let f of m)g.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);g.push("");}}if(c){let m=b$5(i,{transferable:true,limit:d});if(m.length>0){g.push("## Transferable Insights");for(let f of m)g.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);g.push("");}}if(o){let m=i$2(s.rootDir,{pending_only:true,limit:10});if(m.length>0){g.push("## Pending Nominations");for(let f of m)g.push(`- [${f.urgency}] ${f.brief}`);g.push("");}}return {text:n({agent:i,context:g.join(`
445
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:n({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p(s.rootDir,i);if(r)return {text:n({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:n({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q$2(s.rootDir);return {text:n(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:n(await Tu(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${t}`,handled:false}}}var Pu={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ju(t){try{let e=q.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=E.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(n)return n[1].trim()}}catch{}return q.basename(t)}async function Tu(t,e={}){let s=e.dry_run===true,n=ju(t),i=b$a(t),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let f=m.agent;o.has(f)||o.set(f,[]),o.get(f).push(m);}let a=i.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},u=0;for(let[m,f]of o){d[m]=0;let y=f.filter(S=>S.verdict==="accepted").length;f.filter(S=>S.verdict==="dismissed").length;f.filter(S=>S.verdict==="revised").length;let v=f.length,w=v>0?y/v:0;for(let S of f){let k=Pu[S.verdict];if(!k)continue;let C=c.get(m)?.shift(),x=Du(S,C,{acceptRate:w,total:v,accepted:y}),_=S.verdict==="accepted"?.85:S.verdict==="revised"?.6:.4,R={agent:m,verdict:S.verdict,trigger:k,insight:x,symbols:S.symbols};if(l.push(R),s)d[m]++,u++;else try{a$4(m,{trigger:k,insight:x,confidence_before:S.verdict==="accepted"?.7:.8,confidence_after:_,project:n,transferable:S.verdict==="dismissed",tags:["postflight",`verdict:${S.verdict}`,...(S.symbols||[]).map(I=>`symbol:${I}`)]}),d[m]++,u++;}catch{}}}let g={},p=0;if(!s)for(let m of o.keys())try{let f=s$1(t,m);f.promoted>0&&(g[m]=f.promoted,p+=f.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:u,journalsByAgent:d,promoted:p,promotedByAgent:g,dryRun:s,details:l}}function Du(t,e,s){let n=t.symbols?.length?` (symbols: ${t.symbols.join(", ")})`:"",i=t.reason?` Reason: ${t.reason}.`:"";switch(t.verdict){case "accepted":return `Contribution accepted by user${n}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${n}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${n}.${i}`+(t.revisionDelta?` Delta: "${t.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${t.verdict}"${n}.${i}`}}var Ht=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],Lc={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function Fn(t){let e=q.join(t,".paradigm","config.yaml");if(!E.existsSync(e))return {};try{return be.load(E.readFileSync(e,"utf8"))||{}}catch{return {}}}function Ks(t,e){let s=q.join(t,".paradigm","config.yaml");E.writeFileSync(s,be.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Nn(t){let e=t.enforcement?.level||"minimal",s=Lc[e]||Lc.minimal,n=t.enforcement?.checks||{},i=t.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(n))Ht.includes(o)&&Gc(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Gc(t){return t==="block"||t==="warn"||t==="off"}function Ou(t){return t==="strict"||t==="balanced"||t==="minimal"}function Au(t){return Ht.includes(t)}var Iu=[{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+Ht.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function $u(t,e){let{action:s,level:n,checkId:i,severity:r}=e;switch(s){case "status":{let o=Fn(t.rootDir),a=Nn(o),c=o.enforcement?.level||"minimal",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...Ht],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!n||!Ou(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal`});let o=Fn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},Ks(t.rootDir,o);let a=Nn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Au(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Ht.join(", ")}`});if(!r||!Gc(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Fn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,Ks(t.rootDir,o);let a=Nn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=Fn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),Ks(t.rootDir,o);let a=Nn(o),c=o.enforcement?.level||"minimal";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Wc(){return Iu}async function Jc(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await $u(s,e);return o(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}return {handled:false,text:""}}function Fu(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,s[n][i-1]+1,s[n-1][i]+1);return s[e.length][t.length]}function Uc(t,e,s={}){let{maxDistance:n=3,maxResults:i=5}=s,r=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Fu(r,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function Hu(t,e){let s$1=new u(t),n=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:fo,handleTool:i(on)},{key:"tags",tier:"core",getToolsList:Vo,handleTool:i(Ko)},{key:"purpose-portal",tier:"core",getToolsList:sa,handleTool:r$1(ia)},{key:"pm",tier:"core",getToolsList:va,handleTool:i(ka)},{key:"reindex",tier:"core",getToolsList:ka$1,handleTool:r$1(la$1)},{key:"docs",tier:"core",getToolsList:Fc,handleTool:i(Nc)},{key:"ripple",tier:"core",getToolsList:jo,handleTool:i(fn)},{key:"captain",tier:"core",getToolsList:Ho,handleTool:i(St)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:ao,handleTool:i(sn)},{key:"history",tier:"feature",getToolsList:co,handleTool:i(lo)},{key:"lore",tier:"feature",getToolsList:No,handleTool:i(kt)},{key:"streams",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"ambient",tier:"feature",getToolsList:qc,handleTool:i(Mc)},{key:"sentinel",tier:"feature",getToolsList:yo,handleTool:i(ho)},{key:"flows",tier:"feature",getToolsList:wo,handleTool:i(vo)},{key:"fixtures",tier:"feature",getToolsList:Co,handleTool:i(Ro)},{key:"orchestration",tier:"feature",getToolsList:Wo,handleTool:i(Jo)},{key:"habits",tier:"feature",getToolsList:_a,handleTool:i(xa)},{key:"tasks",tier:"feature",getToolsList:Ea,handleTool:i(Ha)},{key:"personas",tier:"feature",getToolsList:Ya,handleTool:i(Va)},{key:"protocols",tier:"feature",getToolsList:To,handleTool:i(yn)},{key:"symphony",tier:"feature",getToolsList:pc,handleTool:i(uc)},{key:"university",tier:"feature",getToolsList:yc,handleTool:i(hc)},{key:"agents",tier:"feature",getToolsList:vc,handleTool:i(kc)},{key:"notebooks",tier:"feature",getToolsList:Sc,handleTool:i(_c)},{key:"aspect-graph",tier:"feature",getToolsList:Fa,handleTool:i(Na)},{key:"enforcement",tier:"feature",getToolsList:Wc,handleTool:i(Jc),detect:o=>E.existsSync(q.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Xa,handleTool:i(Za),detect:o=>E.existsSync(q.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:cc,handleTool:i(lc)},{key:"platform",tier:"advanced",getToolsList:bc,handleTool:i(wc)},{key:"pipeline",tier:"advanced",getToolsList:sc,handleTool:i(ic)},{key:"graduation",tier:"advanced",getToolsList:ja,handleTool:i(Ta)}]),s$1}function qu(t,e){let s=p=>p.toLowerCase().replace(/\/+$/,""),n=s(t),i=s(e);if(n===i)return 1;let r=p=>!p.includes("/")&&p.includes("."),o=p=>r(p)?p.split("."):p.split("/").filter(Boolean),a=o(n),c=o(i);if(r(n)||r(i)){let p=r(n)?n.split("."):n.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),f=0;for(let y=0;y<Math.min(p.length,m.length)&&p[y]===m[y];y++)f++;return f>0?Math.min(1,.5+f/Math.max(p.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let p=0;p<d;p++){let m=a[p]||"",f=c[p]||"";m===f?l++:m.startsWith(":")&&f.startsWith(":")?l+=.9:m.startsWith(":")||f.startsWith(":")?l+=.7:(m.replace(/s$/,"")===f.replace(/s$/,"")||f.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let u=l/d,g=a.length===c.length?.1:0;return Math.min(1,u+g)}function Mu(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function nh(t$1,e,s){let n=e(),i$1=Hu(n.rootDir,s);t$1.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Mu(),...i$1.getActiveTools()]})),t$1.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a}=r.params;q$1(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,u=null;l$1.hasRecoveredThisSession()||(d=await t(c.rootDir),u=a$1(),b$3(),l$1.markRecovered());let g=await(async()=>{switch(o$1){case "paradigm_search":{let{query:p,type:m,limit:f=10,fuzzy:y=true,includeWorkspace:b=false,componentType:h,response_format:v}=a,w=`search:${p}:${m||""}:${f}:${y}:${b}:${h||""}`,S=await v$1.getOrCompute(w,()=>{let _=j$2(c.index,p);return m&&(_=_.filter(R=>R.type===m)),h&&(_=_.filter(R=>R.componentType===h)),_}),k=[];if(S.length===0&&y){let _=n$2(c.index),R=_.map(I=>I.symbol);k=Uc(p,R,{maxDistance:3,maxResults:5}),k.length>0&&(S=k.map(I=>_.find(P=>P.symbol===I.match)).filter(I=>I!=null),m&&(S=S.filter(I=>I.type===m)));}S=S.slice(0,f);let C={query:p,count:S.length,results:S.map(_=>({symbol:_.symbol,type:_.type,description:_.description,filePath:_.filePath,..._.componentType?{componentType:_.componentType}:{},..._.parentSymbol?{parentSymbol:_.parentSymbol}:{}}))};if(k.length>0&&(C.fuzzyMatched=true,C.fuzzyNote=`No exact matches for "${p}". Showing similar symbols.`,C.suggestions=k.map(_=>({symbol:_.match,distance:_.distance}))),b&&c.workspace){let _=bt(c.workspace,p),R=m?_.filter(I=>I.type===m):_;R.length>0&&(C.workspaceResults=R.slice(0,f).map(I=>({symbol:I.symbol,type:I.type,description:I.description,filePath:I.filePath,project:I.project})),C.workspaceCount=R.length);}v==="concise"&&(C.results=S.map(_=>({symbol:_.symbol,type:_.type})),delete C.fuzzyMatched,delete C.fuzzyNote,delete C.suggestions,delete C.workspaceResults,delete C.workspaceCount);let x=JSON.stringify(C,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:p}=a,m=h(c.index,p);if(!m){let h=mn(c.rootDir,p,{maxResults:20});if(h.length===0){let C=JSON.stringify({error:"Symbol not found",symbol:p,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return o(C.length,o$1),{content:[{type:"text",text:C}]}}let v=[...new Set(h.map(C=>C.filePath))],w=h.filter(C=>C.context==="purpose"),S=h.filter(C=>C.context==="code"),k=JSON.stringify({symbol:p,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:v.slice(0,10).map(C=>({file:C,references:h.filter(x=>x.filePath===C).length})),uses:[],summary:{totalFiles:v.length,totalReferences:h.length,purposeFileRefs:w.length,codeRefs:S.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(k.length,o$1),{content:[{type:"text",text:k}]}}let f=k(c.index,p),y=l(c.index,p),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let p=a.response_format,m$1=await v$1.getOrCompute("status",async()=>{let y=m(c.index),b=Object.values(y).reduce((D,j)=>D+j,0),h={};for(let D of Object.keys(y)){let j=i(c.index,D);h[D]=j.slice(0,3).map(T=>T.symbol);}let v=Fo.platform(),w=v==="win32",S=w?"PowerShell/CMD":v==="darwin"?"zsh/bash":"bash",k;try{let D=await V(c.rootDir);D&&D.health.total>0&&(k=D.health);}catch{}let C=i(c.index,"component"),x={};for(let D of C)D.componentType&&(x[D.componentType]=(x[D.componentType]||0)+1);let _=C.filter(D=>!D.componentType).length,R;try{let{checkPurposeHealth:D}=await import('./integrity-checker-VSR3ITBL.js');R=D(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let I;try{let{countNotebookReferences:D}=await import('./session-work-log-6GKGUQ5C.js'),j=D(c.rootDir);j>0&&(I=j);}catch{}let P;try{let{getComplianceTrend:D,getHealthDot:j}=await import('./compliance-health-HCZTJDN7.js'),T=D(c.rootDir);T&&(P={trend:T,dot:j(T,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":y.component,"$ flows":y.flow,"^ gates":y.gate,"! signals":y.signal,"~ aspects":y.aspect},total:b,...Object.keys(x).length>0?{componentTypes:{...x,..._>0?{"(untyped)":_}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...R!==void 0?{purposeHealthScore:R}:{},...k?{protocols:k}:{},...I!==void 0?{notebookReferences:I}:{},...P?{complianceHealth:P}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:v,shell:S,terminalNote:w?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),f=m$1;if(p==="concise")try{let y=JSON.parse(m$1);f=JSON.stringify({project:y.project,counts:y.counts,total:y.total},null,2);}catch{}return o(f.length,o$1),{content:[{type:"text",text:f}]}}case "paradigm_gates_for_route":{let{route:p,response_format:m}=a,y=typeof p=="string"&&!p.includes("/")&&p.includes(".")?"POST":a.method||"GET",b=i(c.index,"gate"),h=[],v=[];if(c.gateConfig?.routes)for(let[P,D]of Object.entries(c.gateConfig.routes))D.gates&&v.push({route:P,gates:D.gates,method:D.method});if(c.workspace)for(let[P,D]of c.workspace.siblingIndices){let j=D.gateConfig;if(j?.routes)for(let[T,A]of Object.entries(j.routes)){let $=A,F=Array.isArray($)?$:$?.gates;F&&v.push({route:T,gates:F,method:Array.isArray($)?void 0:$?.method,source:P});}}for(let P of v){let D=qu(p,P.route);if(D>=.6&&(!P.method||P.method===y))for(let j of P.gates){let T=b.find(A=>A.symbol===j||A.symbol===`^${j}`);if(T&&!h.find(A=>A.gate===T.symbol)){let A=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:T.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:A});}}}let k=p.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",C=p.match(/\/:(id|[a-z]+Id)($|\/)/i);if(C&&k){let P=b.find(D=>{let j=D.symbol.toLowerCase(),T=(D.description||"").toLowerCase();return j.includes(`${k}-owner`)||j.includes("owner")||j.includes("ownership")||T.includes("owner")||T.includes("ownership")||T.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${k}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${k}-owner`,reason:`Consider adding ownership gate for ${k} resource`,confidence:"medium"});}if(p.includes("/admin")||p.includes("/settings")){let P=b.find(D=>D.symbol.includes("admin")||D.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(p.startsWith("/api/")||p.includes("/user")||p.includes("/account")){let P=b.find(D=>D.symbol.includes("authenticated")||D.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(p.includes("/premium")||p.includes("/pro")||p.includes("/export")){let P=b.find(D=>D.symbol.includes("subscription")||D.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(y==="DELETE"){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(y)){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let x=new Set,_=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),R=m==="concise"?{suggestions:_.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:p,method:y,suggestions:_,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:C?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},I=JSON.stringify(R,null,2);o(I.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:_.map(P=>P.gate),context:`Gate check for ${y} ${p}`});}catch{}return {content:[{type:"text",text:I}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:p}=await import('./plugin-update-checker-2EM4K45U.js'),m=await p(),f=m.filter(v=>v.hasRemoteUpdate||v.hasCacheStale);if(f.length===0){let v=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(v.length,o$1),{content:[{type:"text",text:v}]}}let y=[`Plugin updates available:
444
+ `,"utf8");}catch{}let d={count:a.length,nominations:a.map(u=>({id:u.id,agent:u.agent,urgency:u.urgency,type:u.type,brief:u.brief,relevance:u.relevance,timestamp:u.timestamp,engaged:u.engaged,response:u.response}))};if(e.include_debates){let g=j$3(s.rootDir).filter(p=>!p.resolution);d.debates=g.map(p=>({id:p.id,topic:p.topic,type:p.type,nominations:p.nominations})),d.debate_count=g.length;}return {text:n(d),handled:true}}case "paradigm_ambient_events":{let i=e.since?Ru(e.since):void 0,r=e.limit||50,o=a$6(s.rootDir,{type:e.type,source:e.source,symbol:e.symbol,agent:e.agent,since:i,limit:r});return {text:n({count:o.length,events:o.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i=e.nomination_id,r=e.response,o=e.reason,a=k$1(s.rootDir,i,r,o);if(a)try{let{appendSessionWorkEntry:l}=await import('./session-work-log-BX434ZLK.js'),u=i$2(s.rootDir,{limit:500}).find(g=>g.id===i);l(s.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:u?.agent,nominationId:i,verdict:r,reason:o});}catch{}let c=false;return e.resolve_debate&&a&&(c=l$1(s.rootDir,e.resolve_debate,i,e.reason)),{text:n({engaged:a,nomination_id:i,response:r,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let i=e.agent,r=e.symbols||[],o=e.include_nominations!==false,a=e.include_decisions!==false,c=e.include_journal!==false,l=e.max_decisions||5,d=e.max_journal||5,u=f$2(s.rootDir,i);if(!u)return {text:n({error:`Agent profile not found: ${i}`}),handled:true};let g=[],p=p$1(u,r);if(p.trim()&&g.push(p),a){let m=d$2(s.rootDir,{status:"active",limit:l});if(m.length>0){g.push("## Recent Team Decisions");for(let f of m)g.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);g.push("");}}if(c){let m=b$5(i,{transferable:true,limit:d});if(m.length>0){g.push("## Transferable Insights");for(let f of m)g.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);g.push("");}}if(o){let m=i$2(s.rootDir,{pending_only:true,limit:10});if(m.length>0){g.push("## Pending Nominations");for(let f of m)g.push(`- [${f.urgency}] ${f.brief}`);g.push("");}}return {text:n({agent:i,context:g.join(`
445
+ `),sections_included:{profile:true,decisions:a,journal:c,nominations:o}}),handled:true}}case "paradigm_ambient_promote":{let i=e.agent,r=s$1(s.rootDir,i);return {text:n({agent:i,promoted:r.promoted,entries:r.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e.agent,r=e.dry_run===true,o=p(s.rootDir,i);if(r)return {text:n({agent:i,dry_run:true,stats:o,note:o.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(o.acceptRate*100).toFixed(0)}% \u2014 ${o.acceptRate>.8?"would lower threshold":o.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=o$1(s.rootDir,i);return {text:n({agent:i,...a,stats:o}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q$2(s.rootDir);return {text:n(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:n(await Tu(s.rootDir,e)),handled:true};default:return {text:`Unknown ambient tool: ${t}`,handled:false}}}var Pu={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ju(t){try{let e=q.join(t,".paradigm","config.yaml");if(E.existsSync(e)){let n=E.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(n)return n[1].trim()}}catch{}return q.basename(t)}async function Tu(t,e={}){let s=e.dry_run===true,n=ju(t),i=b$a(t),r=i.filter(m=>m.type==="user-verdict"&&m.verdict&&m.agent);if(r.length===0)return {sessionEntries:i.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:s,details:[]};let o=new Map;for(let m of r){let f=m.agent;o.has(f)||o.set(f,[]),o.get(f).push(m);}let a=i.filter(m=>m.type==="agent-contribution"),c=new Map;for(let m of a)m.agent&&(c.has(m.agent)||c.set(m.agent,[]),c.get(m.agent).push(m));let l=[],d={},u=0;for(let[m,f]of o){d[m]=0;let y=f.filter(S=>S.verdict==="accepted").length;f.filter(S=>S.verdict==="dismissed").length;f.filter(S=>S.verdict==="revised").length;let v=f.length,w=v>0?y/v:0;for(let S of f){let k=Pu[S.verdict];if(!k)continue;let C=c.get(m)?.shift(),x=Du(S,C,{acceptRate:w,total:v,accepted:y}),_=S.verdict==="accepted"?.85:S.verdict==="revised"?.6:.4,R={agent:m,verdict:S.verdict,trigger:k,insight:x,symbols:S.symbols};if(l.push(R),s)d[m]++,u++;else try{a$4(m,{trigger:k,insight:x,confidence_before:S.verdict==="accepted"?.7:.8,confidence_after:_,project:n,transferable:S.verdict==="dismissed",tags:["postflight",`verdict:${S.verdict}`,...(S.symbols||[]).map(I=>`symbol:${I}`)]}),d[m]++,u++;}catch{}}}let g={},p=0;if(!s)for(let m of o.keys())try{let f=s$1(t,m);f.promoted>0&&(g[m]=f.promoted,p+=f.promoted);}catch{}return {sessionEntries:i.length,agentsProcessed:Array.from(o.keys()),journalsWritten:u,journalsByAgent:d,promoted:p,promotedByAgent:g,dryRun:s,details:l}}function Du(t,e,s){let n=t.symbols?.length?` (symbols: ${t.symbols.join(", ")})`:"",i=t.reason?` Reason: ${t.reason}.`:"";switch(t.verdict){case "accepted":return `Contribution accepted by user${n}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "dismissed":return `Contribution dismissed by user${n}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;case "revised":return `Contribution revised by user${n}.${i}`+(t.revisionDelta?` Delta: "${t.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(s.acceptRate*100).toFixed(0)}% (${s.accepted}/${s.total}).`;default:return `Unknown verdict "${t.verdict}"${n}.${i}`}}var Ht=["purpose-coverage","purpose-exists","portal-gates","aspect-anchors","purpose-freshness","aspect-advisory","lore-required","habits-blocking","purpose-required-patterns","drift-detection","portal-compliance","graduation-tracking","orchestration-required"],Lc={strict:{"purpose-coverage":"block","purpose-exists":"block","portal-gates":"block","aspect-anchors":"block","purpose-freshness":"warn","aspect-advisory":"warn","lore-required":"block","habits-blocking":"block","purpose-required-patterns":"block","drift-detection":"block","portal-compliance":"block","graduation-tracking":"warn","orchestration-required":"block"},balanced:{"purpose-coverage":"block","purpose-exists":"warn","portal-gates":"warn","aspect-anchors":"warn","purpose-freshness":"warn","aspect-advisory":"off","lore-required":"warn","habits-blocking":"block","purpose-required-patterns":"warn","drift-detection":"warn","portal-compliance":"warn","graduation-tracking":"off","orchestration-required":"warn"},minimal:{"purpose-coverage":"warn","purpose-exists":"off","portal-gates":"off","aspect-anchors":"off","purpose-freshness":"off","aspect-advisory":"off","lore-required":"off","habits-blocking":"warn","purpose-required-patterns":"off","drift-detection":"off","portal-compliance":"off","graduation-tracking":"off","orchestration-required":"off"}};function Fn(t){let e=q.join(t,".paradigm","config.yaml");if(!E.existsSync(e))return {};try{return be.load(E.readFileSync(e,"utf8"))||{}}catch{return {}}}function Ks(t,e){let s=q.join(t,".paradigm","config.yaml");E.writeFileSync(s,be.dump(e,{lineWidth:120,noRefs:true}),"utf8");}function Nn(t){let e=t.enforcement?.level||"minimal",s=Lc[e]||Lc.minimal,n=t.enforcement?.checks||{},i=t.enforcement?.orchestration?.threshold??3,r={...s};for(let[o,a]of Object.entries(n))Ht.includes(o)&&Gc(a)&&(r[o]=a);return r.orchestrationThreshold=i,r}function Gc(t){return t==="block"||t==="warn"||t==="off"}function Ou(t){return t==="strict"||t==="balanced"||t==="minimal"}function Au(t){return Ht.includes(t)}var Iu=[{name:"paradigm_enforcement_configure",description:"View or modify stop hook enforcement levels. Actions: status (view current), set-level (change preset), override (set per-check severity), reset (clear overrides). ~250 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["status","set-level","override","reset"],description:"Action to perform."},level:{type:"string",enum:["strict","balanced","minimal"],description:"Enforcement preset level (for set-level action)."},checkId:{type:"string",description:"Check ID to override (for override action). One of: "+Ht.join(", ")},severity:{type:"string",enum:["block","warn","off"],description:"Severity to set for the check (for override action)."}},required:["action"]}}];async function $u(t,e){let{action:s,level:n,checkId:i,severity:r}=e;switch(s){case "status":{let o=Fn(t.rootDir),a=Nn(o),c=o.enforcement?.level||"minimal",l=o.enforcement?.checks||{},d=o.enforcement?.orchestration?.threshold??3;return JSON.stringify({level:c,orchestrationThreshold:d,orchestrationNote:"Threshold is compared against magnitude score (not just file count). Magnitude = source files + cross-package penalty + security-adjacent penalty + symbol file changes.",overrides:Object.keys(l).length>0?l:void 0,effective:a,checkIds:[...Ht],presetLevels:["strict","balanced","minimal"]},null,2)}case "set-level":{if(!n||!Ou(n))return JSON.stringify({error:`Invalid level "${n}". Must be one of: strict, balanced, minimal`});let o=Fn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.level=n,o.enforcement.checks={},Ks(t.rootDir,o);let a=Nn(o);return JSON.stringify({success:true,level:n,message:`Enforcement level set to "${n}". Per-check overrides cleared.`,effective:a},null,2)}case "override":{if(!i||!Au(i))return JSON.stringify({error:`Invalid checkId "${i}". Must be one of: ${Ht.join(", ")}`});if(!r||!Gc(r))return JSON.stringify({error:`Invalid severity "${r}". Must be one of: block, warn, off`});let o=Fn(t.rootDir);o.enforcement||(o.enforcement={}),o.enforcement.checks||(o.enforcement.checks={}),o.enforcement.checks[i]=r,Ks(t.rootDir,o);let a=Nn(o);return JSON.stringify({success:true,checkId:i,severity:r,message:`Override set: ${i} = ${r}`,effective:a},null,2)}case "reset":{let o=Fn(t.rootDir);o.enforcement&&(o.enforcement.checks={}),Ks(t.rootDir,o);let a=Nn(o),c=o.enforcement?.level||"minimal";return JSON.stringify({success:true,message:`All per-check overrides cleared. Preset "${c}" is now fully in effect.`,effective:a},null,2)}default:return JSON.stringify({error:`Unknown action "${s}". Must be one of: status, set-level, override, reset`})}}function Wc(){return Iu}async function Jc(t,e,s){if(t==="paradigm_enforcement_configure"){let n=await $u(s,e);return o(n.length,"paradigm_enforcement_configure"),{handled:true,text:n}}return {handled:false,text:""}}function Fu(t,e){let s=[];for(let n=0;n<=e.length;n++)s[n]=[n];for(let n=0;n<=t.length;n++)s[0][n]=n;for(let n=1;n<=e.length;n++)for(let i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?s[n][i]=s[n-1][i-1]:s[n][i]=Math.min(s[n-1][i-1]+1,s[n][i-1]+1,s[n-1][i]+1);return s[e.length][t.length]}function Uc(t,e,s={}){let{maxDistance:n=3,maxResults:i=5}=s,r=t.toLowerCase(),o=[];for(let a of e){let c=a.toLowerCase();if(c===r){o.push({match:a,distance:0});continue}if(c.includes(r)||r.includes(c)){o.push({match:a,distance:1});continue}let l=Fu(r,c);l<=n&&o.push({match:a,distance:l});}return o.sort((a,c)=>a.distance!==c.distance?a.distance-c.distance:a.match.localeCompare(c.match)),o.slice(0,i)}v();function Hu(t,e){let s$1=new u(t),n=e||(async()=>{}),i=o=>async(a,c,l)=>o(a,c,l),r$1=o=>async(a,c,l)=>o(a,c,l,n);return s$1.registerAll([{key:"context",tier:"core",getToolsList:r,handleTool:i(s)},{key:"navigate",tier:"core",getToolsList:fo,handleTool:i(on)},{key:"tags",tier:"core",getToolsList:Vo,handleTool:i(Ko)},{key:"purpose-portal",tier:"core",getToolsList:sa,handleTool:r$1(ia)},{key:"pm",tier:"core",getToolsList:va,handleTool:i(ka)},{key:"reindex",tier:"core",getToolsList:ka$1,handleTool:r$1(la$1)},{key:"docs",tier:"core",getToolsList:Fc,handleTool:i(Nc)},{key:"ripple",tier:"core",getToolsList:jo,handleTool:i(fn)},{key:"captain",tier:"core",getToolsList:Ho,handleTool:i(St)}]),s$1.registerAll([{key:"wisdom",tier:"feature",getToolsList:ao,handleTool:i(sn)},{key:"history",tier:"feature",getToolsList:co,handleTool:i(lo)},{key:"lore",tier:"feature",getToolsList:No,handleTool:i(kt)},{key:"streams",tier:"feature",getToolsList:Ec,handleTool:i(Hc)},{key:"ambient",tier:"feature",getToolsList:qc,handleTool:i(Mc)},{key:"sentinel",tier:"feature",getToolsList:yo,handleTool:i(ho)},{key:"flows",tier:"feature",getToolsList:wo,handleTool:i(vo)},{key:"fixtures",tier:"feature",getToolsList:Co,handleTool:i(Ro)},{key:"orchestration",tier:"feature",getToolsList:Wo,handleTool:i(Jo)},{key:"habits",tier:"feature",getToolsList:_a,handleTool:i(xa)},{key:"tasks",tier:"feature",getToolsList:Ea,handleTool:i(Ha)},{key:"personas",tier:"feature",getToolsList:Ya,handleTool:i(Va)},{key:"protocols",tier:"feature",getToolsList:To,handleTool:i(yn)},{key:"symphony",tier:"feature",getToolsList:pc,handleTool:i(uc)},{key:"university",tier:"feature",getToolsList:yc,handleTool:i(hc)},{key:"agents",tier:"feature",getToolsList:vc,handleTool:i(kc)},{key:"notebooks",tier:"feature",getToolsList:Sc,handleTool:i(_c)},{key:"aspect-graph",tier:"feature",getToolsList:Fa,handleTool:i(Na)},{key:"enforcement",tier:"feature",getToolsList:Wc,handleTool:i(Jc),detect:o=>E.existsSync(q.join(o,".paradigm","config.yaml"))},{key:"graph",tier:"feature",getToolsList:Xa,handleTool:i(Za),detect:o=>E.existsSync(q.join(o,".paradigm","aspect-graph.db"))}]),s$1.registerAll([{key:"conductor",tier:"advanced",getToolsList:cc,handleTool:i(lc)},{key:"platform",tier:"advanced",getToolsList:bc,handleTool:i(wc)},{key:"pipeline",tier:"advanced",getToolsList:sc,handleTool:i(ic)},{key:"graduation",tier:"advanced",getToolsList:ja,handleTool:i(Ta)}]),s$1}function qu(t,e){let s=p=>p.toLowerCase().replace(/\/+$/,""),n=s(t),i=s(e);if(n===i)return 1;let r=p=>!p.includes("/")&&p.includes("."),o=p=>r(p)?p.split("."):p.split("/").filter(Boolean),a=o(n),c=o(i);if(r(n)||r(i)){let p=r(n)?n.split("."):n.split("/").filter(Boolean),m=r(i)?i.split("."):i.split("/").filter(Boolean),f=0;for(let y=0;y<Math.min(p.length,m.length)&&p[y]===m[y];y++)f++;return f>0?Math.min(1,.5+f/Math.max(p.length,m.length)*.5):0}let l=0,d=Math.max(a.length,c.length);for(let p=0;p<d;p++){let m=a[p]||"",f=c[p]||"";m===f?l++:m.startsWith(":")&&f.startsWith(":")?l+=.9:m.startsWith(":")||f.startsWith(":")?l+=.7:(m.replace(/s$/,"")===f.replace(/s$/,"")||f.replace(/s$/,"")===m.replace(/s$/,""))&&(l+=.8);}let u=l/d,g=a.length===c.length?.1:0;return Math.min(1,u+g)}function Mu(){return [{name:"paradigm_search",description:"Search for Paradigm symbols by name, description, or tags. Includes fuzzy matching for typo tolerance. Returns matching symbols with names, paths, types, and descriptions. ~150 tokens.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query (matches symbol names, descriptions, tags)"},type:{type:"string",enum:["component","flow","gate","signal","aspect"],description:"Optional: filter by symbol type (v2: #component, $flow, ^gate, !signal, ~aspect)"},limit:{type:"number",description:"Maximum results to return (default: 10)"},fuzzy:{type:"boolean",description:"Enable fuzzy matching for typos (default: true)"},includeWorkspace:{type:"boolean",description:"Also search sibling workspace projects (default: false). Requires workspace configured in config.yaml."},componentType:{type:"string",description:'Filter components by type (e.g., "view", "service", "tool"). Only applies to #component symbols.'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["query"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["find","lookup","locate","where is","which symbol","find symbol"]},{name:"paradigm_related",description:"Get all symbols related to a given symbol. Call before modifying code to understand what uses this symbol and what it depends on. Returns uses/used-by lists with symbol types. ~150 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:"Symbol to find relations for"}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_status",description:"Get project overview - call this at session start for orientation. Shows symbol counts, project health, and available features. Returns symbol counts by type, project health score, and feature flags. ~100 tokens.",inputSchema:{type:"object",properties:{response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["health","overview","dashboard","project status","orientation"]},{name:"paradigm_gates_for_route",description:"Suggest which gates should be applied to a route based on patterns in the project. Returns suggested gates with confidence scores and existing patterns. ~150 tokens.",inputSchema:{type:"object",properties:{route:{type:"string",description:"Route path (e.g., /api/users, /admin/settings)"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method"},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["route"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["auth","permissions","route security","what gates","protect route"]},{name:"paradigm_plugin_check",description:"Check for updates to installed Claude Code plugins. Reports which marketplace clones have newer remote commits and which cached versions are stale.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_workspace_reindex",description:"Rebuild scan-index.json for all workspace members. Requires workspace configured in config.yaml. Returns per-member symbol counts. ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true}},{name:"paradigm_tool_activate",description:"Activate an advanced-tier tool module for this session. Advanced tools are not loaded by default to reduce tool count. Call with a feature key to make its tools available. ~50 tokens.",inputSchema:{type:"object",properties:{feature:{type:"string",description:'Feature key to activate (e.g., "graph", "heatmap", "pipeline", "conductor", "platform")'}},required:["feature"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}function nh(t$1,e,s){let n=e(),i$1=Hu(n.rootDir,s);t$1.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[...Mu(),...i$1.getActiveTools()]})),t$1.setRequestHandler(CallToolRequestSchema,async r=>{let{name:o$1,arguments:a}=r.params;q$1(o$1,a??{});let c=e(),l$1=j$1();l$1.setRootDir(c.rootDir);let d=null,u=null;l$1.hasRecoveredThisSession()||(d=await t(c.rootDir),u=a$1(),b$3(),l$1.markRecovered());let g=await(async()=>{switch(o$1){case "paradigm_search":{let{query:p,type:m,limit:f=10,fuzzy:y=true,includeWorkspace:b=false,componentType:h,response_format:v}=a,w=`search:${p}:${m||""}:${f}:${y}:${b}:${h||""}`,S=await v$1.getOrCompute(w,()=>{let _=j$2(c.index,p);return m&&(_=_.filter(R=>R.type===m)),h&&(_=_.filter(R=>R.componentType===h)),_}),k=[];if(S.length===0&&y){let _=n$2(c.index),R=_.map(I=>I.symbol);k=Uc(p,R,{maxDistance:3,maxResults:5}),k.length>0&&(S=k.map(I=>_.find(P=>P.symbol===I.match)).filter(I=>I!=null),m&&(S=S.filter(I=>I.type===m)));}S=S.slice(0,f);let C={query:p,count:S.length,results:S.map(_=>({symbol:_.symbol,type:_.type,description:_.description,filePath:_.filePath,..._.componentType?{componentType:_.componentType}:{},..._.parentSymbol?{parentSymbol:_.parentSymbol}:{}}))};if(k.length>0&&(C.fuzzyMatched=true,C.fuzzyNote=`No exact matches for "${p}". Showing similar symbols.`,C.suggestions=k.map(_=>({symbol:_.match,distance:_.distance}))),b&&c.workspace){let _=bt(c.workspace,p),R=m?_.filter(I=>I.type===m):_;R.length>0&&(C.workspaceResults=R.slice(0,f).map(I=>({symbol:I.symbol,type:I.type,description:I.description,filePath:I.filePath,project:I.project})),C.workspaceCount=R.length);}v==="concise"&&(C.results=S.map(_=>({symbol:_.symbol,type:_.type})),delete C.fuzzyMatched,delete C.fuzzyNote,delete C.suggestions,delete C.workspaceResults,delete C.workspaceCount);let x=JSON.stringify(C,null,2);return o(x.length,o$1),{content:[{type:"text",text:x}]}}case "paradigm_related":{let{symbol:p}=a,m=h(c.index,p);if(!m){let h=mn(c.rootDir,p,{maxResults:20});if(h.length===0){let C=JSON.stringify({error:"Symbol not found",symbol:p,fallback:"searched",referencesFound:0,recovery:["Run `paradigm_search` with a partial name to find similar symbols","Check `.purpose` files for symbol definitions","Use `paradigm_status` to see available symbols by type","The symbol may not be indexed yet - run `paradigm scan`"]},null,2);return o(C.length,o$1),{content:[{type:"text",text:C}]}}let v=[...new Set(h.map(C=>C.filePath))],w=h.filter(C=>C.context==="purpose"),S=h.filter(C=>C.context==="code"),k=JSON.stringify({symbol:p,status:"not-indexed",fallback:"grep-search",note:"Approximate relationships from grep \u2014 run `paradigm scan` for accurate graph data.",usedBy:v.slice(0,10).map(C=>({file:C,references:h.filter(x=>x.filePath===C).length})),uses:[],summary:{totalFiles:v.length,totalReferences:h.length,purposeFileRefs:w.length,codeRefs:S.length},suggestion:"Run `paradigm scan` to enable full relationship tracking"},null,2);return o(k.length,o$1),{content:[{type:"text",text:k}]}}let f=k(c.index,p),y=l(c.index,p),b=JSON.stringify({symbol:m.symbol,type:m.type,description:m.description,usedBy:f.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),uses:y.map(h=>({symbol:h.symbol,type:h.type,description:h.description}))},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}case "paradigm_status":{let p=a.response_format,m$1=await v$1.getOrCompute("status",async()=>{let y=m(c.index),b=Object.values(y).reduce((D,j)=>D+j,0),h={};for(let D of Object.keys(y)){let j=i(c.index,D);h[D]=j.slice(0,3).map(T=>T.symbol);}let v=Fo.platform(),w=v==="win32",S=w?"PowerShell/CMD":v==="darwin"?"zsh/bash":"bash",k;try{let D=await V(c.rootDir);D&&D.health.total>0&&(k=D.health);}catch{}let C=i(c.index,"component"),x={};for(let D of C)D.componentType&&(x[D.componentType]=(x[D.componentType]||0)+1);let _=C.filter(D=>!D.componentType).length,R;try{let{checkPurposeHealth:D}=await import('./integrity-checker-DHGMZQDG.js');R=D(c.aggregation.purposeFiles,c.rootDir).healthScore;}catch{}let I;try{let{countNotebookReferences:D}=await import('./session-work-log-BX434ZLK.js'),j=D(c.rootDir);j>0&&(I=j);}catch{}let P;try{let{getComplianceTrend:D,getHealthDot:j}=await import('./compliance-health-JNP3P35P.js'),T=D(c.rootDir);T&&(P={trend:T,dot:j(T,c.rootDir)});}catch{}return JSON.stringify({project:c.projectName,symbolSystem:"v2",counts:{"# components":y.component,"$ flows":y.flow,"^ gates":y.gate,"! signals":y.signal,"~ aspects":y.aspect},total:b,...Object.keys(x).length>0?{componentTypes:{...x,..._>0?{"(untyped)":_}:{}}}:{},examples:h,hasPortalYaml:c.gateConfig!==null,purposeFiles:c.aggregation.purposeFiles.length,...R!==void 0?{purposeHealthScore:R}:{},...k?{protocols:k}:{},...I!==void 0?{notebookReferences:I}:{},...P?{complianceHealth:P}:{},note:"Symbol System v2: Use tags [feature], [state], [integration], [idea] for classification. Use type field for structural role (view, service, tool, etc.)",environment:{os:v,shell:S,terminalNote:w?"Use PowerShell syntax: semicolons for command chaining, backslashes for paths, $env:VAR for env vars":"Use Unix syntax: && for command chaining, forward slashes for paths, $VAR for env vars"}},null,2)}),f=m$1;if(p==="concise")try{let y=JSON.parse(m$1);f=JSON.stringify({project:y.project,counts:y.counts,total:y.total},null,2);}catch{}return o(f.length,o$1),{content:[{type:"text",text:f}]}}case "paradigm_gates_for_route":{let{route:p,response_format:m}=a,y=typeof p=="string"&&!p.includes("/")&&p.includes(".")?"POST":a.method||"GET",b=i(c.index,"gate"),h=[],v=[];if(c.gateConfig?.routes)for(let[P,D]of Object.entries(c.gateConfig.routes))D.gates&&v.push({route:P,gates:D.gates,method:D.method});if(c.workspace)for(let[P,D]of c.workspace.siblingIndices){let j=D.gateConfig;if(j?.routes)for(let[T,A]of Object.entries(j.routes)){let $=A,F=Array.isArray($)?$:$?.gates;F&&v.push({route:T,gates:F,method:Array.isArray($)?void 0:$?.method,source:P});}}for(let P of v){let D=qu(p,P.route);if(D>=.6&&(!P.method||P.method===y))for(let j of P.gates){let T=b.find(A=>A.symbol===j||A.symbol===`^${j}`);if(T&&!h.find(A=>A.gate===T.symbol)){let A=P.source?`${P.source}/portal.yaml`:"portal.yaml";h.push({gate:T.symbol,reason:`Similar route "${P.route}" uses this gate`,confidence:D>=.8?"high":"medium",source:A});}}}let k=p.split("/").filter(Boolean).find(P=>!P.startsWith(":")&&P!=="api")?.replace(/s$/,"")||"",C=p.match(/\/:(id|[a-z]+Id)($|\/)/i);if(C&&k){let P=b.find(D=>{let j=D.symbol.toLowerCase(),T=(D.description||"").toLowerCase();return j.includes(`${k}-owner`)||j.includes("owner")||j.includes("ownership")||T.includes("owner")||T.includes("ownership")||T.includes("belongs to")});P?h.push({gate:P.symbol,reason:`Resource ID route (${k}) typically needs ownership verification`,confidence:"high"}):h.push({gate:`^${k}-owner`,reason:`Consider adding ownership gate for ${k} resource`,confidence:"medium"});}if(p.includes("/admin")||p.includes("/settings")){let P=b.find(D=>D.symbol.includes("admin")||D.description?.toLowerCase().includes("admin"));P&&h.push({gate:P.symbol,reason:"Route appears to be admin-related",confidence:"high"});}if(p.startsWith("/api/")||p.includes("/user")||p.includes("/account")){let P=b.find(D=>D.symbol.includes("authenticated")||D.symbol.includes("auth"));P&&h.push({gate:P.symbol,reason:"API/user routes typically require authentication",confidence:"high"});}if(p.includes("/premium")||p.includes("/pro")||p.includes("/export")){let P=b.find(D=>D.symbol.includes("subscription")||D.symbol.includes("premium"));P&&h.push({gate:P.symbol,reason:"Route appears to be a premium feature",confidence:"medium"});}if(y==="DELETE"){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"DELETE operations require authentication",confidence:"high"});}if(["POST","PUT","PATCH"].includes(y)){let P=b.find(D=>D.symbol.includes("authenticated"));P&&!h.find(D=>D.gate===P.symbol)&&h.push({gate:P.symbol,reason:"Write operations typically require authentication",confidence:"high"});}let x=new Set,_=h.filter(P=>x.has(P.gate)?false:(x.add(P.gate),true)),R=m==="concise"?{suggestions:_.map(P=>({gate:P.gate,confidence:P.confidence}))}:{route:p,method:y,suggestions:_,availableGates:b.map(P=>({symbol:P.symbol,description:P.description})),note:C?"Resource ID routes should verify the user owns/has access to the specific resource.":"These are suggestions based on route patterns. Review your portal.yaml for exact requirements."},I=JSON.stringify(R,null,2);o(I.length,o$1);try{n$1(c.rootDir,{type:"gate-checked",source:"mcp-tool-call",tool:"paradigm_gates_for_route",symbols:_.map(P=>P.gate),context:`Gate check for ${y} ${p}`});}catch{}return {content:[{type:"text",text:I}]}}case "paradigm_plugin_check":{let{runPluginUpdateCheck:p}=await import('./plugin-update-checker-M7PW434O.js'),m=await p(),f=m.filter(v=>v.hasRemoteUpdate||v.hasCacheStale);if(f.length===0){let v=m.length===0?"No Claude Code plugins found in ~/.claude/plugins/marketplaces/.":"All installed plugins are up to date.";return o(v.length,o$1),{content:[{type:"text",text:v}]}}let y=[`Plugin updates available:
446
446
  `],b=[];for(let v of f)v.hasRemoteUpdate?(y.push(` ${v.plugin} (${v.repo}): remote has newer commits`),b.push(`git -C ${v.marketplacePath} pull origin main`)):v.hasCacheStale&&y.push(` ${v.plugin} (${v.repo}): ${v.installedVersion} \u2192 ${v.localVersion} (restart needed)`);b.length>0?(y.push(`
447
447
  Update command:
448
448
  ${b.join(` && \\
449
449
  `)}`),y.push(`
450
450
  After running, restart the session to apply updates.`)):y.push(`
451
451
  Restart the session to apply cached updates.`);let h=y.join(`
452
- `);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let y=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(y.length,o$1),{content:[{type:"text",text:y}]}}let{rebuildStaticFiles:p}=await import('./reindex-F7EV3Z34.js'),m=[];for(let y of c.workspace.config.members){let b=q.resolve(q.dirname(c.workspace.workspacePath),y.path);try{let h=await p(b);m.push({name:y.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:y.name,symbolCount:0,status:`error: ${h.message}`});}}let f=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((y,b)=>y+b.symbolCount,0)},null,2);return o(f.length,o$1),v$1.clear(),{content:[{type:"text",text:f}]}}case "paradigm_tool_activate":{let p=a.feature,m=i$1.activateAdvanced(p);if(m){let h=JSON.stringify({action:"tool_activate",feature:p,status:"activated",toolsAdded:m.map(v=>v.name),note:`Advanced module "${p}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let f=i$1.getRegistryInfo(),y=f.activeFeatures.includes(p),b=JSON.stringify({action:"tool_activate",feature:p,status:y?"already_active":"not_found",note:y?`Module "${p}" is already active (auto-detected or core tier).`:`Module "${p}" not found. Available advanced modules: ${f.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:f.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let p=await i$1.dispatch(o$1,a,c);if(p&&p.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(p.text.length,o$1),Lu(o$1,a,c.rootDir),{content:[{type:"text",text:p.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||u){let p=g.content?.[0];if(p&&typeof p=="object"&&"text"in p&&typeof p.text=="string"){let m=[u,d].filter(Boolean).join(`
452
+ `);return o(h.length,o$1),{content:[{type:"text",text:h}]}}case "paradigm_workspace_reindex":{if(!c.workspace){let y=JSON.stringify({error:"No workspace configured",suggestion:'Add a "workspace" field to .paradigm/config.yaml pointing to your .paradigm-workspace file, then run `paradigm workspace init` to create one.'},null,2);return o(y.length,o$1),{content:[{type:"text",text:y}]}}let{rebuildStaticFiles:p}=await import('./reindex-O3WUCEE2.js'),m=[];for(let y of c.workspace.config.members){let b=q.resolve(q.dirname(c.workspace.workspacePath),y.path);try{let h=await p(b);m.push({name:y.name,symbolCount:h.symbolCount,status:"ok"});}catch(h){m.push({name:y.name,symbolCount:0,status:`error: ${h.message}`});}}let f=JSON.stringify({action:"workspace_reindex",workspace:c.workspace.config.name,members:m,totalSymbols:m.reduce((y,b)=>y+b.symbolCount,0)},null,2);return o(f.length,o$1),v$1.clear(),{content:[{type:"text",text:f}]}}case "paradigm_tool_activate":{let p=a.feature,m=i$1.activateAdvanced(p);if(m){let h=JSON.stringify({action:"tool_activate",feature:p,status:"activated",toolsAdded:m.map(v=>v.name),note:`Advanced module "${p}" activated for this session. ${m.length} tool(s) now available.`},null,2);return o(h.length,o$1),{content:[{type:"text",text:h}]}}let f=i$1.getRegistryInfo(),y=f.activeFeatures.includes(p),b=JSON.stringify({action:"tool_activate",feature:p,status:y?"already_active":"not_found",note:y?`Module "${p}" is already active (auto-detected or core tier).`:`Module "${p}" not found. Available advanced modules: ${f.availableAdvanced.join(", ")||"(none)"}`,availableAdvanced:f.availableAdvanced},null,2);return o(b.length,o$1),{content:[{type:"text",text:b}]}}default:{let p=await i$1.dispatch(o$1,a,c);if(p&&p.handled)return o$1.startsWith("paradigm_context_")||o$1.startsWith("paradigm_session_")||o$1==="paradigm_handoff_prepare"||o(p.text.length,o$1),Lu(o$1,a,c.rootDir),{content:[{type:"text",text:p.text}]};throw new Error(`Unknown tool: ${o$1}`)}}})();if(d||u){let p=g.content?.[0];if(p&&typeof p=="object"&&"text"in p&&typeof p.text=="string"){let m=[u,d].filter(Boolean).join(`
453
453
 
454
454
  `);p.text=m+`
455
455