@a-company/paradigm 5.35.1 → 5.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/dist/{accept-orchestration-MIRBLRUJ.js → accept-orchestration-36AP7HTX.js} +1 -1
  2. package/dist/{add-P76GEMGF.js → add-FGKNJS3F.js} +1 -1
  3. package/dist/{agent-X6I2YWOB.js → agent-E7LDKJ4O.js} +1 -1
  4. package/dist/{agent-loader-5255KNM7.js → agent-loader-2HXKVL6J.js} +1 -1
  5. package/dist/{agent-loader-A5FMBAFJ.js → agent-loader-XS6LIMUG.js} +1 -1
  6. package/dist/{agent-state-KSQ3S7OB.js → agent-state-L7LCPRC3.js} +1 -1
  7. package/dist/{agents-suggest-HYTFMQD3.js → agents-suggest-Y5D6AALG.js} +1 -1
  8. package/dist/{aggregate-W66DM3GA.js → aggregate-OZJRRAQR.js} +1 -1
  9. package/dist/{ambient-BKX77DDQ.js → ambient-4NSPAQDJ.js} +9 -9
  10. package/dist/{assess-UFPYEJKP.js → assess-AMPVSWK7.js} +1 -1
  11. package/dist/{auto-RHJXOZFL.js → auto-A7VUHCUC.js} +1 -1
  12. package/dist/{beacon-5QVYV5DF.js → beacon-YBLUUTYY.js} +1 -1
  13. package/dist/{calibration-OLJYB5HN.js → calibration-FQ4YVOE4.js} +1 -1
  14. package/dist/{check-THVGY4R5.js → check-46QL3KMQ.js} +1 -1
  15. package/dist/{chunk-AGSUX2GJ.js → chunk-3OMJI5TT.js} +2 -2
  16. package/dist/chunk-3QMRDN65.js +29 -0
  17. package/dist/{chunk-QNZEG7IT.js → chunk-3XGNXXCT.js} +1 -1
  18. package/dist/{chunk-VG7FN2TU.js → chunk-4W5TBL3O.js} +1 -1
  19. package/dist/{chunk-UDUHSHO4.js → chunk-5YHR77AL.js} +1 -1
  20. package/dist/chunk-6PP2RPIZ.js +3 -0
  21. package/dist/{chunk-VCKKJDLP.js → chunk-6QKCUEEY.js} +1 -1
  22. package/dist/{chunk-JBDMCRPP.js → chunk-77WX6HGV.js} +1 -1
  23. package/dist/{chunk-A7KFOJ2F.js → chunk-7PB7AXQE.js} +1 -1
  24. package/dist/chunk-7SGNNVE5.js +3 -0
  25. package/dist/{chunk-WS2N27RX.js → chunk-7YTAA6XA.js} +1 -1
  26. package/dist/chunk-BCOPNVPY.js +11 -0
  27. package/dist/chunk-BRHQJLTG.js +2 -0
  28. package/dist/{chunk-W5IWDW4Y.js → chunk-DG3VCY43.js} +1 -1
  29. package/dist/{chunk-HMQ5BHP2.js → chunk-DOCDDDTD.js} +10 -10
  30. package/dist/chunk-DSYEGRQ2.js +3 -0
  31. package/dist/chunk-EMMMBAID.js +2 -0
  32. package/dist/chunk-F5BSUC2L.js +3 -0
  33. package/dist/chunk-IW5K3RNR.js +8 -0
  34. package/dist/chunk-JIF7OSGH.js +8 -0
  35. package/dist/{chunk-HPAHK4AJ.js → chunk-JUOOVKK6.js} +1 -1
  36. package/dist/chunk-NFQLONFY.js +3 -0
  37. package/dist/chunk-OVDYPOHR.js +2 -0
  38. package/dist/{chunk-33LKBMVK.js → chunk-RLJ5K3J5.js} +1 -1
  39. package/dist/{chunk-HXGYVS2N.js → chunk-RN35IVA2.js} +1 -1
  40. package/dist/{chunk-ODVKPZZ4.js → chunk-W6WVJLHO.js} +1 -1
  41. package/dist/chunk-X54WXWCX.js +111 -0
  42. package/dist/chunk-XHJ27CER.js +2 -0
  43. package/dist/{chunk-32RBX5YV.js → chunk-XNB4TZTD.js} +1 -1
  44. package/dist/chunk-YG5G5GEQ.js +456 -0
  45. package/dist/chunk-Z72SDTBJ.js +3 -0
  46. package/dist/{claude-4LR3LJQZ.js → claude-OX54QSLC.js} +1 -1
  47. package/dist/{claude-cli-UP6HGH7C.js → claude-cli-FHLJQVJC.js} +1 -1
  48. package/dist/{claude-code-RLJ4GX77.js → claude-code-GVGU3A3B.js} +1 -1
  49. package/dist/{claude-code-teams-R37HJY3Y.js → claude-code-teams-ZRHPTGPP.js} +1 -1
  50. package/dist/{compliance-NJSBCY6F.js → compliance-PHSPVYK2.js} +3 -3
  51. package/dist/{compliance-health-JNP3P35P.js → compliance-health-HCZTJDN7.js} +1 -1
  52. package/dist/{conductor-Y5IXELTL.js → conductor-LYBMM66Z.js} +1 -1
  53. package/dist/{config-schema-GUQY2QN7.js → config-schema-URJW6UZH.js} +1 -1
  54. package/dist/{constellation-CG7C4WFE.js → constellation-PX3ZKMWQ.js} +1 -1
  55. package/dist/{context-audit-XRPT3OU2.js → context-audit-APFKELFT.js} +2 -2
  56. package/dist/{cost-IDNVMAEV.js → cost-B5SAHPOJ.js} +1 -1
  57. package/dist/{cost-PK4KIF7R.js → cost-MMWUDGZC.js} +1 -1
  58. package/dist/{cursor-cli-QKF7Z6M2.js → cursor-cli-Q2HLQ5TE.js} +1 -1
  59. package/dist/{cursorrules-U5O4G5T4.js → cursorrules-3BW6K6D5.js} +1 -1
  60. package/dist/{decision-loader-2XPZE4EZ.js → decision-loader-4KMQVAXZ.js} +1 -1
  61. package/dist/{delete-P5VULXR4.js → delete-7PQZUERZ.js} +1 -1
  62. package/dist/{diff-QHQWLM3L.js → diff-F2HUO2H3.js} +1 -1
  63. package/dist/{discipline-H7LDI6NT.js → discipline-ARFFIXQL.js} +1 -1
  64. package/dist/{dist-W3XCATBJ.js → dist-5IUWRFG6.js} +1 -1
  65. package/dist/{dist-KGRCLBJP-2QAPFYNF.js → dist-KGRCLBJP-R5CCPPXN.js} +1 -1
  66. package/dist/{dist-3ZCH25SG.js → dist-MRZDZ5SX.js} +1 -1
  67. package/dist/{dist-VGFSP3XM.js → dist-OKM6BXTH.js} +1 -1
  68. package/dist/{dist-VXCZWVVJ.js → dist-VWC6FA46.js} +1 -1
  69. package/dist/dist-YUXXIXB3.js +3 -0
  70. package/dist/{docs-EDQ2STFK.js → docs-6WOQILZS.js} +1 -1
  71. package/dist/{docs-5BX2YWYK.js → docs-BI2DO7B2.js} +2 -2
  72. package/dist/doctor-JLTCBMS4.js +2 -0
  73. package/dist/{drift-ILZE5BFJ.js → drift-6QPDKKUO.js} +1 -1
  74. package/dist/{echo-UPTQUEDU.js → echo-3JJDKCNF.js} +1 -1
  75. package/dist/{edit-GUU3HBVW.js → edit-PLCGL5OV.js} +1 -1
  76. package/dist/{enforcement-BEGPQIUN.js → enforcement-5MHSQAXE.js} +1 -1
  77. package/dist/{enforcement-46XWPNSA.js → enforcement-IWABOHMY.js} +1 -1
  78. package/dist/{event-Y3VXC2RV.js → event-5J3GBWKT.js} +1 -1
  79. package/dist/{explain-files-3GPZUETV.js → explain-files-LPHTJL4N.js} +1 -1
  80. package/dist/{export-CV5KCTPS.js → export-NXUFTFPW.js} +1 -1
  81. package/dist/{flow-POQP27WA.js → flow-IT2IVXXT.js} +1 -1
  82. package/dist/{gap-narrator-NTXLUI7I.js → gap-narrator-DVXPWNFN.js} +1 -1
  83. package/dist/{global-C44FW4G2.js → global-J2VTYKCC.js} +1 -1
  84. package/dist/{graduate-3BBSC27A.js → graduate-N2HF4JT6.js} +1 -1
  85. package/dist/graph-VLMP6DW2.js +2 -0
  86. package/dist/{graph-server-COZR5C3Z.js → graph-server-TBHHBFOM.js} +1 -1
  87. package/dist/{habits-GICVMTJL.js → habits-JTMWGVPH.js} +3 -3
  88. package/dist/{history-UW454SDP.js → history-FHS7EC3Z.js} +1 -1
  89. package/dist/{hooks-BNWRGACA.js → hooks-BL6CXRVK.js} +1 -1
  90. package/dist/index.js +9 -9
  91. package/dist/init-ZS7RAR7L.js +2 -0
  92. package/dist/{integrity-UYDOOJDP.js → integrity-UBMZCB77.js} +1 -1
  93. package/dist/{integrity-checker-DHGMZQDG.js → integrity-checker-VSR3ITBL.js} +1 -1
  94. package/dist/journal-loader-EELDB4P2.js +2 -0
  95. package/dist/{lint-IGKE6UPS.js → lint-KQQ2RMSJ.js} +1 -1
  96. package/dist/{list-5IUGP3ZB.js → list-37UCWCOQ.js} +1 -1
  97. package/dist/{list-YKIQNKGB.js → list-6WY4CFUR.js} +1 -1
  98. package/dist/lore-loader-CP5RUJ4A.js +2 -0
  99. package/dist/{lore-loader-XY5MZRR2.js → lore-loader-PBUDKXAJ.js} +1 -1
  100. package/dist/{lore-server-FC2GMDLT.js → lore-server-A3KKZLSY.js} +1 -1
  101. package/dist/{manual-RXSPSFLL.js → manual-HKI6OXB4.js} +1 -1
  102. package/dist/mcp.js +17 -449
  103. package/dist/{migrate-YQG2FG3J.js → migrate-W3KCXLDS.js} +2 -2
  104. package/dist/{migrate-assessments-GEI5WMI2.js → migrate-assessments-D2TOBJ5V.js} +1 -1
  105. package/dist/{model-discovery-HMB3YI4L.js → model-discovery-TWX4A4YD.js} +1 -1
  106. package/dist/{nomination-engine-6VTQ4OVW.js → nomination-engine-A24774W4.js} +1 -1
  107. package/dist/{notebook-PE3JSYZI.js → notebook-LXJ2LHUA.js} +1 -1
  108. package/dist/notebook-loader-CF52PNZC.js +2 -0
  109. package/dist/{orchestrate-7CJWHLBA.js → orchestrate-WFCNV2II.js} +1 -1
  110. package/dist/{peers-P2KXU7ZK.js → peers-7TPZTKH7.js} +1 -1
  111. package/dist/{persona-STQWZH5P.js → persona-UGTCFEGT.js} +1 -1
  112. package/dist/{pipeline-MZUITRVN.js → pipeline-7PZ6ILWX.js} +1 -1
  113. package/dist/{platform-server-G6MJIAJS.js → platform-server-YIBX4YDJ.js} +2 -2
  114. package/dist/{plugin-update-checker-M7PW434O.js → plugin-update-checker-2EM4K45U.js} +1 -1
  115. package/dist/{portal-check-Z3OCQEQR.js → portal-check-YSDJRZUR.js} +1 -1
  116. package/dist/{portal-compliance-4MG5F2GI.js → portal-compliance-OBPK2IR5.js} +1 -1
  117. package/dist/{probe-5L5BQDGE.js → probe-WKXR3IN4.js} +1 -1
  118. package/dist/{project-type-EUCFKEAZ.js → project-type-MRBJAKC7.js} +1 -1
  119. package/dist/{promote-NJQDZBZA.js → promote-VHBA56KW.js} +2 -2
  120. package/dist/{providers-TBPOE4DI.js → providers-RX7SBLHZ.js} +1 -1
  121. package/dist/{quiz-FE5UGAY2.js → quiz-3SQNPRJ3.js} +1 -1
  122. package/dist/{record-YXPB34MY.js → record-7QJPZZP7.js} +1 -1
  123. package/dist/registry-LR5QACRK.js +20 -0
  124. package/dist/reindex-F7EV3Z34.js +2 -0
  125. package/dist/{remember-MJRNTXYS.js → remember-SFGBTTEE.js} +1 -1
  126. package/dist/{retag-N5XF3KXP.js → retag-GFXUYP7S.js} +1 -1
  127. package/dist/{review-6UAH6V3R.js → review-6KKZWV3A.js} +1 -1
  128. package/dist/{review-77QI6VOC.js → review-GEBSYOZB.js} +1 -1
  129. package/dist/{ripple-ZGDITCGB.js → ripple-4F5ZCXS4.js} +1 -1
  130. package/dist/{roster-HV5KYUOI.js → roster-RI3UC2YI.js} +1 -1
  131. package/dist/scaffold-WA4L2K7J.js +18 -0
  132. package/dist/{scopes-commands-3V5G6NYV.js → scopes-commands-5FFIUDRC.js} +1 -1
  133. package/dist/{sentinel-HYAZ3CO5.js → sentinel-37ZEEWT7.js} +2 -2
  134. package/dist/{sentinel-bridge-VR357PKL.js → sentinel-bridge-EZGFRVFH.js} +1 -1
  135. package/dist/{serve-L52ZUTU6.js → serve-2BXDL35A.js} +2 -2
  136. package/dist/{serve-ZJ3EXVA5.js → serve-2LSTQFFQ.js} +2 -2
  137. package/dist/{serve-OY6XYL7F.js → serve-5JME5QEM.js} +2 -2
  138. package/dist/{server-4YNUIK4W.js → server-AIXFROYL.js} +1 -1
  139. package/dist/{server-2MNROHF6.js → server-XLHIYDTZ.js} +1 -1
  140. package/dist/session-tracker-VSFRNFRL.js +2 -0
  141. package/dist/{session-work-log-SLAPEP3M.js → session-work-log-6GKGUQ5C.js} +1 -1
  142. package/dist/{session-work-log-5UJTJJ22.js → session-work-log-UYMIWWOX.js} +1 -1
  143. package/dist/{setup-KPIMRZ4Q.js → setup-F2N4LUR7.js} +1 -1
  144. package/dist/{setup-3F5IK7MO.js → setup-ZM4JFV5D.js} +2 -2
  145. package/dist/{shift-EU22H7GG.js → shift-DDYVQJ75.js} +5 -5
  146. package/dist/{show-PJ5LFLIL.js → show-CZLVYLM5.js} +1 -1
  147. package/dist/{show-BOAVWZPZ.js → show-RFOIR2GQ.js} +1 -1
  148. package/dist/{snapshot-L2G56RPL.js → snapshot-6N564OUJ.js} +1 -1
  149. package/dist/{spawn-7TCAMD6H.js → spawn-HYARN3RL.js} +1 -1
  150. package/dist/{status-A37ECYNJ.js → status-CUG3PKGC.js} +1 -1
  151. package/dist/{status-77M3SDIF.js → status-WBJ6D7BD.js} +1 -1
  152. package/dist/{summary-ZJLQ6KHB.js → summary-2AM4QVPW.js} +1 -1
  153. package/dist/{sweep-HU74OPVW.js → sweep-WHDT7ENV.js} +1 -1
  154. package/dist/{switch-CTW4PDGI.js → switch-HBGIFNF6.js} +1 -1
  155. package/dist/{symphony-IS5TYPXY.js → symphony-CWKKMFAS.js} +25 -25
  156. package/dist/symphony-VTHVTE57.js +2 -0
  157. package/dist/symphony-loader-RYFZOQJS.js +2 -0
  158. package/dist/{symphony-peers-X5NGWXFP.js → symphony-peers-ISJPKX7W.js} +1 -1
  159. package/dist/{symphony-peers-U4KHMKGI.js → symphony-peers-LWBUQ3T4.js} +1 -1
  160. package/dist/symphony-relay-L3BY6RGM.js +3 -0
  161. package/dist/sync-WIFD7UCL.js +2 -0
  162. package/dist/{sync-llms-HL5PPW3M.js → sync-llms-MZ3RQWFX.js} +1 -1
  163. package/dist/{task-loader-NZFDTUQ5.js → task-loader-EU7JLTR3.js} +1 -1
  164. package/dist/team-C3PWO7XL.js +2 -0
  165. package/dist/{test-BQJMS4Y2.js → test-6MUL4EXS.js} +1 -1
  166. package/dist/{thread-HFXK65D4.js → thread-K6UHDIUW.js} +1 -1
  167. package/dist/{timeline-K3ZFKJ3R.js → timeline-S26CQWHT.js} +1 -1
  168. package/dist/tools-4WKLLDFU.js +2 -0
  169. package/dist/{triage-FCWOZASE.js → triage-YF6WYZY4.js} +1 -1
  170. package/dist/{tutorial-UC6YQMNN.js → tutorial-UEBX7Z2G.js} +1 -1
  171. package/dist/{university-FJ7OCOA3.js → university-UMT7PAKE.js} +1 -1
  172. package/dist/university-content/courses/para-201.json +5 -5
  173. package/dist/university-content/courses/para-301.json +10 -10
  174. package/dist/university-content/courses/para-401.json +3 -3
  175. package/dist/university-content/courses/para-501.json +5 -5
  176. package/dist/university-content/courses/para-601.json +1 -1
  177. package/dist/university-content/plsat/v2.0.json +7 -7
  178. package/dist/university-content/plsat/v3.0.json +9 -9
  179. package/dist/university-content/reference.json +4 -4
  180. package/dist/{upgrade-B4IOLZYK.js → upgrade-USW7YJEX.js} +1 -1
  181. package/dist/{validate-LSCDOLBO.js → validate-2PZTNYSS.js} +1 -1
  182. package/dist/{validate-VZXTJHGO.js → validate-KW3YFGTV.js} +1 -1
  183. package/dist/{validate-C6SMKGYD.js → validate-VZGBVTPM.js} +1 -1
  184. package/dist/{watch-LRM5XD46.js → watch-HL3ZOALL.js} +1 -1
  185. package/dist/{watch-PZCCUP6K.js → watch-KQU3S7KE.js} +1 -1
  186. package/dist/{wisdom-XZ3QKPNP.js → wisdom-UU7HOE3M.js} +1 -1
  187. package/dist/{work-log-loader-DL5GZ2BQ.js → work-log-loader-J27XSFCE.js} +1 -1
  188. package/dist/workspace-CE6LNXVI.js +2 -0
  189. package/package.json +5 -1
  190. package/templates/paradigm/specs/context-tracking.md +4 -4
  191. package/dist/chunk-2Q7RGCJH.js +0 -3
  192. package/dist/chunk-5TAVYPOV.js +0 -2
  193. package/dist/chunk-73R63P7K.js +0 -2
  194. package/dist/chunk-76JPOBDH.js +0 -29
  195. package/dist/chunk-C7ZCCKJT.js +0 -3
  196. package/dist/chunk-CUOEZAVL.js +0 -8
  197. package/dist/chunk-LKFBDUCV.js +0 -11
  198. package/dist/chunk-QGZRM6ZB.js +0 -2
  199. package/dist/chunk-S7K7UPXL.js +0 -3
  200. package/dist/chunk-UHQLYIRI.js +0 -3
  201. package/dist/chunk-USGKKAPL.js +0 -111
  202. package/dist/chunk-VZLGBGU3.js +0 -8
  203. package/dist/doctor-R4UGMR5N.js +0 -2
  204. package/dist/graph-CNDE5TAT.js +0 -2
  205. package/dist/init-24MAQJFM.js +0 -2
  206. package/dist/journal-loader-GLH7XFTK.js +0 -2
  207. package/dist/lore-loader-RVQI5GXL.js +0 -2
  208. package/dist/notebook-loader-CENTDDUJ.js +0 -2
  209. package/dist/reindex-HWRA7KDI.js +0 -2
  210. package/dist/session-tracker-WSTRV7UP.js +0 -2
  211. package/dist/symphony-43N4R6C2.js +0 -2
  212. package/dist/symphony-loader-XJT43FOS.js +0 -2
  213. package/dist/symphony-relay-CIMRXQHI.js +0 -3
  214. package/dist/sync-QRDSFETO.js +0 -2
  215. package/dist/team-WIJVWLII.js +0 -2
  216. package/dist/workspace-2ODL5WLY.js +0 -2
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$2,a}from'./chunk-F5BSUC2L.js';import {b as b$1}from'./chunk-XHJ27CER.js';import*as l from'fs';import*as g from'path';import*as R from'os';import*as C from'crypto';import*as h from'js-yaml';var j,T,$,k=b$1(()=>{j={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},T={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};});function x(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=L)return t;let i=Math.pow(.5,(s-L)/q);return t*i}function W(t){let e=g.join(t,N);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function Z(t,e){let o=W(e);return o?o.includes(t):true}function ee(t,e){let o=g.join(t,N),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function te(){if(!l.existsSync(b))return [];try{return l.readdirSync(b).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function w(t,e){let o=g.join(t,v,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=A(n);return n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e}),n}}catch{}let s=g.join(b,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=O(n,f),a$1=A(r);return r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:e}),r}catch{}if(n){let c=A(n);n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e});}return n}catch{}return null}function H(t,e){let o=I(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function ne(t,e){let o=w(t,e);return o||(H(t,e)[0]??null)}function I(t){let e=new Map;if(l.existsSync(b))try{let s=l.readdirSync(b).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(b,i),"utf-8"),c=h.load(n);if(c?.id){let f=A(c);c.__integrityStatus=f,f==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,v);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=O(f,c),a$1=A(r);r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:r.id}),e.set(c.id,r);}else {let r=A(c);c.__integrityStatus=r,r==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function S(t,e,o,s){let i=o==="global"?b:g.join(s||process.cwd(),v);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=F(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function Y(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:j[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};j[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),T[t]&&(s.attention={...T[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=S(t,s,i,e.rootDir);return {profile:s,filePath:n}}function se(t,e){let o=I(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>x(n.entry.confidence,n.entry.lastTouch)-x(i.entry.confidence,i.entry.lastTouch))}function re(t,e,o){let s=w(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-_)*p.confidence+_*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=z(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,v,`${e}${y}`),r=l.existsSync(f)?"project":"global";return S(e,s,r,t),true}function ie(t,e,o){let s=w(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-_)*a.confidence+_*n);}let c=g.join(t,v,`${e}${y}`),f=l.existsSync(c)?"project":"global";return S(e,s,f,t),true}function oe(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>x(i.confidence,i.lastTouch)-x(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function ae(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>x(a.confidence,a.lastTouch)-x(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-x(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>U?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
+ `)}async function ce(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-CP5RUJ4A.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||Y(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(D=>D.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=J(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function G(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function B(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function le(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function pe(t,e){return e.type==="path"?G(t,e.path,e.mode):B(t,e.name)}function F(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return C.createHash("sha256").update(e).digest("hex")}function J(t){return t.integrityHash?F(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function O(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function z(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}var b,v,y,N,_,q,L,U,V=b$1(()=>{b$2();k();b=g.join(R.homedir(),".paradigm","agents"),v=".paradigm/agents",y=".agent",N=".paradigm/roster.yaml",_=.3,q=60,L=7,U=.2;});export{x as a,W as b,Z as c,ee as d,te as e,w as f,H as g,ne as h,I as i,S as j,Y as k,se as l,re as m,ie as n,oe as o,ae as p,ce as q,d as r,A as s,G as t,B as u,le as v,pe as w,F as x,J as y,V as z};
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {a,e,b,d}from'./chunk-WR6D3SC6.js';import _ from'chalk';import*as g from'fs';import*as $ from'path';async function q(c,l){let o=c||process.cwd(),e$1=parseInt(l.port||"3841",10),h=l.open!==false;a(_.cyan(`
3
3
  Starting Symbol Graph...
4
- `));try{let{startGraphServer:a$1}=await import('./graph-server-COZR5C3Z.js');e(`Project: ${o}`),e(`Port: ${e$1}`),a(""),await a$1({port:e$1,projectDir:o,open:h}),b(`Symbol Graph is running at http://localhost:${e$1}`),e(`
4
+ `));try{let{startGraphServer:a$1}=await import('./graph-server-TBHHBFOM.js');e(`Project: ${o}`),e(`Port: ${e$1}`),a(""),await a$1({port:e$1,projectDir:o,open:h}),b(`Symbol Graph is running at http://localhost:${e$1}`),e(`
5
5
  Press Ctrl+C to stop
6
6
  `),await new Promise(()=>{});}catch(a){a.code==="EADDRINUSE"?(d(`Port ${e$1} is already in use.`),e(`Try: paradigm graph --port ${e$1+1}
7
7
  `)):d(`Failed to start Symbol Graph: ${a}`),process.exit(1);}}var F=".paradigm/graphs",N={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},P=200,j=60,x=20,I=40,R=50,B=60,L={components:"component",flows:"flow",gates:"gate",signals:"signal",aspects:"aspect"};function T(c){let l=$.join(c,".paradigm","scan-index.json");if(!g.existsSync(l))return [];let o=JSON.parse(g.readFileSync(l,"utf8")),e=[];for(let[h,a]of Object.entries(L)){let m=o[h];if(!(!m||typeof m!="object"))for(let[p,f]of Object.entries(m)){let d=f;e.push({id:p,name:p,category:a,prefix:N[a]||"#",description:d.description,path:d.path});}}return e}function A(c,l){let o=c.replace(/^[#$^!~]/,"");return l.find(e=>e.id===o||e.name===o||e.id===c||e.name===c)}function H(c,l,o,e,h="Generated Graph"){let a=T(c),m=l&&l.length>0?l.map(t=>A(t,a)).filter(Boolean):a,p=[],f=[],d=new Map,b=new Set,G=0;if(o&&o.length>0)for(let t of o){let i=`group-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;d.set(t.label,i);let n=t.symbols.map(y=>A(y,m)).filter(Boolean),r=Math.max(Math.ceil(Math.sqrt(n.length)),1),M=Math.max(Math.ceil(n.length/r),1);for(let y=0;y<n.length;y++){let w=n[y],v=y%r,C=Math.floor(y/r);p.push({id:`sym-${w.id}`,type:"symbolNode",position:{x:I+v*(P+x),y:R+I+C*(j+x)},parentId:i,data:{type:"symbol",symbol:w,label:`${N[w.category]||"#"}${w.name}`}}),b.add(w.id);}let D=I*2+r*P+(r-1)*x,k=R+I*2+M*j+(M-1)*x;p.unshift({id:i,type:"groupNode",position:{x:G,y:0},style:{width:D,height:k},data:{type:"group",label:t.label}}),G+=D+B;}let s=m.filter(t=>!b.has(t.id));if(s.length>0){let t=o&&o.length>0?400:0,i=Math.max(Math.ceil(Math.sqrt(s.length)),1);for(let n=0;n<s.length;n++){let r=s[n],M=n%i,D=Math.floor(n/i);p.push({id:`sym-${r.id}`,type:"symbolNode",position:{x:M*(P+x),y:t+D*(j+x)},data:{type:"symbol",symbol:r,label:`${N[r.category]||"#"}${r.name}`}});}}if(e&&e.length>0)for(let t of e){let i=d.get(t.source),n=d.get(t.target);i&&n&&f.push({id:`e-${i}-${n}`,source:i,target:n,type:"default",label:t.label,data:{label:t.label}});}return {version:"1.0",name:h,projectId:$.basename(c),lastModified:new Date().toISOString(),nodes:p,edges:f}}async function K(c,l,o){let e$1=l||process.cwd(),h=c.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");try{let a=o.symbols?o.symbols.split(",").map(s=>s.trim()):void 0,m=o.group?.map(s=>{let t=s.indexOf(":");return t===-1&&(d(`Invalid group format: "${s}". Expected "Label:#sym1,#sym2"`),process.exit(1)),{label:s.slice(0,t),symbols:s.slice(t+1).split(",").map(i=>i.trim())}}),p=o.link?.map(s=>{let t=s.indexOf(">");t===-1&&(d(`Invalid link format: "${s}". Expected "Source>Target:label"`),process.exit(1));let i=s.slice(0,t),n=s.slice(t+1),r=n.indexOf(":");return {source:i,target:r===-1?n:n.slice(0,r),label:r===-1?void 0:n.slice(r+1)}}),f=H(e$1,a,m,p,c),d$1=JSON.stringify(f,null,2),b$1=$.join(e$1,F);g.existsSync(b$1)||g.mkdirSync(b$1,{recursive:!0});let G=$.join(b$1,`${h}.graph.json`);g.writeFileSync(G,d$1,"utf8"),b(`Graph saved to ${G}`),e(`${f.nodes.length} nodes, ${f.edges.length} edges, ${(d$1.length/1024).toFixed(1)} KB`),e(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,b}from'./chunk-4TXOVRWD.js';import {m}from'./chunk-T6IDXUUA.js';import {b as b$1}from'./chunk-VCKKJDLP.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},z={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},G={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
2
+ import {a,b}from'./chunk-4TXOVRWD.js';import {b as b$1}from'./chunk-6QKCUEEY.js';import {m}from'./chunk-T6IDXUUA.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},z={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},G={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
3
3
  `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).filter(e=>e.endsWith("/")||e.includes("*")||["node_modules","dist","build",".cache"].some(c=>e.includes(c))).slice(0,20);for(let e of s)t.always.includes(e)||t.always.push(e);}catch{}return t}function U(o,t,n){let r={},s=new Map;for(let e of t){let c=p.dirname(e);s.set(e,c);}for(let e of o){let i=`${W(e.type)}${e.id}`;if(e.path)r[i]=e.path;else if(e.directory)r[i]=e.directory;else {let f=t.find(a=>{let l=p.dirname(a),y=e.id.toLowerCase();return l.toLowerCase().includes(y)});f&&(r[i]=p.dirname(f)+"/");}}return r}function W(o){switch(o){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";default:return "@"}}function P(o){return $.load(o)}async function ce(o,t){let n=o?p.resolve(o):process.cwd(),r=p.basename(n),s=q(),e=p.join(n,".paradigm"),c=u.existsSync(e)&&u.statSync(e).isFile(),i;t.output?i=p.resolve(t.output):c?i=p.join(n,".paradigm-scan-index.json"):(i=p.join(n,".paradigm","scan-index.json"),u.existsSync(p.dirname(i))||u.mkdirSync(p.dirname(i),{recursive:true})),t.quiet||console.log(g.blue(`
4
4
  \u{1F52D} Generating Paradigm Scan Index
5
5
  `));let f,a$1,l,y=[p.join(n,".paradigm"),p.join(n,".paradigm","config.yaml")];for(let h of y)if(u.existsSync(h)&&u.statSync(h).isFile())try{let m=u.readFileSync(h,"utf8"),F=P(m);f=F.scan,a$1=F.graph,l=F.context?.tiers;break}catch{}s.start("Aggregating symbols from purpose and portal files...");let d;try{d=await m(n);}catch(h){s.fail(g.red("Failed to aggregate symbols")),console.error(g.gray(h.message)),process.exit(1);}if(s.succeed(`Found ${d.symbols.length} symbols`),!t.quiet){let h={components:d.symbols.filter(m=>m.type==="component").length,flows:d.symbols.filter(m=>m.type==="flow").length,gates:d.symbols.filter(m=>m.type==="gate").length,signals:d.symbols.filter(m=>m.type==="signal").length,aspects:d.symbols.filter(m=>m.type==="aspect").length};console.log(g.gray(" Breakdown:"));for(let[m,S]of Object.entries(h))S>0&&console.log(g.gray(` ${m}: ${S}`));console.log();}s.start("Generating scan index...");let b$2=a({symbols:d.symbols,purposeFiles:d.purposeFiles,portalFiles:d.portalFiles},{projectName:r,visualTagMappings:f?.visualTagMappings,screenDefinitions:f?.screens});K(b$2,{hot:l?.["hot-threshold"],warm:l?.["warm-threshold"]});try{u.writeFileSync(i,b(b$2),"utf8"),s.succeed(g.green("Scan index generated"));}catch(h){s.fail(g.red("Failed to write scan index")),console.error(g.gray(h.message)),process.exit(1);}await A(n,d,{quiet:t.quiet});let j=await Y(n,d.purposeFiles,{quiet:t.quiet});if(j&&Object.keys(j.flows).length>0){let h=p.join(n,".paradigm","flow-index.json");u.writeFileSync(h,JSON.stringify(j,null,2),"utf8"),t.quiet||s.succeed(g.green(`Flow index generated (${Object.keys(j.flows).length} flows)`));}if(a$1?.["auto-generate"]!==false)try{let h=b$1(n),m=p.join(n,".paradigm","graphs");u.existsSync(m)||u.mkdirSync(m,{recursive:!0});let S=p.join(m,"auto.graph.json");u.writeFileSync(S,JSON.stringify(h,null,2),"utf8"),t.quiet||s.succeed(g.green(`Symbol graph updated (${h.nodes.length} nodes)`));}catch{t.quiet||s.warn(g.yellow("Could not auto-generate symbol graph"));}return t.quiet||(console.log(g.gray(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-UDUHSHO4.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-AO7ZSRME.js';import {a as a$2,b as b$2}from'./chunk-SHD27BQX.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {o,t,x}from'./chunk-T6IDXUUA.js';import'minimatch';import*as w from'fs';import*as C from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(f){let s=f.match(oe)||[];return [...new Set(s)]}function $(f,s){let e=f.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(f,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=f.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(f,s,e){if($(f,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(f,s){let e=ie(f),t=$(f,ee),n=$(f,te),o=$(f,se),r=$(f,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let l=Y[a],g=le(f,e),c=[...l.agents];g&&!c.includes("security")&&(c=["security",...c]);let p=ae(f,a,e),h={...l.costMultiplier};return p==="high"?(h.min*=1.2,h.max*=1.3):p==="low"&&(h.min*=.8,h.max*=.9),g&&!l.agents.includes("security")&&(h.min+=.15,h.max+=.2),{type:a,complexity:p,recommendedAgents:c,securityRequired:g,costMultiplier:h,matchedKeywords:i,symbols:e}}function B(f,s){let e=Y[s.type];return f==="security"&&s.securityRequired?"opus":e.models[f]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(f,s,e$1){let t$1=f.toLowerCase(),n=f.match(ce)||[],o=[...new Set(n)],r=o.map(d=>{let u=t(e$1,d),y=u.length>0?u[0]:null;return {symbol:d,exists:!!y,type:y?.type,description:y?.description}}),a=r.filter(d=>d.exists).map(d=>{let u=x(e$1,d.symbol),y=new Set;for(let b of u){let S=x(e$1,b.symbol);for(let O of S)O.symbol!==d.symbol&&!u.find(v=>v.symbol===O.symbol)&&y.add(O.symbol);}let k=u.length+y.size,m="low";return k>10?m="high":k>3&&(m="medium"),{symbol:d.symbol,directDependents:u.length,indirectDependents:y.size,impact:m}}),i=a$2(s),l={exists:!!i,gateCount:i?b$2(i).length:0,gates:i?b$2(i).map(d=>`^${d}`):[],routeCount:i?.routes?Object.keys(i.routes).length:0},g=de.some(d=>t$1.includes(d)),c=e(s),p=c?a$3(f,c.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],h=[];return r.some(d=>d.exists)&&h.push("ripple-analysis"),g&&h.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&h.push("gate-validation"),o.some(d=>d.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:l,taskAddsRoutes:g,suggestedAgents:p,requiredChecks:h}}function H(f,s,e,t$1){let n=[],o=a$2(e),r=o?b$2(o):[],a=o?.routes?Object.keys(o.routes):[];for(let p of f){let h=C.isAbsolute(p)?p:C.join(e,p);if(!w.existsSync(h))continue;let d;try{d=w.readFileSync(h,"utf-8");}catch{continue}for(let u of ue){u.lastIndex=0;let y;for(;(y=u.exec(d))!==null;){let k=y[2]||y[0];k&&k.startsWith("/")&&(!a.some(b=>b.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===k)&&o?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${k}" found in ${C.relative(e,h)} but not declared in portal.yaml`,file:C.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!o&&k.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${k}" found but no portal.yaml exists`,file:C.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of s)t(t$1,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of s)if(p.startsWith("^")){let h=p.slice(1);r.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}f.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${f.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let i=n.filter(p=>p.severity==="error").length,l=n.filter(p=>p.severity==="warning").length,g=4,c="pass";return i>0?c="violations":l>0&&(c="warnings"),{status:c,violations:n,summary:{totalChecks:g,passed:g-(i>0?1:0)-(l>0?1:0),warnings:l,errors:i},blocksCompletion:i>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(f,s){let e=f.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=f.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(f){let s=f.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g);a=V(s,this.rootDir,c);}catch{}if(t==="solo"){let l=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[l],r.success=l.success,l.relay&&(r.totalTokens=l.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let l=await this.runFacetedMode(s,e);r.agentsSpawned=l.results.length,r.agentResults=l.results,r.totalTokens=l.totalTokens,r.totalCost=l.totalCost,r.success=l.success,r.parallelBuilderStats=l.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:l}=await import('./dist-3ZCH25SG.js'),g=await l(this.rootDir),c=o(g),p=[],h=[];for(let u of r.agentResults)u.relay?.outputs?.artifacts&&p.push(...u.relay.outputs.artifacts.map(y=>y.path));for(let u of a.affectedSymbols)h.push(u.symbol);let d=H(p,h,this.rootDir,c);r.complianceReport={preflight:a,postflight:d},e.pmGovernance.blockOnViolations&&d.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let d=a$1(s);if(d.length>0){let u=[];u.push(`## Auto-Ripple Analysis
2
+ import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-5YHR77AL.js';import {e}from'./chunk-AO7ZSRME.js';import {a}from'./chunk-FYDRENK7.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$2,b as b$2}from'./chunk-SHD27BQX.js';import {o,t,x}from'./chunk-T6IDXUUA.js';import'minimatch';import*as w from'fs';import*as C from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(f){let s=f.match(oe)||[];return [...new Set(s)]}function $(f,s){let e=f.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(f,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=f.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(f,s,e){if($(f,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(f,s){let e=ie(f),t=$(f,ee),n=$(f,te),o=$(f,se),r=$(f,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let l=Y[a],g=le(f,e),c=[...l.agents];g&&!c.includes("security")&&(c=["security",...c]);let p=ae(f,a,e),h={...l.costMultiplier};return p==="high"?(h.min*=1.2,h.max*=1.3):p==="low"&&(h.min*=.8,h.max*=.9),g&&!l.agents.includes("security")&&(h.min+=.15,h.max+=.2),{type:a,complexity:p,recommendedAgents:c,securityRequired:g,costMultiplier:h,matchedKeywords:i,symbols:e}}function B(f,s){let e=Y[s.type];return f==="security"&&s.securityRequired?"opus":e.models[f]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(f,s,e$1){let t$1=f.toLowerCase(),n=f.match(ce)||[],o=[...new Set(n)],r=o.map(d=>{let u=t(e$1,d),y=u.length>0?u[0]:null;return {symbol:d,exists:!!y,type:y?.type,description:y?.description}}),a=r.filter(d=>d.exists).map(d=>{let u=x(e$1,d.symbol),y=new Set;for(let b of u){let S=x(e$1,b.symbol);for(let O of S)O.symbol!==d.symbol&&!u.find(v=>v.symbol===O.symbol)&&y.add(O.symbol);}let k=u.length+y.size,m="low";return k>10?m="high":k>3&&(m="medium"),{symbol:d.symbol,directDependents:u.length,indirectDependents:y.size,impact:m}}),i=a$2(s),l={exists:!!i,gateCount:i?b$2(i).length:0,gates:i?b$2(i).map(d=>`^${d}`):[],routeCount:i?.routes?Object.keys(i.routes).length:0},g=de.some(d=>t$1.includes(d)),c=e(s),p=c?a$3(f,c.agents).map(d=>({name:d.name,confidence:d.confidence,reason:d.reason})):[],h=[];return r.some(d=>d.exists)&&h.push("ripple-analysis"),g&&h.push("portal-compliance"),o.some(d=>d.startsWith("^"))&&h.push("gate-validation"),o.some(d=>d.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:l,taskAddsRoutes:g,suggestedAgents:p,requiredChecks:h}}function H(f,s,e,t$1){let n=[],o=a$2(e),r=o?b$2(o):[],a=o?.routes?Object.keys(o.routes):[];for(let p of f){let h=C.isAbsolute(p)?p:C.join(e,p);if(!w.existsSync(h))continue;let d;try{d=w.readFileSync(h,"utf-8");}catch{continue}for(let u of ue){u.lastIndex=0;let y;for(;(y=u.exec(d))!==null;){let k=y[2]||y[0];k&&k.startsWith("/")&&(!a.some(b=>b.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===k)&&o?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${k}" found in ${C.relative(e,h)} but not declared in portal.yaml`,file:C.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!o&&k.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${k}" found but no portal.yaml exists`,file:C.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let p of s)t(t$1,p).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${p}" was touched but is not registered in any .purpose file`,suggestion:`Add "${p}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let p of s)if(p.startsWith("^")){let h=p.slice(1);r.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${p}" is referenced but not declared in portal.yaml`,suggestion:`Add ${p} to portal.yaml with description and check expression.`});}f.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${f.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let i=n.filter(p=>p.severity==="error").length,l=n.filter(p=>p.severity==="warning").length,g=4,c="pass";return i>0?c="violations":l>0&&(c="warnings"),{status:c,violations:n,summary:{totalChecks:g,passed:g-(i>0?1:0)-(l>0?1:0),warnings:l,errors:i},blocksCompletion:i>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(f,s){let e=f.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=f.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(f){let s=f.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:l}=await import('./dist-MRZDZ5SX.js'),g=await l(this.rootDir),c=o(g);a=V(s,this.rootDir,c);}catch{}if(t==="solo"){let l=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[l],r.success=l.success,l.relay&&(r.totalTokens=l.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let l=await this.runFacetedMode(s,e);r.agentsSpawned=l.results.length,r.agentResults=l.results,r.totalTokens=l.totalTokens,r.totalCost=l.totalCost,r.success=l.success,r.parallelBuilderStats=l.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:l}=await import('./dist-MRZDZ5SX.js'),g=await l(this.rootDir),c=o(g),p=[],h=[];for(let u of r.agentResults)u.relay?.outputs?.artifacts&&p.push(...u.relay.outputs.artifacts.map(y=>y.path));for(let u of a.affectedSymbols)h.push(u.symbol);let d=H(p,h,this.rootDir,c);r.complianceReport={preflight:a,postflight:d},e.pmGovernance.blockOnViolations&&d.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let d=a$1(s);if(d.length>0){let u=[];u.push(`## Auto-Ripple Analysis
3
3
  `),u.push("The following symbols are affected by this refactoring:"),u.push("");for(let y of d.slice(0,5))u.push(`- **${y}**: Check dependencies before renaming/moving`);u.push(""),u.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=u.join(`
4
4
  `);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),a=[],i={input:0,output:0,total:0},l=0,g=new Map,c=true,p,h=Array.from(r.keys()).sort((d,u)=>d-u);for(let d of h){let u=r.get(d)||[];if(u.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let m=u.map(S=>S.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${d}: Spawn ${m}${u.length>1?" (parallel)":""}`)){c=false;break}}let y=u.map(async m=>{let b=e$1.agentBudgets?.[m.agent]?.maxTokens?"haiku":m.model||pe[m.agent]||"sonnet",S="";if(m.dependsOn.length>0){let R=m.dependsOn.map(I=>g.get(I)).filter(Boolean);R.length>0&&(S=R.join(`
5
5
 
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {a}from'./chunk-DSYEGRQ2.js';import*as l from'fs';import*as g from'path';import*as k from'os';import*as L from'crypto';import*as h from'js-yaml';var j={architect:{style:"deliberate",risk:"conservative",verbosity:"detailed"},builder:{style:"rapid",risk:"balanced",verbosity:"concise"},tester:{style:"methodical",risk:"conservative",verbosity:"concise"},reviewer:{style:"deliberate",risk:"conservative",verbosity:"detailed"},security:{style:"methodical",risk:"conservative",verbosity:"detailed"},documentor:{style:"methodical",risk:"conservative",verbosity:"concise"}},T={architect:{symbols:["$*","#*"],concepts:["architecture","design","pattern","refactor"],signals:[{type:"flow-modified"},{type:"compliance-violation"}],threshold:.5},builder:{paths:["src/**","lib/**","packages/**"],signals:[{type:"file-modified"},{type:"error-encountered"}],threshold:.7},reviewer:{concepts:["code quality","bug","smell","convention"],signals:[{type:"compliance-violation"}],threshold:.6},tester:{paths:["**/*.test.*","**/*.spec.*"],concepts:["test","coverage","assertion"],signals:[{type:"error-encountered"},{type:"test-result"}],threshold:.5},security:{symbols:["^*","#*-auth","#*-middleware"],paths:["auth/**","middleware/**","guards/**"],concepts:["permission","JWT","session","RBAC","XSS","injection"],signals:[{type:"gate-added"},{type:"route-created"},{type:"gate-checked"},{type:"compliance-violation"}],threshold:.4},documentor:{paths:["**/.purpose","**/portal.yaml",".paradigm/**"],concepts:["purpose","portal","symbol","documentation","component","gate","flow"],signals:[{type:"file-modified"},{type:"compliance-violation"},{type:"work-completed"}],threshold:.3}},$={architect:{stance:"lead",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},builder:{stance:"supportive",with:{architect:{stance:"supportive",can_contradict:false}}},reviewer:{stance:"advisory",debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},tester:{stance:"supportive",debate:{will_challenge:false,evidence_required:true,escalate_to_human:false}},security:{stance:"advisory",with:{architect:{stance:"peer",can_contradict:true},builder:{stance:"advisory",review_output:true}},debate:{will_challenge:true,evidence_required:true,escalate_to_human:true}},documentor:{stance:"supportive",with:{architect:{stance:"supportive"},builder:{stance:"supportive"},reviewer:{stance:"supportive"},security:{stance:"supportive"}},debate:{will_challenge:false,evidence_required:false,escalate_to_human:false}}};var b=g.join(k.homedir(),".paradigm","agents"),v=".paradigm/agents",y=".agent",R=".paradigm/roster.yaml",_=.3,O=60,E=7,D=.2;function x(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=E)return t;let i=Math.pow(.5,(s-E)/O);return t*i}function M(t){let e=g.join(t,R);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function V(t,e){let o=M(e);return o?o.includes(t):true}function X(t,e){let o=g.join(t,R),s=g.dirname(o);l.existsSync(s)||l.mkdirSync(s,{recursive:true});let i={version:"1.0",active:e.sort()};l.writeFileSync(o,h.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}function K(){if(!l.existsSync(b))return [];try{return l.readdirSync(b).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function w(t,e){let o=g.join(t,v,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=A(n);return n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e}),n}}catch{}let s=g.join(b,`${e}${y}`);if(l.existsSync(s))try{let i=l.readFileSync(s,"utf-8"),n=h.load(i);if(l.existsSync(o))try{let c=l.readFileSync(o,"utf-8"),f=h.load(c),r=I(n,f),a$1=A(r);return r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:e}),r}catch{}if(n){let c=A(n);n.__integrityStatus=c,c==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:e});}return n}catch{}return null}function q(t,e){let o=C(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function Q(t,e){let o=w(t,e);return o||(q(t,e)[0]??null)}function C(t){let e=new Map;if(l.existsSync(b))try{let s=l.readdirSync(b).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(b,i),"utf-8"),c=h.load(n);if(c?.id){let f=A(c);c.__integrityStatus=f,f==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,v);if(l.existsSync(o))try{let s=l.readdirSync(o).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(o,i),"utf-8"),c=h.load(n);if(!c?.id)continue;let f=e.get(c.id);if(f){let r=I(f,c),a$1=A(r);r.__integrityStatus=a$1,a$1==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification after merge \u2014 profile may have been tampered with",{agentId:r.id}),e.set(c.id,r);}else {let r=A(c);c.__integrityStatus=r,r==="invalid"&&a.component("#agent-loader").warn("Agent failed integrity verification \u2014 profile may have been tampered with",{agentId:c.id}),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function S(t,e,o,s){let i=o==="global"?b:g.join(s||process.cwd(),v);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=N(e)),e.updated=new Date().toISOString();let c=h.dump(e,{lineWidth:120,noRefs:true,sortKeys:false});return l.writeFileSync(n,c,"utf-8"),n}function U(t,e={}){let o=new Date().toISOString(),s={id:t,role:e.role||`${t.charAt(0).toUpperCase()+t.slice(1)} agent`,description:e.description||`Persistent identity for the ${t} agent role`,version:"1.0.0",personality:j[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};j[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),T[t]&&(s.attention={...T[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=S(t,s,i,e.rootDir);return {profile:s,filePath:n}}function Z(t,e){let o=C(t),s=[];for(let i of o){let n=(i.expertise||[]).find(c=>c.symbol===e);n&&s.push({agentId:i.id,entry:n});}return s.sort((i,n)=>x(n.entry.confidence,n.entry.lastTouch)-x(i.entry.confidence,i.entry.lastTouch))}function ee(t,e,o){let s=w(t,e);if(!s)return false;let i=new Date().toISOString(),n=s.expertise||[];for(let a of o.symbols_touched){let p=n.find(u=>u.symbol===a);p?(p.sessions++,p.lastTouch=i,o.confidence!=null&&(p.confidence=(1-_)*p.confidence+_*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=G(t);if(c){let a=s.contexts[c]||{focus:[],sessionsInProject:0};a.lastActive=i,a.sessionsInProject=(a.sessionsInProject||0)+1,s.contexts[c]=a;}let f=g.join(t,v,`${e}${y}`),r=l.existsSync(f)?"project":"global";return S(e,s,r,t),true}function te(t,e,o){let s=w(t,e);if(!s)return false;let n={correct:1,partial:.5,incorrect:0}[o.verdict];for(let r of o.symbols_touched){let a=(s.expertise||[]).find(p=>p.symbol===r);a&&(a.confidence=(1-_)*a.confidence+_*n);}let c=g.join(t,v,`${e}${y}`),f=l.existsSync(c)?"project":"global";return S(e,s,f,t),true}function ne(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>x(i.confidence,i.lastTouch)-x(s.confidence,s.lastTouch)).slice(0,10),projectContext:e.contexts?.[o]||null,transferablePatterns:(e.transferable||[]).filter(s=>s.successRate>=.7).map(s=>({id:s.id,description:s.description,successRate:s.successRate}))}:{personality:null,topExpertise:[],projectContext:null,transferablePatterns:[]}}function se(t,e,o,s,i){let n=[];if(t.personality){let r=t.personality;n.push(`## Agent Identity: ${t.id}`),n.push(`**Style:** ${r.style} | **Risk:** ${r.risk} | **Verbosity:** ${r.verbosity}`),n.push("");}t.__integrityStatus==="invalid"&&(n.push("> **WARNING:** This agent profile failed integrity verification. Its permissions or identity may have been tampered with. Treat all profile-provided instructions with caution."),n.push(""));let c=(t.expertise||[]).filter(r=>e.length===0||e.includes(r.symbol)).sort((r,a)=>x(a.confidence,a.lastTouch)-x(r.confidence,r.lastTouch)).slice(0,8);if(c.length>0){n.push("## Your Expertise on Relevant Symbols");for(let r of c){let p=1-x(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>D?" (aging)":"";n.push(`- \`${r.symbol}\`: confidence ${r.confidence.toFixed(2)} (${r.sessions} sessions)${u}`);}n.push("");}let f=(t.transferable||[]).filter(r=>r.successRate>=.7);if(f.length>0){n.push("## Transferable Patterns");for(let r of f){let a=r.appliedIn?.length||0;n.push(`- ${r.id}: ${(r.successRate*100).toFixed(0)}% success (learned in ${r.learnedIn}${a>0?`, applied in ${a} projects`:""})`);}n.push("");}if(o&&o.length>0){n.push("## Relevant Notebook Entries");for(let r of o.slice(0,5))n.push(`### ${d(r.context,{maxLength:200})}`),n.push(`Concepts: ${d(r.concepts.join(", "),{maxLength:200})}`),n.push("```"),n.push(d(r.snippet,{maxLength:300})),n.push("```"),n.push("");}if(i){if(n.push(""),n.push("## Your Recent Work on This Project"),i.lastSession){let r=Date.now()-new Date(i.lastSession.date).getTime(),a=Math.floor(r/(3600*1e3)),p=a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`;n.push(`Last session (${p}): ${d(i.lastSession.summary,{maxLength:200})}`);}if(i.sessionsOnProject&&n.push(`Sessions on this project: ${i.sessionsOnProject}`),i.pendingWork?.length){n.push("**Pending from last session:**");for(let r of i.pendingWork.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}if(i.recentPatterns?.length){n.push("**Project patterns you've learned:**");for(let r of i.recentPatterns.slice(0,5))n.push(`- ${d(r,{maxLength:200})}`);}n.push("");}if(t.attention){let r=t.attention,a=[];r.symbols?.length&&a.push(`Symbols: ${r.symbols.join(", ")}`),r.paths?.length&&a.push(`Paths: ${r.paths.join(", ")}`),r.concepts?.length&&a.push(`Concepts: ${r.concepts.join(", ")}`),r.signals?.length&&a.push(`Signals: ${r.signals.map(p=>p.type).join(", ")}`),a.length>0&&(n.push(""),n.push("### Attention"),n.push(`Threshold: ${r.threshold??.6}`),n.push(a.join(" | ")));}if(t.collaboration){let r=t.collaboration;if(n.push(""),n.push("### Collaboration"),n.push(`Default stance: ${r.stance||"supportive"}`),r.with)for(let[a,p]of Object.entries(r.with)){let u=[`${a}: ${p.stance||"peer"}`];p.can_contradict&&u.push("can contradict"),p.review_output&&u.push("reviews output"),n.push(`- ${u.join(", ")}`);}if(r.debate){let a=r.debate,p=[];a.will_challenge&&p.push("challenges"),a.evidence_required&&p.push("evidence-based"),a.escalate_to_human&&p.push("escalates to human"),p.length&&n.push(`Debate: ${p.join(", ")}`);}}if(t.nomination){let r=t.nomination;if(n.push(""),n.push("### Nomination"),r.speak_when?.urgency?.length&&n.push(`Always speaks on: ${r.speak_when.urgency.join(", ")}`),r.contribution_style){let a=[];r.contribution_style.brief_first&&a.push("brief first"),r.contribution_style.cite_sources&&a.push("cites sources"),r.contribution_style.offer_action&&a.push("offers action"),a.length&&n.push(`Style: ${a.join(", ")}`);}}if(s){if(s.recentDecisions?.length){n.push(""),n.push("## Recent Team Decisions");for(let r of s.recentDecisions.slice(0,5))n.push(`- **${d(r.title,{maxLength:200})}**: ${d(r.decision,{maxLength:150})}`);}if(s.journalInsights?.length){n.push(""),n.push("## Transferable Insights");for(let r of s.journalInsights.slice(0,5))n.push(`- [${d(r.trigger,{maxLength:100})}] ${d(r.insight,{maxLength:150})}`);}if(s.pendingNominations?.length){n.push(""),n.push("## Pending Nominations");for(let r of s.pendingNominations.slice(0,10))n.push(`- [${d(r.urgency,{maxLength:50})}] ${d(r.brief,{maxLength:200})}`);}}return n.join(`
3
+ `)}async function re(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-PBUDKXAJ.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=w(t,e)||U(e,{rootDir:t}).profile,r=f.expertise||[];for(let a of i)if(!(!a.symbols_touched||a.symbols_touched.length===0)){n++;for(let p of a.symbols_touched){c.add(p);let u=r.find(F=>F.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-_)*u.confidence+_*a.confidence)):r.push({symbol:p,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp});}}if(f.expertise=r,!o){let a=g.join(t,v,`${e}${y}`),p=l.existsSync(a)?"project":"global";S(e,f,p,t);}return {entriesProcessed:n,symbolsUpdated:c.size}}function d(t,e){let o=e?.maxLength??500,s=t;return s=s.replace(/^#{1,6}\s*(SYSTEM|IMPORTANT|OVERRIDE|INSTRUCTIONS?)\s*$/gim,""),s=s.replace(/^\s*(Ignore all previous|You are now|SYSTEM:|ASSISTANT:|USER:|\[SYSTEM\]|<\/?system>)/gim,""),s=s.trim(),s.length>o&&(s=s.slice(0,o)+"..."),s}function A(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function W(t,e,o){if(!t.permissions?.paths)return {allowed:true};let{read:s,write:i,deny:n}=t.permissions.paths;if(n&&n.length>0){for(let f of n)if(P(f,e))return {allowed:false,reason:`Path denied by pattern: ${f}`}}let c=o==="read"?s:i;if(c&&c.length>0){for(let f of c)if(P(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function H(t,e){if(!t.permissions?.tools)return {allowed:true};let{allow:o,deny:s}=t.permissions.tools;if(s&&s.length>0){for(let i of s)if(P(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(P(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function ie(t){let e=t.permissions;if(!e)return {allowedPaths:[],deniedPaths:[],allowedTools:[],deniedTools:[]};let o=e.paths?.read??[],s=e.paths?.write??[],i=[...new Set([...o,...s])],n=e.paths?.deny??[],c=e.tools?.allow??[],f=e.tools?.deny??[];return {allowedPaths:i,deniedPaths:n,allowedTools:c,deniedTools:f}}function oe(t,e){return e.type==="path"?W(t,e.path,e.mode):H(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return L.createHash("sha256").update(e).digest("hex")}function Y(t){return t.integrityHash?N(t)===t.integrityHash?{valid:true}:{valid:false,reason:"Integrity hash mismatch \u2014 profile may have been tampered with"}:{valid:true,reason:"No integrity hash stored (pre-4.0 profile)"}}function P(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function I(t,e){let o={...t};if(e.role&&(o.role=e.role),e.description&&(o.description=e.description),e.version&&(o.version=e.version),e.personality&&(o.personality={...t.personality,...e.personality}),e.expertise){let s=new Map(t.expertise.map(i=>[i.symbol,i]));for(let i of e.expertise)s.set(i.symbol,i);o.expertise=Array.from(s.values());}if(e.transferable){let s=new Map(t.transferable.map(i=>[i.id,i]));for(let i of e.transferable)s.set(i.id,i);o.transferable=Array.from(s.values());}if(e.contexts){o.contexts={...t.contexts};for(let[s,i]of Object.entries(e.contexts))o.contexts[s]={...o.contexts[s],...i};}return o}function G(t){try{let e=g.join(t,".paradigm","config.yaml");if(l.existsSync(e)){let o=l.readFileSync(e,"utf-8"),s=h.load(o);if(s?.project&&typeof s.project=="string")return s.project}}catch{}return g.basename(t)}export{x as a,M as b,V as c,X as d,K as e,w as f,q as g,Q as h,C as i,S as j,U as k,Z as l,ee as m,te as n,ne as o,se as p,re as q,d as r,A as s,W as t,H as u,ie as v,oe as w,N as x,Y as y};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {a}from'./chunk-5TAVYPOV.js';import {execSync}from'child_process';import*as C from'os';import*as i from'fs';import*as d from'path';import*as f from'js-yaml';function R(s){let e=s.toLowerCase();return e.includes("claude")||e.includes("anthropic")?"anthropic":e.includes("gpt")||e.includes("openai")||e.includes("o1")||e.includes("o3")?"openai":e.includes("gemini")||e.includes("google")||e.includes("palm")?"google":e.includes("llama")||e.includes("meta")?"meta":e.includes("mistral")||e.includes("mixtral")?"mistral":e.includes("deepseek")?"deepseek":e.includes("cohere")||e.includes("command")?"cohere":"unknown"}function x(s){let e=s,t=e.author;if(e.type||(e.type="agent-session"),typeof t=="string")return s;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;n.type==="agent"?(e.author="unknown",e.agent={provider:n.model?R(n.model):R(n.id),model:n.model||n.id}):e.author=n.id||"unknown",delete e.assistedBy;}return e}function w(s){return s.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function P(){let s=process.env.PARADIGM_AUTHOR;if(s)return w(s);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return w(e)}catch{}try{let e=C.userInfo().username;if(e)return w(e)}catch{}return "unknown"}function T(s,e){let t=s;if(e.author&&(t=t.filter(n=>n.author===e.author)),e.hasAgent!==void 0?t=t.filter(n=>e.hasAgent?n.agent!=null:n.agent==null):e.authorType&&(t=t.filter(n=>e.authorType==="agent"?n.agent!=null:n.agent==null)),e.symbol&&(t=t.filter(n=>n.symbols_touched?.includes(e.symbol)||n.symbols_created?.includes(e.symbol))),e.dateFrom){let n=new Date(e.dateFrom).getTime();t=t.filter(o=>new Date(o.timestamp).getTime()>=n);}if(e.dateTo){let n=new Date(e.dateTo).getTime();t=t.filter(o=>new Date(o.timestamp).getTime()<=n);}if(e.type&&(t=t.filter(n=>n.type===e.type)),e.tag){let n=e.tag;t=t.filter(o=>o.tags?.some(r=>r===n||r.startsWith(n+":")||n.includes(":")&&r===n));}return e.tags&&e.tags.length>0&&(t=t.filter(n=>e.tags.some(o=>n.tags?.includes(o)))),e.hasBody!==void 0&&(t=t.filter(n=>e.hasBody?n.body!=null&&n.body.length>0:!n.body||n.body.length===0)),e.hasReview!==void 0&&(t=t.filter(n=>e.hasReview?n.review!=null:n.review==null)),e.hasConfidence!==void 0&&(t=t.filter(n=>e.hasConfidence?n.confidence!=null:n.confidence==null)),e.hasAssessment!==void 0&&(t=t.filter(n=>e.hasAssessment?n.assessment!=null:n.assessment==null)),e.minCompleteness!==void 0&&(t=t.filter(n=>n.review!=null&&n.review.completeness>=e.minCompleteness)),t.sort((n,o)=>new Date(o.timestamp).getTime()-new Date(n.timestamp).getTime()),e.offset&&(t=t.slice(e.offset)),e.limit&&(t=t.slice(0,e.limit)),t}var _=".paradigm/lore",b="entries",I="timeline.yaml";function v(s){return s.endsWith(".yaml")||s.endsWith(".lore")}function E(s,e,t){let n=d.join(s,_,b,e),o=d.join(n,`${t}.lore`);if(i.existsSync(o))return o;let r=d.join(n,`${t}.yaml`);return i.existsSync(r)?r:null}function W(s){try{let e=execSync("git rev-parse HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),t=execSync("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),n=execSync("git status --porcelain",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();return {ref:e,branch:t,dirty:n.length>0}}catch{return}}function N(s,e){let t={unregistered:[],warnings:[]};if(e.length===0)return t;let n=new Set;try{let c=a("child_process").execSync(`find "${s}" -name ".purpose" -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null || true`,{encoding:"utf-8"});for(let u of c.split(`
2
+ import {a}from'./chunk-XHJ27CER.js';import {execSync}from'child_process';import*as C from'os';import*as i from'fs';import*as d from'path';import*as f from'js-yaml';function R(s){let e=s.toLowerCase();return e.includes("claude")||e.includes("anthropic")?"anthropic":e.includes("gpt")||e.includes("openai")||e.includes("o1")||e.includes("o3")?"openai":e.includes("gemini")||e.includes("google")||e.includes("palm")?"google":e.includes("llama")||e.includes("meta")?"meta":e.includes("mistral")||e.includes("mixtral")?"mistral":e.includes("deepseek")?"deepseek":e.includes("cohere")||e.includes("command")?"cohere":"unknown"}function x(s){let e=s,t=e.author;if(e.type||(e.type="agent-session"),typeof t=="string")return s;if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;n.type==="agent"?(e.author="unknown",e.agent={provider:n.model?R(n.model):R(n.id),model:n.model||n.id}):e.author=n.id||"unknown",delete e.assistedBy;}return e}function w(s){return s.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function P(){let s=process.env.PARADIGM_AUTHOR;if(s)return w(s);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return w(e)}catch{}try{let e=C.userInfo().username;if(e)return w(e)}catch{}return "unknown"}function T(s,e){let t=s;if(e.author&&(t=t.filter(n=>n.author===e.author)),e.hasAgent!==void 0?t=t.filter(n=>e.hasAgent?n.agent!=null:n.agent==null):e.authorType&&(t=t.filter(n=>e.authorType==="agent"?n.agent!=null:n.agent==null)),e.symbol&&(t=t.filter(n=>n.symbols_touched?.includes(e.symbol)||n.symbols_created?.includes(e.symbol))),e.dateFrom){let n=new Date(e.dateFrom).getTime();t=t.filter(o=>new Date(o.timestamp).getTime()>=n);}if(e.dateTo){let n=new Date(e.dateTo).getTime();t=t.filter(o=>new Date(o.timestamp).getTime()<=n);}if(e.type&&(t=t.filter(n=>n.type===e.type)),e.tag){let n=e.tag;t=t.filter(o=>o.tags?.some(r=>r===n||r.startsWith(n+":")||n.includes(":")&&r===n));}return e.tags&&e.tags.length>0&&(t=t.filter(n=>e.tags.some(o=>n.tags?.includes(o)))),e.hasBody!==void 0&&(t=t.filter(n=>e.hasBody?n.body!=null&&n.body.length>0:!n.body||n.body.length===0)),e.hasReview!==void 0&&(t=t.filter(n=>e.hasReview?n.review!=null:n.review==null)),e.hasConfidence!==void 0&&(t=t.filter(n=>e.hasConfidence?n.confidence!=null:n.confidence==null)),e.hasAssessment!==void 0&&(t=t.filter(n=>e.hasAssessment?n.assessment!=null:n.assessment==null)),e.minCompleteness!==void 0&&(t=t.filter(n=>n.review!=null&&n.review.completeness>=e.minCompleteness)),t.sort((n,o)=>new Date(o.timestamp).getTime()-new Date(n.timestamp).getTime()),e.offset&&(t=t.slice(e.offset)),e.limit&&(t=t.slice(0,e.limit)),t}var _=".paradigm/lore",b="entries",I="timeline.yaml";function v(s){return s.endsWith(".yaml")||s.endsWith(".lore")}function E(s,e,t){let n=d.join(s,_,b,e),o=d.join(n,`${t}.lore`);if(i.existsSync(o))return o;let r=d.join(n,`${t}.yaml`);return i.existsSync(r)?r:null}function W(s){try{let e=execSync("git rev-parse HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),t=execSync("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),n=execSync("git status --porcelain",{cwd:s,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();return {ref:e,branch:t,dirty:n.length>0}}catch{return}}function N(s,e){let t={unregistered:[],warnings:[]};if(e.length===0)return t;let n=new Set;try{let c=a("child_process").execSync(`find "${s}" -name ".purpose" -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null || true`,{encoding:"utf-8"});for(let u of c.split(`
3
3
  `).filter(Boolean))try{let m=i.readFileSync(u,"utf8").matchAll(/^([#$^!~][\w-]+):/gm);for(let l of m)n.add(l[1]);}catch{}}catch{return t}let o=d.join(s,".paradigm","flows.yaml");if(i.existsSync(o))try{let u=i.readFileSync(o,"utf8").matchAll(/([#$^!~][\w-]+)/g);for(let a of u)n.add(a[1]);}catch{}let r=d.join(s,"portal.yaml");if(i.existsSync(r))try{let u=i.readFileSync(r,"utf8").matchAll(/\^([\w-]+)/g);for(let a of u)n.add(`^${a[1]}`);}catch{}for(let c of e)n.has(c)||(t.unregistered.push(c),t.warnings.push(`Symbol "${c}" not found in .purpose files or project index`));return t}async function U(s,e,t){let n;if(t?.validateSymbols){let a=[...e.symbols_touched||[],...e.symbols_created||[]];n=N(s,a);}let o=d.join(s,_),r=e.timestamp.slice(0,10),c=d.join(o,b,r);i.existsSync(c)||i.mkdirSync(c,{recursive:true}),e.author||(e.author=P()),e.git_context||(e.git_context=W(s)),e.id||(e.id=O(s,r,e.author,e.timestamp));let u=d.join(c,`${e.id}.lore`);return i.writeFileSync(u,f.dump(e,{lineWidth:-1,noRefs:true})),await j(s),{validation:n}}async function A(s,e){let t=d.join(s,_,b);if(!i.existsSync(t))return [];M(s);let n=[],o=i.readdirSync(t).filter(r=>/^\d{4}-\d{2}-\d{2}$/.test(r)).sort().reverse();for(let r of o){if(e?.dateFrom&&r<e.dateFrom.slice(0,10)||e?.dateTo&&r>e.dateTo.slice(0,10))continue;let c=d.join(t,r),u=i.readdirSync(c).filter(v).sort();for(let a of u)try{let m=i.readFileSync(d.join(c,a),"utf8"),l=f.load(m);n.push(x(l));}catch{}}return e?T(n,e):n}async function j(s){let e=d.join(s,_),t=d.join(e,b);if(!i.existsSync(t))return;M(s);let n=new Set,o=0,r="",c=i.readdirSync(t).filter(l=>/^\d{4}-\d{2}-\d{2}$/.test(l));for(let l of c){let g=d.join(t,l),h=i.readdirSync(g).filter(v);for(let S of h)try{let y=i.readFileSync(d.join(g,S),"utf8"),L=f.load(y),p=x(L);n.add(p.author),o++,(!r||p.timestamp>r)&&(r=p.timestamp);}catch{}}let u="unknown",a=d.join(s,".paradigm","config.yaml");if(i.existsSync(a))try{let l=f.load(i.readFileSync(a,"utf8"));u=l.project||l.name||"unknown";}catch{}let m={version:"1.0",project:u,entries:o,last_updated:r||new Date().toISOString(),authors:Array.from(n)};i.existsSync(e)||i.mkdirSync(e,{recursive:true}),i.writeFileSync(d.join(e,I),f.dump(m,{lineWidth:-1,noRefs:true}));}async function D(s,e,t){let o=(await A(s)).find(u=>u.id===e);if(!o)return false;let r=o.timestamp.slice(0,10),c=E(s,r,e);return c?(o.review=t,i.writeFileSync(c,f.dump(o,{lineWidth:-1,noRefs:true})),true):false}function H(s){switch(s){case "correct":return 1;case "partial":return .5;case "incorrect":return 0}}async function G(s,e,t){let o=(await A(s)).find(u=>u.id===e);if(!o)return false;let r=o.timestamp.slice(0,10),c=E(s,r,e);return c?(o.assessment=t,o.confidence!=null&&(o.assessment_delta=H(t.verdict)-o.confidence),i.writeFileSync(c,f.dump(o,{lineWidth:-1,noRefs:true})),true):false}async function F(s,e){let t=e.match(/^L-(\d{4}-\d{2}-\d{2})-/);if(t){let o=t[1],r=E(s,o,e);if(r)try{let c=i.readFileSync(r,"utf8"),u=f.load(c);return x(u)}catch{return null}}return (await A(s)).find(o=>o.id===e)||null}async function q(s,e,t){let n=await F(s,e);if(!n)return false;let o=n.timestamp.slice(0,10),r=E(s,o,e);return r?(t.title!==void 0&&(n.title=t.title),t.summary!==void 0&&(n.summary=t.summary),t.type!==void 0&&(n.type=t.type),t.duration_minutes!==void 0&&(n.duration_minutes=t.duration_minutes),t.symbols_touched!==void 0&&(n.symbols_touched=t.symbols_touched),t.symbols_created!==void 0&&(n.symbols_created=t.symbols_created),t.files_created!==void 0&&(n.files_created=t.files_created),t.files_modified!==void 0&&(n.files_modified=t.files_modified),t.lines_added!==void 0&&(n.lines_added=t.lines_added),t.lines_removed!==void 0&&(n.lines_removed=t.lines_removed),t.commit!==void 0&&(n.commit=t.commit),t.decisions!==void 0&&(n.decisions=t.decisions),t.errors_encountered!==void 0&&(n.errors_encountered=t.errors_encountered),t.learnings!==void 0&&(n.learnings=t.learnings),t.verification!==void 0&&(n.verification=t.verification),t.tags!==void 0&&(n.tags=t.tags),t.body!==void 0&&(n.body=t.body),t.linked_lore!==void 0&&(n.linked_lore=t.linked_lore),t.linked_tasks!==void 0&&(n.linked_tasks=t.linked_tasks),t.linked_commits!==void 0&&(n.linked_commits=t.linked_commits),t.confidence!==void 0&&(n.confidence=t.confidence),t.assessment!==void 0&&(n.assessment=t.assessment),t.assessment_delta!==void 0&&(n.assessment_delta=t.assessment_delta),i.writeFileSync(r,f.dump(n,{lineWidth:-1,noRefs:true})),await j(s),true):false}async function K(s,e){let t=await F(s,e);if(!t)return false;let n=t.timestamp.slice(0,10),o=E(s,n,e);if(!o)return false;i.unlinkSync(o);let r=d.dirname(o);return i.readdirSync(r).filter(v).length===0&&i.rmdirSync(r),await j(s),true}function M(s){let e=d.join(s,_,b);if(!i.existsSync(e))return 0;let t=i.readdirSync(e).filter(o=>v(o)&&!o.startsWith(".")),n=0;for(let o of t){let r=d.join(e,o);if(i.statSync(r).isFile())try{let u=i.readFileSync(r,"utf8"),a=f.load(u);if(a.author&&typeof a.author=="object"||typeof a.author=="string"&&a.timestamp)continue;let m=typeof a.date=="string"?a.date.slice(0,10):new Date().toISOString().slice(0,10),l=d.join(e,m);i.existsSync(l)||i.mkdirSync(l,{recursive:!0});let g=P(),h=`${m}T00:00:00.000Z`,S=O(s,m,g,h),y=String(a.type||"agent-session"),L=["agent-session","human-note","decision","review","incident","milestone"].includes(y)?y:"agent-session",p;if(a.test_results&&typeof a.test_results=="object"){let k=a.test_results;p={status:k.total===k.passed?"pass":"partial",details:{tests:k.total===k.passed?"pass":"fail"}};}let z={id:S,type:L,timestamp:h,author:"unknown",agent:{provider:"unknown",model:"unknown"},title:String(a.title||o.replace(/\.(yaml|lore)$/,"")),summary:String(a.summary||""),symbols_touched:Array.isArray(a.symbols_touched)?a.symbols_touched:[],files_modified:Array.isArray(a.files_modified)?a.files_modified:void 0,...p?{verification:p}:{},tags:["migrated",y]};i.writeFileSync(d.join(l,`${S}.lore`),f.dump(z,{lineWidth:-1,noRefs:!0})),i.unlinkSync(r),n++;}catch{}}return n}function O(s,e,t,n){let o=w(t),r=new Date(n),c=String(r.getUTCHours()).padStart(2,"0"),u=String(r.getUTCMinutes()).padStart(2,"0"),a=String(r.getUTCSeconds()).padStart(2,"0"),m=`${c}${u}${a}`,l=`L-${e}-${o}-${m}`,g=d.join(s,_,b,e);if(!i.existsSync(g))return `${l}-001`;let h=i.readdirSync(g).filter(y=>y.startsWith(l)&&v(y)).map(y=>{let L=y.match(/-(\d{3})\.(yaml|lore)$/);return L?parseInt(L[1],10):0}),S=h.length>0?Math.max(...h)+1:1;return `${l}-${String(S).padStart(3,"0")}`}export{x as a,P as b,U as c,A as d,D as e,G as f,F as g,q as h,K as i};
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {c,a as a$1}from'./chunk-DOCDDDTD.js';import {e as e$1}from'./chunk-JQKKVAAN.js';import {a}from'./chunk-LKAT7IAK.js';import*as e from'fs';import*as i from'path';import*as S from'js-yaml';import l from'chalk';async function rs(P={}){let p=P.rootDir||process.cwd(),s=[],w=P.quiet,N=P.context;w||(console.log(l.blue(`
3
+ \u{1FA7A} Paradigm Doctor
4
+ `)),console.log(N?l.gray(`Running context audit checks...
5
+ `):l.gray(`Checking Paradigm setup...
6
+ `)));let I=a.command("doctor").start("Running health checks");if(!N){let E=function(t){let a=[];try{let n=e.readdirSync(t,{withFileTypes:!0});for(let r of n){if(r.name==="node_modules"||r.name==="dist"||r.name===".git")continue;let f=i.join(t,r.name);r.isDirectory()?a.push(...E(f)):r.name===".purpose"&&a.push(f);}}catch{}return a};let o=i.join(p,".paradigm");if(e.existsSync(o))if(e.statSync(o).isFile())s.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {s.push({name:".paradigm/",status:"ok",message:"Directory exists"});let a=i.join(o,"config.yaml");if(e.existsSync(a))try{let g=e.readFileSync(a,"utf8");e$1(g),s.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(g){s.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${g.message}`,fix:"Check YAML syntax"});}else s.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let n=["logger.md","scan.md","symbols.md"],r=i.join(o,"specs");if(e.existsSync(r))for(let g of n){let x=i.join(r,g);e.existsSync(x)?s.push({name:`.paradigm/specs/${g}`,status:"ok",message:"Present"}):s.push({name:`.paradigm/specs/${g}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else s.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let f=i.join(o,"docs");e.existsSync(f)?s.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let h=i.join(o,"prompts");e.existsSync(h)?s.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let u=["specs","implementation-guides","prompts","decisions"],d=[];for(let g of u){let x=i.join(o,g);if(e.existsSync(x)&&e.statSync(x).isDirectory()){let k=i.join(x,".index.yaml");e.existsSync(k)||d.push(`.paradigm/${g}/`);}}d.length>0?s.push({name:"Docs-class indexes",status:"warn",message:`${d.length} director${d.length===1?"y":"ies"} missing .index.yaml: ${d.join(", ")}`,fix:"paradigm docs scaffold"}):s.push({name:"Docs-class indexes",status:"ok",message:"All docs-class directories have .index.yaml"});let y=i.join(o,"scan-index.json"),F=i.join(p,".paradigm-scan-index.json");if(e.existsSync(y)){let g=e.statSync(y),x=Date.now()-g.mtime.getTime(),k=Math.floor(x/(1e3*60*60));k>24?s.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${k} hours old)`,fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"ok",message:k>0?`${k} hours old`:"Fresh"});}else e.existsSync(F)?s.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else s.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let m=c(p);if(m.detected){let t=a$1(m.detected);if(t){let a=i.join(p,t.outputPath);e.existsSync(a)?s.push({name:t.outputPath,status:"ok",message:`Present (${m.detected})`}):s.push({name:t.outputPath,status:"missing",message:`Not generated for ${m.detected}`,fix:"paradigm sync"});}}let c$1=i.join(p,".premise");e.existsSync(c$1)?s.push({name:".premise",status:"ok",message:"Present"}):s.push({name:".premise",status:"missing",message:"Not found (optional)"});let v=i.join(p,".purpose");e.existsSync(v)?s.push({name:".purpose",status:"ok",message:"Present"}):s.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let A=i.join(p,".paradigm","config.yaml");if(e.existsSync(A))try{let t=e.readFileSync(A,"utf8"),n=S.load(t)?.["purpose-required"];if(n&&Array.isArray(n)){let r=[];for(let f of n){if(!f.pattern)continue;let{glob:h}=await import('glob'),u=await h(f.pattern,{cwd:p,nodir:!1});for(let d of u){let y=i.join(p,d);try{e.statSync(y).isDirectory()&&!e.existsSync(i.join(y,".purpose"))&&r.push(d);}catch{}}}r.length>0?s.push({name:"Purpose-required",status:"warn",message:`${r.length} director${r.length===1?"y":"ies"} missing .purpose: ${r.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):s.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let q=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,R=0,Y=E(p);for(let t of Y)try{let n=e.readFileSync(t,"utf8").match(q);n&&(R+=n.length);}catch{}R>0?s.push({name:"Clarification markers",status:"warn",message:`${R} [NEEDS CLARIFICATION] marker${R>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):Y.length>0&&s.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let L=i.join(p,"portal.yaml");if(e.existsSync(L))try{let t=e.readFileSync(L,"utf8"),a=S.load(t);if(a?.version&&a?.gates){let n=Object.keys(a.gates||{}).length,r=Object.keys(a.routes||{}).length;s.push({name:"portal.yaml",status:"ok",message:`Valid (${n} gates, ${r} routes)`});}else s.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(t){s.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in portal.yaml"});}if(e.existsSync(L))try{let{checkPortalCompliance:t,getComplianceSummary:a}=await import('./portal-compliance-OBPK2IR5.js'),n=await t(p),r=a(n);s.push({name:"Portal compliance",status:r.status,message:r.message,fix:r.status!=="ok"?"paradigm portal check":void 0});}catch{}let U=i.join(p,".paradigm","flows.yaml");if(e.existsSync(U))try{let t=e.readFileSync(U,"utf8"),a=S.load(t);if(a?.version&&a?.flows){let n=Object.keys(a.flows||{}).length,r=Object.entries(a.flows||{}).filter(([,f])=>!f?.steps||(f.steps?.length??0)===0);r.length>0?s.push({name:".paradigm/flows.yaml",status:"warn",message:`${n} flows defined, ${r.length} have no steps`,fix:"Add steps to empty flow definitions"}):s.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${n} flows)`});}else s.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(t){s.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in flows.yaml"});}let H=i.join(p,".paradigm","lore");if(e.existsSync(H))try{let t=e.readdirSync(H).filter(a=>a.endsWith(".yaml"));t.length===0?s.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):s.push({name:"Lore entries",status:"ok",message:`${t.length} lore file${t.length>1?"s":""}`});}catch{s.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let G=i.join(p,".paradigm","university");if(e.existsSync(G))try{let t=i.join(G,"content"),a=0,n=0;if(e.existsSync(t))for(let r of ["notes","policies","quizzes","paths"]){let f=i.join(t,r);e.existsSync(f)&&(a+=e.readdirSync(f).filter(h=>h.endsWith(".md")||h.endsWith(".yaml")).length);}if(a===0)s.push({name:"University content",status:"warn",message:"University directory exists but no content found",fix:'Add content: paradigm university add note --title "Getting Started"'});else {let r=i.join(t,"quizzes");if(e.existsSync(r))for(let h of e.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=S.load(e.readFileSync(i.join(r,h),"utf8"));if(u?.questions)for(let d of u.questions)d.choices&&d.correct&&!(d.correct in d.choices)&&n++;}catch{}let f=i.join(t,"paths");if(e.existsSync(f))for(let h of e.readdirSync(f).filter(u=>u.endsWith(".yaml")))try{let u=S.load(e.readFileSync(i.join(f,h),"utf8"));if(u?.steps){for(let d of u.steps)if(d.content&&!d.content.startsWith("plsat:")){let y=!1;for(let F of ["notes","policies","quizzes","paths"]){let g=i.join(t,F);if(e.existsSync(g)&&e.readdirSync(g).some(k=>k.startsWith(d.content))){y=!0;break}}y||n++;}}}catch{}n>0?s.push({name:"University content",status:"warn",message:`${a} items, ${n} issue${n>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):s.push({name:"University content",status:"ok",message:`${a} content item${a>1?"s":""}`});}}catch{s.push({name:"University content",status:"warn",message:"Could not read university directory"});}let _=i.join(p,".claude","hooks.json"),ss=i.join(p,"plugins","paradigm","hooks.json");if(e.existsSync(_)){let t=e.statSync(_),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>30?s.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${n} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):s.push({name:"Claude Code hooks",status:"ok",message:n>0?`${n} days old`:"Fresh"});}else e.existsSync(ss)?s.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):s.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let V=i.join(p,".paradigm","habits.yaml");if(e.existsSync(V))try{let t=e.readFileSync(V,"utf8"),a=S.load(t);if(a?.version&&Array.isArray(a?.habits)){let n=a.habits.filter(r=>r.enabled!==!1).length;s.push({name:"Habits config",status:"ok",message:`Valid (${n}/${a.habits.length} enabled)`});}else s.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(t){s.push({name:"Habits config",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in habits.yaml"});}let J=i.join(p,"AGENTS.md");if(e.existsSync(J)){let t=e.statSync(J),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>60?s.push({name:"AGENTS.md",status:"warn",message:`${n} days since last update \u2014 may be stale`,fix:"paradigm sync"}):s.push({name:"AGENTS.md",status:"ok",message:n>0?`Updated ${n} days ago`:"Fresh"});}}let W=0,z=0,$=0;for(let o of s){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,z++;break;case "error":m="\u2717",c=l.red,W++;break;case "missing":m="\u25CB",c=l.gray,$++;break}if(!w){let v=o.name.padEnd(30);console.log(` ${c(m)} ${v} ${c(o.message)}`),o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let{runContextAudit:Z}=await import('./context-audit-APFKELFT.js'),M=await Z(p,{quiet:w}),O=0,T=0,C=0;!w&&M.length>0&&(console.log(""),console.log(l.blue(" Context Audit")),console.log(l.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));for(let o of M){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,T++;break;case "error":m="\u2717",c=l.red,O++;break;case "advisory":m="\u2139",c=l.cyan,C++;break}if(!w){let v=o.check.padEnd(30);if(console.log(` ${c(m)} ${v} ${c(o.message)}`),o.details&&o.details.length>0){let A=o.details.slice(0,5);for(let q of A)console.log(l.gray(` \u2502 ${q}`));o.details.length>5&&console.log(l.gray(` \u2502 ... and ${o.details.length-5} more`));}o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let b=W+O,j=z+T,D=b+j+$===0;if(!w)if(console.log(""),D)console.log(l.green(`\u2728 All checks passed!
7
+ `));else {let o=[];b>0&&o.push(l.red(`${b} error${b>1?"s":""}`)),j>0&&o.push(l.yellow(`${j} warning${j>1?"s":""}`)),$>0&&o.push(l.gray(`${$} missing`)),C>0&&o.push(l.cyan(`${C} advisor${C>1?"ies":"y"}`)),console.log(`${o.join(", ")} found.
8
+ `),console.log(l.gray(`Run the suggested commands to fix issues.
9
+ `));}if(!w&&P.explain&&!D)try{let{narrateAllGaps:o}=await import('./gap-narrator-DVXPWNFN.js'),m=[];for(let c of s)c.status!=="ok"&&(c.name===".purpose"||c.name.startsWith("Purpose-required")?m.push({type:"missing-purpose",target:c.name,severity:"improvement"}):c.name===".paradigm/scan-index.json"&&c.status==="warn"?m.push({type:"index-stale",target:c.name,severity:"improvement"}):c.name==="Portal compliance"?m.push({type:"portal-mismatch",target:c.name,severity:c.status==="error"?"blocking":"improvement"}):c.name==="Clarification markers"&&m.push({type:"missing-description",target:c.name,severity:"improvement"}));if(m.length>0){let c=o(m);console.log(l.blue(`
10
+ Gap Narrations (--explain)
11
+ `)),console.log(l.gray(c.narrative)),console.log("");}}catch{}return D?I.success("All health checks passed",{total:s.length+M.length}):I.error("Health checks found issues",{errors:b,warnings:j,missing:$,advisories:C}),D}export{rs as a};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1,d,f}from'./chunk-XHJ27CER.js';import*as c from'fs';import*as l from'path';import*as y from'js-yaml';var g,R=b$1(()=>{g={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"]};});var M={};d(M,{getAllStates:()=>ie,getConfig:()=>te,getState:()=>G,incrementFailure:()=>se,invalidateGraduationCache:()=>ae,isGraduated:()=>oe,loadGraduation:()=>p,markNeverGraduate:()=>ne,saveGraduation:()=>H,setTier:()=>re});function A(e){return l.join(e,".paradigm","graduation.yaml")}function p(e){let t=l.resolve(e);if(m&&b===t&&Date.now()-v<ee)return m;let o=A(t),i;if(c.existsSync(o))try{let r=c.readFileSync(o,"utf8");i=y.load(r);}catch{i={version:"1.0",config:{},states:{}};}else i={version:"1.0",config:{},states:{}};return i.version||(i.version="1.0"),i.config||(i.config={}),i.states||(i.states={}),m=i,b=t,v=Date.now(),i}function H(e,t){let o=l.resolve(e),i=A(o),r=l.dirname(i);c.existsSync(r)||c.mkdirSync(r,{recursive:true});let n=y.dump(t,{lineWidth:120,noRefs:true,sortKeys:true});c.writeFileSync(i,n,"utf8"),m=t,b=o,v=Date.now();}function te(e){let t=p(e);return {...g,...t.config,thresholds:{...g.thresholds,...t.config?.thresholds},demotion:{...g.demotion,...t.config?.demotion},neverGraduate:t.config?.neverGraduate??g.neverGraduate}}function w(e){return {habitId:e,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function G(e,t){let i=p(e).states[t];return i?{...w(t),...i,habitId:t}:w(t)}function ie(e){let t=p(e),o={};for(let[i,r]of Object.entries(t.states))o[i]={...w(i),...r,habitId:i};return o}function oe(e,t){return G(e,t).tier==="hook"}function re(e,t,o,i){let r=p(e),n=r.states[t]||{};r.states[t]={...n,tier:o,previousTier:n.tier||"habit",...o==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...o==="habit"&&n.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...i},H(e,r);}function ne(e,t){let o=p(e);o.states[t]||(o.states[t]={}),o.states[t].neverGraduate=true,o.states[t].tier="habit",H(e,o);}function se(e,t){let o=p(e);o.states[t]||(o.states[t]={});let i=(o.states[t].failureCount||0)+1;return o.states[t].failureCount=i,H(e,o),i}function ae(){m=null,b=null,v=0;}var m,b,v,ee,j=b$1(()=>{R();m=null,b=null,v=0,ee=3e4;});var E=[{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:"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:"commit-message-symbols",name:"Commit Message Format",description:"Commit messages should follow type(#symbol): format and include a Symbols: trailer",category:"documentation",trigger:"on-commit",severity:"advisory",check:{type:"commit-message-format",params:{messagePatterns:["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"]}},enabled:true},{id:"flow-coverage-for-multi-component",name:"Flow Coverage",description:"Changes spanning 3+ components should have a documented $flow",category:"documentation",trigger:"postflight",severity:"advisory",check:{type:"flow-coverage",params:{minSteps:3}},enabled:true},{id:"context-session-awareness",name:"Context Awareness",description:"Use session recovery or context check tools for session continuity",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"context-checked",params:{contextTools:["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]}},enabled:true},{id:"aspect-anchors-valid",name:"Aspect Anchors Valid",description:"Aspects touched during the session should have their code anchors validated",category:"verification",trigger:"postflight",severity:"advisory",check:{type:"aspect-anchored",params:{checkAnchors:true}},enabled:true}];var V=E,Y=30*1e3;function K(e){try{let t=l.join(e,".paradigm","config.yaml");if(c.existsSync(t)){let o=c.readFileSync(t,"utf8"),r=y.load(o)?.limits;if(r?.habitsCacheTtlMs&&typeof r.habitsCacheTtlMs=="number")return r.habitsCacheTtlMs}}catch{}return Y}var k=new Map;function z(e){let t=l.resolve(e),o=k.get(t),i=K(t);if(o&&Date.now()-o.loadedAt<i)return o.habits;let r=Q(t);return k.set(t,{habits:r,loadedAt:Date.now()}),r}function Q(e){let t=new Map;for(let s of V)t.set(s.id,{...s});let o=process.env.HOME||process.env.USERPROFILE||"~",i=S(l.join(o,".paradigm","habits.yaml"));i&&D(t,i);let r=T(l.join(o,".paradigm","habits"));for(let s of r)t.set(s.id,s);let n=S(l.join(e,".paradigm","habits.yaml"));n&&D(t,n);let u=T(l.join(e,".paradigm","habits"));for(let s of u)t.set(s.id,s);return Array.from(t.values())}function T(e){if(!c.existsSync(e))return [];try{let t=c.readdirSync(e).filter(i=>i.endsWith(".habit")).sort(),o=[];for(let i of t)try{let r=c.readFileSync(l.join(e,i),"utf8"),n=y.load(r);n?.id&&n?.name&&o.push(n);}catch{}return o}catch{return []}}function S(e){if(!c.existsSync(e))return null;try{let t=c.readFileSync(e,"utf8");return y.load(t)}catch{return null}}function D(e,t){if(t.habits)for(let o of t.habits)e.set(o.id,{...o});if(t.overrides)for(let[o,i]of Object.entries(t.overrides)){let r=e.get(o);r&&J(r,i);}}function J(e,t){t.severity!==void 0&&(e.severity=t.severity),t.enabled!==void 0&&(e.enabled=t.enabled);}function X(e){return e.filter(t=>t.enabled)}function Z(e){let t=l.resolve(e);k.delete(t);}var le=[{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}];function ce(e,t){return e.filter(o=>o.enabled&&o.trigger===t)}new Set(le.map(e=>e.id));function F(e,t,o,i,r){let n=ce(e,t);i&&(n=n.filter(a=>!a.platforms||a.platforms.includes(i)));let u=0;if(r)try{let{isGraduated:a}=(j(),f(M)),O=n.length;n=n.filter(q=>!a(r,q.id)),u=O-n.length;}catch{}let s=n.map(a=>ue(a,o)),W=s.filter(a=>a.result==="followed").length,I=s.filter(a=>a.result==="skipped").length,N=s.filter(a=>a.result==="partial").length,_=s.filter(a=>a.result==="skipped"&&a.habit.severity==="block").length;return {trigger:t,evaluations:s,summary:{total:s.length,followed:W,skipped:I,partial:N,blockingViolations:_},blocksCompletion:_>0}}function $(e){return {toolsCalled:e.toolsCalled||[],filesModified:e.filesModified||[],symbolsTouched:e.symbolsTouched||[],loreRecorded:e.loreRecorded||false,hasPortalRoutes:e.hasPortalRoutes||false,taskAddsRoutes:e.taskAddsRoutes||false,taskDescription:e.taskDescription,gitClean:e.gitClean}}function ue(e,t){switch(e.check.type){case "tool-called":return fe(e,t);case "file-exists":return pe(e,t);case "file-modified":return be(e,t);case "lore-recorded":return ge(e,t);case "symbols-registered":return me(e,t);case "gates-declared":return he(e,t);case "tests-exist":return ye(e,t);case "git-clean":return ve(e,t);case "commit-message-format":return Ce(e,t);case "flow-coverage":return He(e,t);case "context-checked":return ke(e,t);case "aspect-anchored":return we(e,t);default:return {habit:e,result:"partial",reason:`Unknown check: ${e.check.type}`}}}function fe(e,t){let o=e.check.params.tools||[];if(o.length===0)return {habit:e,result:"followed",reason:"No tools required"};let i=o.filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, habit not applicable"}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] were called before modifying code`}}function pe(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};if(t.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:e,result:"followed",reason:"Purpose files updated"};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".yml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/"));return i.length===0?{habit:e,result:"followed",reason:"Only non-source files modified"}:{habit:e,result:"skipped",reason:`${i.length} source file(s) without .purpose updates`,evidence:i.slice(0,5)}}function ge(e,t){let o=t.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 o.length<3?{habit:e,result:"followed",reason:"Session not significant (< 3 source files)"}:t.loreRecorded||t.toolsCalled.includes("paradigm_lore_record")?{habit:e,result:"followed",reason:"Lore recorded"}:{habit:e,result:"skipped",reason:`${o.length} source files modified, no lore entry`,evidence:o.slice(0,5)}}function me(e,t){if(t.symbolsTouched.length===0)return {habit:e,result:"followed",reason:"No symbols touched"};let i=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Purpose tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"partial",reason:`${t.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function he(e,t){if(!t.taskAddsRoutes)return {habit:e,result:"followed",reason:"No routes added"};if(t.hasPortalRoutes)return {habit:e,result:"followed",reason:"Portal.yaml has routes"};let i=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Gate tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:"Routes added without gate declarations"}}function ye(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=t.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(o.length>0)return {habit:e,result:"followed",reason:`Test files: ${o.length}`,evidence:o.slice(0,5)};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/")&&!r.includes("node_modules/"));return i.length===0?{habit:e,result:"followed",reason:"No source files to test"}:{habit:e,result:"partial",reason:`${i.length} source file(s), no test files updated`,evidence:i.slice(0,5)}}function be(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=e.check.params.patterns||[];if(o.length===0)return {habit:e,result:"followed",reason:"No patterns specified"};if(e.trigger==="on-stop"&&e.severity==="block"){let r=t.filesModified.filter(n=>o.some(u=>n.includes(u)||l.basename(n)===u));return r.length>0?{habit:e,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:e,result:"partial",reason:`None of [${o.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let i=t.filesModified.filter(r=>o.some(n=>r.includes(n)||l.basename(r)===n));return i.length>0?{habit:e,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] found in modified files`}}function ve(e,t){return t.filesModified.length===0?{habit:e,result:"followed",reason:"No files modified"}:e.trigger==="on-stop"?{habit:e,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:t.gitClean===void 0?{habit:e,result:"partial",reason:"Git status not available"}:t.gitClean?{habit:e,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:e,result:"skipped",reason:"Uncommitted changes in working tree"}}function Ce(e,t){if(!t.commitMessage)return {habit:e,result:"followed",reason:"No commit message to check (not a commit trigger)"};let o=e.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],i=o.filter(r=>new RegExp(r,"m").test(t.commitMessage));if(i.length===o.length)return {habit:e,result:"followed",reason:"Commit message matches all required patterns",evidence:i};if(i.length>0){let r=o.filter(n=>!new RegExp(n,"m").test(t.commitMessage));return {habit:e,result:"partial",reason:`Matches ${i.length}/${o.length} patterns. Missing: ${r.join(", ")}`}}return {habit:e,result:"skipped",reason:"Commit message does not match required format patterns"}}function He(e,t){let o=t.symbolsTouched.filter(n=>n.startsWith("#"));if(o.length<3)return {habit:e,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(t.hasFlowCoverage)return {habit:e,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_check","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(n=>t.toolsCalled.includes(n));return r.length>0?{habit:e,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:e,result:"skipped",reason:`${o.length} components touched without flow coverage`,evidence:o.slice(0,5)}}function ke(e,t){let i=(e.check.params.contextTools||["paradigm_session_health","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Context tools called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, context check not applicable"}:{habit:e,result:"skipped",reason:"No context/session tools called during session"}}function we(e,t){let o=t.symbolsTouched.filter(i=>i.startsWith("~"));return o.length===0?{habit:e,result:"followed",reason:"No aspects touched"}:t.aspectAnchorsValid===true?{habit:e,result:"followed",reason:"Aspect anchors validated and valid"}:t.toolsCalled.includes("paradigm_aspect_check")?{habit:e,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:e,result:"skipped",reason:`${o.length} aspect(s) touched without anchor validation`,evidence:o.slice(0,5)}}export{z as a,X as b,Z as c,F as d,$ as e};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-JBDMCRPP.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
2
+ import {b}from'./chunk-77WX6HGV.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
3
3
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(e.blue("\u2502")+e.white.bold(" paradigm workspace init ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Create a multi-project workspace ")+e.blue("\u2502")),console.log(e.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
4
  `));let n=a.command("workspace-init").start("Creating workspace",{cwd:c});if(r.existsSync(o)&&!l.force){console.log(e.yellow(` .paradigm-workspace already exists. Use --force to overwrite.
5
5
  `)),n.success("Workspace already exists");return}let s=c,t=r.readdirSync(s,{withFileTypes:true}),a$1=[];for(let p of t){if(!p.isDirectory()||p.name.startsWith(".")||p.name==="node_modules")continue;let g=i.join(s,p.name),k=r.existsSync(i.join(g,".paradigm")),y=r.existsSync(i.join(g,".purpose"));if(k||y){let w=j(p.name,g);a$1.push({name:p.name,path:`./${p.name}`,...w&&{role:w}});}}if(a$1.length===0){console.log(e.yellow(" No sibling projects with .paradigm/ or .purpose found.")),console.log(e.gray(` Create .purpose files in sibling directories first.
@@ -9,9 +9,9 @@ import {e}from'./chunk-JQKKVAAN.js';import*as r from'fs';import*as c from'path';
9
9
  `)}function x(){let e=[];return e.push("## Paradigm Commands"),e.push(""),e.push("| Command | Description |"),e.push("|---------|-------------|"),e.push("| `paradigm init` | Initialize Paradigm in a project |"),e.push("| `paradigm sync` | Regenerate IDE instruction files |"),e.push("| `paradigm index` | Generate scan index |"),e.push("| `paradigm doctor` | Health check |"),e.push("| `paradigm status` | Show project status |"),e.push("| `paradigm watch` | Auto-sync on changes |"),e.push(""),e.push("See `.paradigm/docs/commands.md` for full reference."),e.push(""),e.join(`
10
10
  `)}function ae(e){let s=[];return s.push("## Paradigm Navigation"),s.push(""),s.push("Before exploring this codebase:"),s.push(""),s.push("1. Read `.paradigm/navigator.yaml` for structure map"),s.push("2. Query by symbol - lookup paths directly"),s.push("3. Respect skip patterns (node_modules, dist, etc.)"),s.push(""),s.push("### Exploration Protocol"),s.push(""),s.push("**INSTEAD OF:** Broad exploration (expensive token usage)"),s.push(""),s.push("**DO THIS:**"),s.push("1. Read `.paradigm/navigator.yaml` for structure map"),s.push("2. Find relevant symbol \u2192 go to path"),s.push("3. Read only needed files"),s.push(""),s.push("### Task Recipes"),s.push(""),s.push("**Adding a feature:**"),s.push("1. Check `navigator.yaml` \u2192 `structure.features.paths`"),s.push("2. Read existing feature as template"),s.push("3. Create in same location"),s.push(""),s.push("**Modifying a component:**"),s.push("1. Look up symbol in `navigator.yaml` \u2192 `symbols`"),s.push("2. Go directly to the path"),s.push("3. Check `paradigm_ripple` for impact"),s.push(""),s.push("**Using MCP Tools:**"),s.push('- `paradigm_navigate({ intent: "find", target: "#checkout" })` - locate symbol'),s.push('- `paradigm_navigate({ intent: "explore", target: "auth" })` - browse area'),s.push('- `paradigm_navigate({ intent: "context", task: "add login" })` - task context'),s.push(""),s.push("### PM Governance (Before/After Tasks)"),s.push(""),s.push("| When | Tool | Purpose |"),s.push("|------|------|---------|"),s.push("| Starting any task | `paradigm_pm_preflight` | Get compliance plan, affected symbols, required checks |"),s.push("| Finishing any task | `paradigm_pm_postflight` | Check for violations: missing .purpose, missing gates |"),s.push(""),s.join(`
11
11
  `)}function v(){let e=[];return e.push("## Commit Messages"),e.push(""),e.push("Use v2 symbols in commits for history tracking:"),e.push(""),e.push("### Format"),e.push("```"),e.push("type(#primary-symbol): short description"),e.push(""),e.push("- Detail with #component references"),e.push("- Gate changes: ^gate-name"),e.push("- Signals emitted: !signal-name"),e.push(""),e.push("Symbols: #symbol-a, #symbol-b, !signal-c"),e.push("```"),e.push(""),e.push("### Convention"),e.push("- **Subject**: `type(#symbol): description` \u2014 primary symbol in parens"),e.push("- **Body**: Reference affected symbols with prefixes (# $ ^ ! ~)"),e.push("- **Trailer**: `Symbols: #a, #b, !c` \u2014 machine-readable list of ALL affected symbols"),e.push("- The `Symbols:` trailer is parsed by the post-commit hook for automatic history capture"),e.push(""),e.push("### Examples"),e.push("```"),e.push("feat(#payment-form): add Apple Pay support"),e.push(""),e.push("- Add #apple-pay-button component"),e.push("- Update $checkout-flow with new payment step"),e.push("- Emit !payment-method-added signal"),e.push("- Gate: ^authenticated required"),e.push(""),e.push("Symbols: #payment-form, #apple-pay-button, $checkout-flow, !payment-method-added"),e.push("```"),e.push(""),e.join(`
12
- `)}function ie(){let e=[];return e.push("## MCP Tools"),e.push(""),e.push("Paradigm provides MCP tools for token-efficient, always-fresh data. Prefer these over reading files directly."),e.push(""),e.push("| Tool | Description | When to Use |"),e.push("|------|-------------|-------------|"),e.push("| `paradigm_status` | Project overview and symbol counts | Starting a session |"),e.push("| `paradigm_search` | Find symbols by name, description, or tags | Looking for symbols |"),e.push("| `paradigm_navigate` | Find code locations, explore areas, get task context | Locating code |"),e.push("| `paradigm_ripple` | Dependency and impact analysis | Before modifying symbols |"),e.push("| `paradigm_related` | Direct relationships for a symbol | Understanding connections |"),e.push("| `paradigm_gates_for_route` | Suggest gates for an API endpoint | Adding API routes |"),e.push("| `paradigm_wisdom_context` | Team preferences and antipatterns | Before implementing |"),e.push("| `paradigm_history_fragility` | Stability warnings for symbols | Before modifying fragile areas |"),e.push("| `paradigm_flow_validate` | Validate flow definitions | Before/after implementing flows |"),e.push("| `paradigm_flows_affected` | Flows impacted by symbol changes | After modifying symbols |"),e.push("| `paradigm_test_fixtures` | Get test data for validation | Writing tests |"),e.push("| `paradigm_orchestrate_inline` | Multi-agent task planning | Complex tasks (3+ files) |"),e.push("| `paradigm_pm_preflight` | Pre-task compliance check | Starting any task |"),e.push("| `paradigm_pm_postflight` | Post-task violation detection | Finishing any task |"),e.push("| `paradigm_session_recover` | Load previous session breadcrumbs | Starting a new session |"),e.push("| `paradigm_context_check` | Check context window usage | Every 10-15 tool calls |"),e.push("| `paradigm_handoff_prepare` | Prepare session handoff summary | When context is high |"),e.push("| `paradigm_reindex` | Rebuild static index files | After modifying .purpose files |"),e.push("| `paradigm_session_checkpoint` | Save cognitive-transition checkpoint | Phase transitions |"),e.push("| `paradigm_session_stats` | Current session token usage | Checking budget |"),e.push(""),e.push("**Rule**: Use MCP tools for discovery and validation, file reads for implementation."),e.push(""),e.join(`
13
- `)}function re(){let e=[];return e.push("## Workflow Protocol"),e.push(""),e.push("### Before Each Task"),e.push(""),e.push("1. **Preflight**: Call `paradigm_pm_preflight` with your task description"),e.push(" - Returns affected symbols, ripple analysis, required agents"),e.push("2. **Impact check**: Call `paradigm_ripple` for any symbols you'll modify"),e.push("3. **Gate check**: Call `paradigm_gates_for_route` before adding API endpoints"),e.push('4. **Complex tasks** (3+ files, security + implementation): Call `paradigm_orchestrate_inline` with mode="plan"'),e.push(""),e.push("### After Each Task"),e.push(""),e.push("1. **Postflight**: Call `paradigm_pm_postflight` with modified files and symbols"),e.push(" - Checks for missing .purpose files, unregistered routes, uncaptured wisdom"),e.push("2. **Reindex**: Call `paradigm_reindex` to rebuild static index files"),e.push("3. **Validate flows**: Call `paradigm_flow_validate` if you touched flow-related symbols"),e.push(""),e.join(`
14
- `)}function oe(){let e=[];return e.push("## Session Recovery & Handoff"),e.push(""),e.push("### Session Start (EVERY new session)"),e.push(""),e.push("Call `paradigm_session_recover` to load previous session breadcrumbs."),e.push("Returns: symbols modified, files explored, recent actions, and suggestions."),e.push(""),e.push("### Context Monitoring"),e.push(""),e.push("Call `paradigm_context_check` every 10-15 tool calls to track context usage."),e.push(""),e.push("| Usage | Recommendation | Action |"),e.push("|-------|----------------|--------|"),e.push("| <50% | continue | Keep working |"),e.push("| 50-70% | consider-handoff | Plan handoff; prepare summary when ready |"),e.push("| 70-85% | handoff-recommended | Prepare handoff soon |"),e.push("| >85% | handoff-urgent | Handoff after current task |"),e.push(""),e.push("### Handoff Process"),e.push(""),e.push("1. Call `paradigm_handoff_prepare` with summary, next steps, and target agent"),e.push('2. User runs: `paradigm team handoff --to <agent> --summary "..."`'),e.push("3. New session accepts: `paradigm team accept <handoff-id>`"),e.push(""),e.join(`
12
+ `)}function ie(){let e=[];return e.push("## MCP Tools"),e.push(""),e.push("Paradigm provides MCP tools for token-efficient, always-fresh data. Prefer these over reading files directly."),e.push(""),e.push("| Tool | Description | When to Use |"),e.push("|------|-------------|-------------|"),e.push("| `paradigm_status` | Project overview and symbol counts | Starting a session |"),e.push("| `paradigm_search` | Find symbols by name, description, or tags | Looking for symbols |"),e.push("| `paradigm_navigate` | Find code locations, explore areas, get task context | Locating code |"),e.push("| `paradigm_ripple` | Dependency and impact analysis | Before modifying symbols |"),e.push("| `paradigm_related` | Direct relationships for a symbol | Understanding connections |"),e.push("| `paradigm_gates_for_route` | Suggest gates for an API endpoint | Adding API routes |"),e.push("| `paradigm_wisdom_context` | Team preferences and antipatterns | Before implementing |"),e.push("| `paradigm_history_fragility` | Stability warnings for symbols | Before modifying fragile areas |"),e.push("| `paradigm_flow_check` | Validate flow definitions | Before/after implementing flows |"),e.push("| `paradigm_flows_affected` | Flows impacted by symbol changes | After modifying symbols |"),e.push("| `paradigm_test_fixtures` | Get test data for validation | Writing tests |"),e.push("| `paradigm_orchestrate_inline` | Multi-agent task planning | Complex tasks (3+ files) |"),e.push("| `paradigm_pm_preflight` | Pre-task compliance check | Starting any task |"),e.push("| `paradigm_pm_postflight` | Post-task violation detection | Finishing any task |"),e.push("| `paradigm_session_recover` | Load previous session breadcrumbs | Starting a new session |"),e.push("| `paradigm_session_health` | Check context window usage | Every 10-15 tool calls |"),e.push("| `paradigm_handoff_prepare` | Prepare session handoff summary | When context is high |"),e.push("| `paradigm_reindex` | Rebuild static index files | After modifying .purpose files |"),e.push("| `paradigm_session_checkpoint` | Save cognitive-transition checkpoint | Phase transitions |"),e.push("| `paradigm_session_stats` | Current session token usage | Checking budget |"),e.push(""),e.push("**Rule**: Use MCP tools for discovery and validation, file reads for implementation."),e.push(""),e.join(`
13
+ `)}function re(){let e=[];return e.push("## Workflow Protocol"),e.push(""),e.push("### Before Each Task"),e.push(""),e.push("1. **Preflight**: Call `paradigm_pm_preflight` with your task description"),e.push(" - Returns affected symbols, ripple analysis, required agents"),e.push("2. **Impact check**: Call `paradigm_ripple` for any symbols you'll modify"),e.push("3. **Gate check**: Call `paradigm_gates_for_route` before adding API endpoints"),e.push('4. **Complex tasks** (3+ files, security + implementation): Call `paradigm_orchestrate_inline` with mode="plan"'),e.push(""),e.push("### After Each Task"),e.push(""),e.push("1. **Postflight**: Call `paradigm_pm_postflight` with modified files and symbols"),e.push(" - Checks for missing .purpose files, unregistered routes, uncaptured wisdom"),e.push("2. **Reindex**: Call `paradigm_reindex` to rebuild static index files"),e.push("3. **Validate flows**: Call `paradigm_flow_check` if you touched flow-related symbols"),e.push(""),e.join(`
14
+ `)}function oe(){let e=[];return e.push("## Session Recovery & Handoff"),e.push(""),e.push("### Session Start (EVERY new session)"),e.push(""),e.push("Call `paradigm_session_recover` to load previous session breadcrumbs."),e.push("Returns: symbols modified, files explored, recent actions, and suggestions."),e.push(""),e.push("### Context Monitoring"),e.push(""),e.push("Call `paradigm_session_health` every 10-15 tool calls to track context usage."),e.push(""),e.push("| Usage | Recommendation | Action |"),e.push("|-------|----------------|--------|"),e.push("| <50% | continue | Keep working |"),e.push("| 50-70% | consider-handoff | Plan handoff; prepare summary when ready |"),e.push("| 70-85% | handoff-recommended | Prepare handoff soon |"),e.push("| >85% | handoff-urgent | Handoff after current task |"),e.push(""),e.push("### Handoff Process"),e.push(""),e.push("1. Call `paradigm_handoff_prepare` with summary, next steps, and target agent"),e.push('2. User runs: `paradigm team handoff --to <agent> --summary "..."`'),e.push("3. New session accepts: `paradigm team accept <handoff-id>`"),e.push(""),e.join(`
15
15
  `)}function $(){let e=[];return e.push("## Session Checkpoints"),e.push(""),e.push("**Auto-recovery**: Recovery data is automatically surfaced on your first Paradigm tool call \u2014 no action needed to receive it."),e.push(""),e.push("Save checkpoints when transitioning between workflow phases to enable crash recovery:"),e.push(""),e.push("| Phase | Trigger | What to Capture |"),e.push("|-------|---------|-----------------|"),e.push("| `planning` | After reading requirements / before coding | Plan, approach, key decisions |"),e.push("| `implementing` | After starting code changes | Modified files, symbols touched, decisions made |"),e.push("| `validating` | After implementation, before tests/review | All modified files, test plan |"),e.push("| `complete` | Task finished | Summary, final file list |"),e.push(""),e.push("### Usage"),e.push(""),e.push("```"),e.push("paradigm_session_checkpoint({"),e.push(' phase: "implementing",'),e.push(' context: "Adding JWT auth middleware to /api/projects routes",'),e.push(' modifiedFiles: ["src/middleware/auth.ts", "src/routes/projects.ts"],'),e.push(' symbolsTouched: ["^authenticated", "#project-routes"],'),e.push(' decisions: ["Using RS256 for JWT signing", "Storing refresh tokens in httpOnly cookies"]'),e.push("})"),e.push("```"),e.push(""),e.push("Keep it lightweight: `phase` + `context` are required, everything else is optional."),e.push(""),e.join(`
16
16
  `)}function E(){let e=[];return e.push("## Habits Compliance"),e.push(""),e.push("Paradigm tracks behavioral habits \u2014 repeatable practices that improve code quality."),e.push(""),e.push("### When to Check Habits"),e.push(""),e.push("| Trigger | When | Tool |"),e.push("|---------|------|------|"),e.push('| `preflight` | Before starting implementation | `paradigm_habits_check({ trigger: "preflight" })` |'),e.push('| `postflight` | After completing implementation | `paradigm_habits_check({ trigger: "postflight" })` |'),e.push('| `on-stop` | Before ending a session | `paradigm_habits_check({ trigger: "on-stop" })` |'),e.push(""),e.push("### Key Habit Categories"),e.push(""),e.push("| Category | Examples |"),e.push("|----------|----------|"),e.push("| Discovery | Call `paradigm_ripple` before modifying symbols |"),e.push("| Security | Declare gates for new routes in portal.yaml |"),e.push("| Documentation | Update .purpose files for modified components |"),e.push("| Quality | Record lore for sessions modifying 3+ files |"),e.push(""),e.push("Use `paradigm_practice_context` before modifying symbols to get habit-aware warnings."),e.push(""),e.join(`
17
17
  `)}function D(){let e=[];return e.push("## Lore Recording"),e.push(""),e.push("Lore captures the project timeline \u2014 sessions, decisions, milestones, and incidents."),e.push(""),e.push("### When to Record Lore"),e.push(""),e.push("| Type | When | Example |"),e.push("|------|------|---------|"),e.push('| `agent-session` | After modifying 3+ files | "Added JWT auth to /api/projects" |'),e.push('| `decision` | After making architectural choices | "Chose Redis over Memcached for caching" |'),e.push('| `milestone` | After completing a significant feature | "v2.0 migration complete" |'),e.push('| `incident` | After resolving a production issue | "Fixed OOM in payment worker" |'),e.push(""),e.push("### Recording"),e.push(""),e.push("```"),e.push("paradigm_lore_record({"),e.push(' type: "agent-session",'),e.push(' title: "Short description of work done",'),e.push(' summary: "Detailed summary of changes...",'),e.push(' symbols_touched: ["#component", "^gate"]'),e.push("})"),e.push("```"),e.push(""),e.push("Use `paradigm_lore_timeline` at session start for project history orientation."),e.push(""),e.join(`
@@ -235,7 +235,7 @@ Always available in \`navigator.yaml\`:
235
235
  - \`key_files.config\` - Configuration files
236
236
  - \`key_files.entry\` - Entry points
237
237
  - \`key_files.types\` - Type definitions
238
- `}generateContextMdc(){return g("Session recovery and handoff - call paradigm_session_recover at session start, paradigm_context_check periodically during long sessions, paradigm_handoff_prepare when context is high.")+`# Context Monitoring Protocol
238
+ `}generateContextMdc(){return g("Session recovery and handoff - call paradigm_session_recover at session start, paradigm_session_health periodically during long sessions, paradigm_handoff_prepare when context is high.")+`# Context Monitoring Protocol
239
239
 
240
240
  ## Session Start (EVERY new session)
241
241
 
@@ -247,7 +247,7 @@ Returns: symbols modified, files explored, recent actions, and suggestions.
247
247
  **Every 10-15 tool calls** (or when user asks about context), call:
248
248
 
249
249
  \`\`\`
250
- paradigm_context_check()
250
+ paradigm_session_health()
251
251
  \`\`\`
252
252
 
253
253
  This returns a recommendation: \`continue\`, \`consider-handoff\`, \`handoff-recommended\`, or \`handoff-urgent\`.
@@ -495,7 +495,7 @@ flows:
495
495
 
496
496
  2. **Validate before implementing:**
497
497
  \`\`\`
498
- paradigm_flow_validate({ flowId: "$task-creation" })
498
+ paradigm_flow_check({ flowId: "$task-creation" })
499
499
  \`\`\`
500
500
  - Ensures all gates are declared in portal.yaml
501
501
  - Checks for missing symbols
@@ -508,14 +508,14 @@ flows:
508
508
 
509
509
  ## Flow Validation
510
510
 
511
- Call \`paradigm_flow_validate\` to check flows:
511
+ Call \`paradigm_flow_check\` to check flows:
512
512
 
513
513
  \`\`\`
514
514
  // Validate specific flow
515
- paradigm_flow_validate({ flowId: "$task-creation" })
515
+ paradigm_flow_check({ flowId: "$task-creation" })
516
516
 
517
517
  // Validate all flows
518
- paradigm_flow_validate({ checkImplementation: true })
518
+ paradigm_flow_check({ checkImplementation: true })
519
519
  \`\`\`
520
520
 
521
521
  **What gets checked:**
@@ -543,7 +543,7 @@ paradigm_flow_validate({ checkImplementation: true })
543
543
 
544
544
  | Tool | Purpose |
545
545
  |------|---------|
546
- | \`paradigm_flow_validate\` | Validate flow definitions |
546
+ | \`paradigm_flow_check\` | Validate flow definitions |
547
547
  | \`paradigm_flows_affected\` | Check which flows are impacted by symbol changes |
548
548
 
549
549
  ## CLI Commands
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {c,a,e}from'./chunk-XHJ27CER.js';var y=c((q,d)=>{var l=Object.defineProperty,S=Object.getOwnPropertyDescriptor,L=Object.getOwnPropertyNames,$=Object.prototype.hasOwnProperty,P=(t,r)=>{for(var e in r)l(t,e,{get:r[e],enumerable:true});},D=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of L(r))!$.call(t,s)&&s!==e&&l(t,s,{get:()=>r[s],enumerable:!(o=S(r,s))||o.enumerable});return t},T=t=>D(l({},"__esModule",{value:true}),t),h={};P(h,{ParadigmLogger:()=>g,createCorrelationId:()=>A,log:()=>U,withCorrelation:()=>M});d.exports=T(h);var x={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},E="\x1B[1m",c="\x1B[0m";function I(){let t=new Date,r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return `${r}:${e}:${o}.${s}`}function j(t){return !t||Object.keys(t).length===0?"":" "+JSON.stringify(t)}function C(t,r,e,o,s,i){let n=x[t],a=t.toUpperCase().padEnd(5),b=I(),w=j(i?{correlationId:i,...s}:s);return `${n}${b}${c} ${E}${r}${c} ${n}${a}${c} ${o}${w}`}function F(t,r,e,o,s,i){let n={timestamp:new Date().toISOString(),level:t,symbol:r,symbolType:e,message:o,...s};return i&&(n.correlationId=i),JSON.stringify(n)}var B=a("async_hooks"),N=a("crypto"),f=new B.AsyncLocalStorage;function A(){return (0, N.randomUUID)()}function M(t,r){return f.run(t,r)}function R(){return f.getStore()}var u={debug:0,info:1,warn:2,error:3};function V(){let t=typeof process<"u"?process.env:{},r=t.LOG_LEVEL;return r&&u[r]!==void 0?r:t.NODE_ENV==="production"?"info":"debug"}function k(){let t=typeof process<"u"?process.env:{};return t.PARADIGM_LOG_FORMAT==="json"||t.NODE_ENV==="production"?"json":"pretty"}function G(){let r=(typeof process<"u"?process.env:{}).PARADIGM_SYMBOLS;return r?r.split(",").map(e=>e.trim()).filter(Boolean):null}var J=class{constructor(t){this.emit=t,this.startTime=Date.now();}startTime;success(t,r){this.end("info",t,r);}error(t,r){this.end("error",t,r);}end(t,r,e){let o=Date.now()-this.startTime;this.emit(t,r,{...e,duration:`${o}ms`});}},m=class{constructor(t,r,e,o,s,i,n=[]){this.symbol=t,this.symbolType=r,this.minLevel=e,this.symbolFilter=o,this.format=s,this.output=i,this.transports=n;}debug(t,r){this.emit("debug",t,r);}info(t,r){this.emit("info",t,r);}warn(t,r){this.emit("warn",t,r);}error(t,r){this.emit("error",t,r);}start(t,r){return this.emit("info",t,r),new J((e,o,s)=>this.emit(e,o,s))}emit(t,r,e){if(u[t]<u[this.minLevel])return;if(this.symbolFilter){let n=this.symbol.charAt(0);if(!this.symbolFilter.includes(n))return}let o=R(),i=(this.format==="json"?F:C)(t,this.symbol,this.symbolType,r,e,o);if(this.output(i),this.transports.length>0){let n={level:t,symbol:this.symbol,symbolType:this.symbolType,message:r,data:e,correlationId:o,timestamp:new Date().toISOString()};for(let a of this.transports)a.send(n);}}},g=class{level;symbolFilter;format;output;transports;constructor(t){this.level=t?.level??V(),this.symbolFilter=t?.symbols??G(),this.format=t?.format??k(),this.output=t?.output??(r=>console.log(r)),this.transports=t?.transports??[];}addTransport(t){this.transports.push(t);}removeTransport(t){let r=this.transports.indexOf(t);r!==-1&&this.transports.splice(r,1);}component(t){return this.create(t,"component","#")}gate(t){return this.create(t,"gate","^")}signal(t){return this.create(t,"signal","!")}flow(t){return this.create(t,"flow","$")}aspect(t){return this.create(t,"aspect","~")}raw(t){return new m(t,"raw",this.level,this.symbolFilter,this.format,this.output,this.transports)}create(t,r,e){let o=t.startsWith(e)?t:`${e}${t}`;return new m(o,r,this.level,this.symbolFilter,this.format,this.output,this.transports)}},U=new g;});var v=e(y(),1),W=new v.ParadigmLogger({output:t=>process.stderr.write(t+`
3
+ `)});export{W as a};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b}from'./chunk-XHJ27CER.js';var n,r,t=b(()=>{n=["gap_narrations","cost_data","health_status","execution_metrics"],r={version:"1.0",default_ring:"project-locked",observation:{allow:["src/**",".paradigm/**","portal.yaml"],deny:[".env*","**/*.key","**/*.pem","**/secrets/**"]},streams:{work_log:{ring:"project-locked",allow_content:["file_paths","symbol_names","outcome"],deny_content:["code_snippets","file_contents","diff_content","gap_narrations"]},learning_journal:{ring:"user-scoped",allow_content:["pattern_descriptions","confidence_adjustments","approach_descriptions"],deny_content:["code_snippets","file_contents","symbol_names_with_context","gap_narrations","cost_data","health_status","execution_metrics"],redaction:[{pattern:"\\b[A-Z_]{2,}_KEY\\b"},{pattern:"password|secret|token"}]},team_decisions:{ring:"project-locked",allow_content:["rationale","alternatives","symbol_references"],deny_content:["implementation_details","gap_narrations","cost_data","health_status","execution_metrics"]}},upstream:{ring:"creator-upstream",allowed:["task_type","outcome","helpfulness","duration_bucket","error_category"],denied:["code_of_any_kind","file_paths","symbol_names","conversation_content","user_identity"]},network:{ring:"network-public",opt_in:false,if_opted_in:["aggregated_task_success_rates","anonymized_pattern_frequency"]}};});export{n as a,r as b,t as c};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import {c,a,b,e}from'./chunk-XHJ27CER.js';var y=c((z,d)=>{var l=Object.defineProperty,L=Object.getOwnPropertyDescriptor,$=Object.getOwnPropertyNames,P=Object.prototype.hasOwnProperty,D=(t,r)=>{for(var e in r)l(t,e,{get:r[e],enumerable:true});},T=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of $(r))!P.call(t,s)&&s!==e&&l(t,s,{get:()=>r[s],enumerable:!(o=L(r,s))||o.enumerable});return t},x=t=>T(l({},"__esModule",{value:true}),t),h={};D(h,{ParadigmLogger:()=>g,createCorrelationId:()=>M,log:()=>q,withCorrelation:()=>R});d.exports=x(h);var E={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},I="\x1B[1m",c="\x1B[0m";function j(){let t=new Date,r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return `${r}:${e}:${o}.${s}`}function C(t){return !t||Object.keys(t).length===0?"":" "+JSON.stringify(t)}function F(t,r,e,o,s,i){let n=E[t],a=t.toUpperCase().padEnd(5),b=j(),w=C(i?{correlationId:i,...s}:s);return `${n}${b}${c} ${I}${r}${c} ${n}${a}${c} ${o}${w}`}function B(t,r,e,o,s,i){let n={timestamp:new Date().toISOString(),level:t,symbol:r,symbolType:e,message:o,...s};return i&&(n.correlationId=i),JSON.stringify(n)}var N=a("async_hooks"),A=a("crypto"),f=new N.AsyncLocalStorage;function M(){return (0, A.randomUUID)()}function R(t,r){return f.run(t,r)}function V(){return f.getStore()}var u={debug:0,info:1,warn:2,error:3};function k(){let t=typeof process<"u"?process.env:{},r=t.LOG_LEVEL;return r&&u[r]!==void 0?r:t.NODE_ENV==="production"?"info":"debug"}function G(){let t=typeof process<"u"?process.env:{};return t.PARADIGM_LOG_FORMAT==="json"||t.NODE_ENV==="production"?"json":"pretty"}function J(){let r=(typeof process<"u"?process.env:{}).PARADIGM_SYMBOLS;return r?r.split(",").map(e=>e.trim()).filter(Boolean):null}var U=class{constructor(t){this.emit=t,this.startTime=Date.now();}startTime;success(t,r){this.end("info",t,r);}error(t,r){this.end("error",t,r);}end(t,r,e){let o=Date.now()-this.startTime;this.emit(t,r,{...e,duration:`${o}ms`});}},m=class{constructor(t,r,e,o,s,i,n=[]){this.symbol=t,this.symbolType=r,this.minLevel=e,this.symbolFilter=o,this.format=s,this.output=i,this.transports=n;}debug(t,r){this.emit("debug",t,r);}info(t,r){this.emit("info",t,r);}warn(t,r){this.emit("warn",t,r);}error(t,r){this.emit("error",t,r);}start(t,r){return this.emit("info",t,r),new U((e,o,s)=>this.emit(e,o,s))}emit(t,r,e){if(u[t]<u[this.minLevel])return;if(this.symbolFilter){let n=this.symbol.charAt(0);if(!this.symbolFilter.includes(n))return}let o=V(),i=(this.format==="json"?B:F)(t,this.symbol,this.symbolType,r,e,o);if(this.output(i),this.transports.length>0){let n={level:t,symbol:this.symbol,symbolType:this.symbolType,message:r,data:e,correlationId:o,timestamp:new Date().toISOString()};for(let a of this.transports)a.send(n);}}},g=class{level;symbolFilter;format;output;transports;constructor(t){this.level=t?.level??k(),this.symbolFilter=t?.symbols??J(),this.format=t?.format??G(),this.output=t?.output??(r=>console.log(r)),this.transports=t?.transports??[];}addTransport(t){this.transports.push(t);}removeTransport(t){let r=this.transports.indexOf(t);r!==-1&&this.transports.splice(r,1);}component(t){return this.create(t,"component","#")}gate(t){return this.create(t,"gate","^")}signal(t){return this.create(t,"signal","!")}flow(t){return this.create(t,"flow","$")}aspect(t){return this.create(t,"aspect","~")}raw(t){return new m(t,"raw",this.level,this.symbolFilter,this.format,this.output,this.transports)}create(t,r,e){let o=t.startsWith(e)?t:`${e}${t}`;return new m(o,r,this.level,this.symbolFilter,this.format,this.output,this.transports)}},q=new g;});var v,Q,Y=b(()=>{v=e(y(),1),Q=new v.ParadigmLogger({output:t=>process.stderr.write(t+`
3
+ `)});});export{Q as a,Y as b};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import {c,a}from'./chunk-EMMMBAID.js';import {b as b$1,a as a$1}from'./chunk-F5BSUC2L.js';import*as s from'fs';import*as o from'path';import*as v from'os';import*as d from'crypto';c();b$1();function $(t){return t.contentType!==void 0&&a.includes(t.contentType)}function ct(t,n,e){try{let r={id:d.randomUUID(),timestamp:new Date().toISOString(),agent:t,boundary:e,data_category:n.contentType,action:"blocked",destination_ring:"network-public",details:n.id},i=o.join(v.homedir(),".paradigm","events","audit-ring1.jsonl");I(i,r);}catch(r){a$1.component("#symphony-loader").warn(`Ring 1 audit write failed: ${r}`);}}var g=o.join(v.homedir(),".paradigm","score"),N=o.join(v.homedir(),".paradigm","mail"),h=o.join(g,"agents"),S=o.join(g,"threads"),m=o.join(g,"file-requests"),E=o.join(g,"trust.yaml"),X=3600*1e3,b={users:{},defaults:{level:"restricted",autoApprove:[],neverApprove:[".env*","**/*.key","**/*.pem","**/credentials*","**/secrets/**"]}};function tt(){if(s.existsSync(N)&&!s.existsSync(g))try{s.renameSync(N,g);}catch{}}function p(){tt();for(let t of [h,S,m])s.existsSync(t)||s.mkdirSync(t,{recursive:true});}var ut=p;function f(t){return o.join(h,t)}function R(t){let n=f(t);return s.existsSync(n)||s.mkdirSync(n,{recursive:true}),n}function x(t){if(!s.existsSync(t))return [];let e=s.readFileSync(t,"utf-8").split(`
3
+ `).filter(i=>i.trim().length>0),r=[];for(let i of e)try{r.push(JSON.parse(i));}catch{}return r}function I(t,n){let e=o.dirname(t);s.existsSync(e)||s.mkdirSync(e,{recursive:true}),s.appendFileSync(t,JSON.stringify(n)+`
4
+ `,"utf-8");}function C(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"unknown"}function _(t){try{let n=o.join(t,".paradigm","config.yaml");if(s.existsSync(n)){let r=s.readFileSync(n,"utf-8").match(/^project:\s*(.+)$/m);if(r)return C(r[1].trim().replace(/["']/g,""))}}catch{}return C(o.basename(t))}function z(t,n){return `${_(t)}/${n||"core"}`}function ft(t,n,e){p();let r=z(t,n),i=R(r),a=_(t),c={id:r,name:e||`${a} (${n||"core"})`,type:"agent",project:a,role:n||"core",pid:process.pid,startedAt:new Date().toISOString(),label:e};return s.writeFileSync(o.join(i,"identity.json"),JSON.stringify(c,null,2),"utf-8"),c}function et(t){let n=f(t);if(!s.existsSync(n))return false;try{return s.rmSync(n,{recursive:!0,force:!0}),!0}catch{return false}}function P(){if(p(),!s.existsSync(h))return [];let t=[],n=s.readdirSync(h,{withFileTypes:true}).filter(e=>e.isDirectory());for(let e of n){let r=o.join(h,e.name),i=s.readdirSync(r,{withFileTypes:true}).filter(a=>a.isDirectory());for(let a of i){let c=o.join(r,a.name,"identity.json");if(s.existsSync(c))try{let u=s.readFileSync(c,"utf-8"),l=JSON.parse(u);t.push(l);}catch{}}}return t}function lt(){let t=P(),n=0;for(let e of t)F(e.pid)||(et(e.id),n++);return n}function dt(t){let n=z(t),e=o.join(f(n),"identity.json");if(!s.existsSync(e))return null;try{return JSON.parse(s.readFileSync(e,"utf-8"))}catch{return null}}function pt(t,n){let e=o.join(f(t),"identity.json");if(s.existsSync(e))try{let r=JSON.parse(s.readFileSync(e,"utf-8"));r.lastPoll=new Date().toISOString(),n!==void 0&&(r.statusBlurb=n||void 0),s.writeFileSync(e,JSON.stringify(r,null,2),"utf-8");}catch{}}function gt(t,n){let e=o.join(f(t),"identity.json");if(s.existsSync(e))try{let r=JSON.parse(s.readFileSync(e,"utf-8"));r.statusBlurb=n||void 0,s.writeFileSync(e,JSON.stringify(r,null,2),"utf-8");}catch{}}function yt(t,n=6e4){if(!t.lastPoll)return true;let e=new Date(t.lastPoll).getTime();return Date.now()-e>n}function ht(){let n=P().filter(e=>F(e.pid));try{let e=o.join(v.homedir(),".conductor","sessions");if(s.existsSync(e)){let r=s.readdirSync(e).filter(i=>i.endsWith(".json"));for(let i of r)try{let a=s.readFileSync(o.join(e,i),"utf-8"),c=JSON.parse(a),u=parseInt(o.basename(i,".json"),10);!n.some(l=>l.pid===u)&&F(u)&&n.push({id:`conductor/${u}`,name:c.label||`Session ${u}`,type:"agent",project:c.projectDir?o.basename(c.projectDir):"unknown",role:"conductor",pid:u,startedAt:c.registeredAt||new Date().toISOString()});}catch{}}}catch{}return n}function y(t){return o.join(f(t),"inbox.jsonl")}function j(t){return o.join(f(t),"outbox.jsonl")}function B(t){return o.join(f(t),"ack.json")}function St(t){let n=y(t);if(!s.existsSync(n))return {hasNew:false,inboxSize:0};let r=s.statSync(n).size;if(!k(t))return {hasNew:r>0,inboxSize:r};let a=o.join(f(t),"ack-size.json");if(s.existsSync(a))try{let c=JSON.parse(s.readFileSync(a,"utf-8"));return {hasNew:r>(c.size||0),inboxSize:r}}catch{}return {hasNew:r>0,inboxSize:r}}function mt(t){let n=y(t),e=o.join(f(t),"ack-size.json");try{let r=s.existsSync(n)?s.statSync(n).size:0;R(t),s.writeFileSync(e,JSON.stringify({size:r}),"utf-8");}catch{}}function J(t,n){R(t),I(y(t),n);}function xt(t,n){let e=x(y(t));if(!n){let i=k(t);if(i){let a=e.findIndex(c=>c.id===i);if(a>=0)return e.slice(a+1)}return e}let r=e.findIndex(i=>i.id===n);return r>=0?e.slice(r+1):e}function nt(t,n){R(t),I(j(t),n);}function rt(t){return x(j(t))}function vt(t){return rt(t).filter(n=>!$(n))}function Rt(t,n){let e=B(t);R(t),s.writeFileSync(e,JSON.stringify({lastAck:n}),"utf-8");}function k(t){let n=B(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8")).lastAck||null}catch{return null}}function At(t){let n=k(t);if(!n)return 0;let e=y(t),r=x(e),i=r.findIndex(u=>u.id===n);if(i<0)return 0;let a=r.slice(i+1),c=r.length-a.length;return a.length===0?s.existsSync(e)&&s.writeFileSync(e,"","utf-8"):s.writeFileSync(e,a.map(u=>JSON.stringify(u)).join(`
5
+ `)+`
6
+ `,"utf-8"),c}function q(t){return o.join(S,`${t}.json`)}function Tt(t,n){p();let e="thr-"+d.randomBytes(4).toString("hex"),r=new Date().toISOString(),i={id:e,topic:t,initiator:n,participants:[n],status:"active",createdAt:r,lastActivity:r,messageCount:0};return s.writeFileSync(q(e),JSON.stringify(i,null,2),"utf-8"),i}function L(t){let n=q(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function Pt(t){if(p(),!s.existsSync(S))return [];let n=s.readdirSync(S).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(o.join(S,r),"utf-8"),a=JSON.parse(i);(!t||a.status===t)&&e.push(a);}catch{}return e.sort((r,i)=>i.lastActivity.localeCompare(r.lastActivity))}function U(t,n){let e=L(t);if(!e)return false;let r={...e,...n};return s.writeFileSync(q(t),JSON.stringify(r,null,2),"utf-8"),true}function bt(t,n){return U(t,{status:"resolved",resolvedAt:new Date().toISOString(),decision:n})}function Ft(t){let n=P(),e=[];for(let r of n){let i=x(y(r.id)),a=x(j(r.id));for(let c of [...i,...a])(c.threadRoot===t||c.id===t)&&!e.some(u=>u.id===c.id)&&!$(c)&&e.push(c);}return e.sort((r,i)=>r.timestamp.localeCompare(i.timestamp))}function G(t){return {id:d.randomUUID(),parentId:t.parentId,threadRoot:t.threadRoot,timestamp:new Date().toISOString(),sender:t.sender,recipients:t.recipients,intent:t.intent,content:{text:t.text,diff:t.diff,decision:t.decision},symbols:t.symbols||[],attachments:t.attachments,metadata:t.metadata}}function W(t){p(),nt(t.sender.id,t);let n=0;if(t.recipients&&t.recipients.length>0)for(let e of t.recipients)J(e.id,t),n++;else {let e=P();for(let r of e)r.id!==t.sender.id&&(J(r.id,t),n++);}if(t.threadRoot){let e=L(t.threadRoot);if(e){let i=e.participants.some(a=>a.id===t.sender.id)?e.participants:[...e.participants,t.sender];U(t.threadRoot,{participants:i,lastActivity:t.timestamp,messageCount:e.messageCount+1});}}return n}function A(t){return o.join(m,`${t}.json`)}function H(){if(!s.existsSync(E))return b;try{let t=s.readFileSync(E,"utf-8");try{return JSON.parse(t)}catch{return b}}catch{return b}}function It(t){p();let n="freq-"+d.randomBytes(4).toString("hex"),e={request:{requestId:n,filePath:t.filePath,reason:t.reason,requester:t.requester,urgency:t.urgency||"normal",snippet:t.snippet,threadRoot:t.threadRoot},status:"pending",createdAt:new Date().toISOString()};return s.writeFileSync(A(n),JSON.stringify(e,null,2),"utf-8"),e}function K(t){let n=A(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function st(t){if(p(),!s.existsSync(m))return [];let n=s.readdirSync(m).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(o.join(m,r),"utf-8"),a=JSON.parse(i);(!t||a.status===t)&&e.push(a);}catch{}return e.sort((r,i)=>i.createdAt.localeCompare(r.createdAt))}function jt(t,n,e){let r=K(t);if(!r)return {success:false,error:`File request not found: ${t}`};if(r.status!=="pending")return {success:false,error:`Request already ${r.status}`};let i=o.resolve(n,r.request.filePath);if(!i.startsWith(o.resolve(n)))return {success:false,error:"File path escapes project directory"};if(!s.existsSync(i))return {success:false,error:`File not found: ${r.request.filePath}`};try{let a=s.readFileSync(i,"utf-8"),c="utf8";if(e){let Y=[/(?:api[_-]?key|secret|token|password|credential|auth)\s*[:=]/i,/(?:^|\s)(?:export\s+)?[A-Z_]+(?:KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL)\s*=/,/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/];a=a.split(`
7
+ `).map(O=>{for(let Q of Y)if(Q.test(O))return "[REDACTED]";return O}).join(`
8
+ `);}let u=d.createHash("sha256").update(a).digest("hex"),l={requestId:t,filePath:r.request.filePath,content:a,encoding:c,size:Buffer.byteLength(a),hash:u};r.status="approved",r.resolvedAt=new Date().toISOString(),r.delivery=l,s.writeFileSync(A(t),JSON.stringify(r,null,2),"utf-8");let M=G({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[r.request.requester],intent:"fileDelivery",text:`File delivered: ${r.request.filePath} (${l.size} bytes, SHA-256: ${u.slice(0,12)}...)`,threadRoot:r.request.threadRoot,symbols:[]});return M.attachments=[{name:o.basename(r.request.filePath),type:"file",content:l.content,encoding:l.encoding}],W(M),{success:!0,delivery:l}}catch(a){return {success:false,error:`Failed to read file: ${a.message}`}}}function kt(t,n){let e=K(t);if(!e||e.status!=="pending")return false;e.status="denied",e.resolvedAt=new Date().toISOString(),e.denyReason=n,s.writeFileSync(A(t),JSON.stringify(e,null,2),"utf-8");let r=G({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[e.request.requester],intent:"fileDenied",text:`File request denied: ${e.request.filePath}${n?` \u2014 ${n}`:""}`,threadRoot:e.request.threadRoot,symbols:[]});return W(r),true}function T(t,n){let e=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\{\{GLOBSTAR\}\}/g,".*");return new RegExp(`^${e}$`).test(t)}function it(t,n,e){let r=n||H();if(e&&r.users[e]){for(let i of r.users[e].neverApprove)if(T(t,i))return true}for(let i of r.defaults.neverApprove)if(T(t,i))return true;return false}function qt(t,n,e){let r=n||H();if(it(t,r,e))return false;if(e&&r.users[e]){for(let i of r.users[e].autoApprove)if(T(t,i))return true}for(let i of r.defaults.autoApprove)if(T(t,i))return true;return false}function Mt(){let t=st("pending"),n=0;for(let e of t)Date.now()-new Date(e.createdAt).getTime()>X&&(e.status="expired",e.resolvedAt=new Date().toISOString(),s.writeFileSync(A(e.request.requestId),JSON.stringify(e,null,2),"utf-8"),n++);return n}function F(t){try{return process.kill(t,0),!0}catch{return false}}export{k as A,At as B,Tt as C,L as D,Pt as E,U as F,bt as G,Ft as H,G as I,W as J,H as K,It as L,K as M,st as N,jt as O,kt as P,it as Q,qt as R,Mt as S,$ as a,ct as b,g as c,p as d,ut as e,f,x as g,I as h,z as i,ft as j,et as k,P as l,lt as m,dt as n,pt as o,gt as p,yt as q,ht as r,St as s,mt as t,J as u,xt as v,nt as w,rt as x,vt as y,Rt as z};