@a-company/paradigm 5.34.0 → 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 (223) 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-E7LDKJ4O.js +33 -0
  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-4NSPAQDJ.js +35 -0
  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-GE3GQALR.js +2 -0
  34. package/dist/chunk-IW5K3RNR.js +8 -0
  35. package/dist/chunk-JIF7OSGH.js +8 -0
  36. package/dist/{chunk-HPAHK4AJ.js → chunk-JUOOVKK6.js} +1 -1
  37. package/dist/chunk-NFQLONFY.js +3 -0
  38. package/dist/chunk-OVDYPOHR.js +2 -0
  39. package/dist/{chunk-33LKBMVK.js → chunk-RLJ5K3J5.js} +1 -1
  40. package/dist/{chunk-HXGYVS2N.js → chunk-RN35IVA2.js} +1 -1
  41. package/dist/{chunk-ODVKPZZ4.js → chunk-W6WVJLHO.js} +1 -1
  42. package/dist/chunk-X54WXWCX.js +111 -0
  43. package/dist/chunk-XHJ27CER.js +2 -0
  44. package/dist/{chunk-32RBX5YV.js → chunk-XNB4TZTD.js} +1 -1
  45. package/dist/chunk-YG5G5GEQ.js +456 -0
  46. package/dist/chunk-Z72SDTBJ.js +3 -0
  47. package/dist/{claude-4LR3LJQZ.js → claude-OX54QSLC.js} +1 -1
  48. package/dist/{claude-cli-UP6HGH7C.js → claude-cli-FHLJQVJC.js} +1 -1
  49. package/dist/{claude-code-RLJ4GX77.js → claude-code-GVGU3A3B.js} +1 -1
  50. package/dist/{claude-code-teams-R37HJY3Y.js → claude-code-teams-ZRHPTGPP.js} +1 -1
  51. package/dist/{compliance-Q676YALK.js → compliance-PHSPVYK2.js} +3 -3
  52. package/dist/{compliance-health-JNP3P35P.js → compliance-health-HCZTJDN7.js} +1 -1
  53. package/dist/{conductor-Y5IXELTL.js → conductor-LYBMM66Z.js} +1 -1
  54. package/dist/{config-schema-GUQY2QN7.js → config-schema-URJW6UZH.js} +1 -1
  55. package/dist/{constellation-CG7C4WFE.js → constellation-PX3ZKMWQ.js} +1 -1
  56. package/dist/{context-audit-XRPT3OU2.js → context-audit-APFKELFT.js} +2 -2
  57. package/dist/{cost-IDNVMAEV.js → cost-B5SAHPOJ.js} +1 -1
  58. package/dist/{cost-PK4KIF7R.js → cost-MMWUDGZC.js} +1 -1
  59. package/dist/{cursor-cli-QKF7Z6M2.js → cursor-cli-Q2HLQ5TE.js} +1 -1
  60. package/dist/{cursorrules-U5O4G5T4.js → cursorrules-3BW6K6D5.js} +1 -1
  61. package/dist/{decision-loader-2XPZE4EZ.js → decision-loader-4KMQVAXZ.js} +1 -1
  62. package/dist/{delete-P5VULXR4.js → delete-7PQZUERZ.js} +1 -1
  63. package/dist/{diff-QHQWLM3L.js → diff-F2HUO2H3.js} +1 -1
  64. package/dist/{discipline-H7LDI6NT.js → discipline-ARFFIXQL.js} +1 -1
  65. package/dist/{dist-W3XCATBJ.js → dist-5IUWRFG6.js} +1 -1
  66. package/dist/{dist-KGRCLBJP-2QAPFYNF.js → dist-KGRCLBJP-R5CCPPXN.js} +1 -1
  67. package/dist/{dist-3ZCH25SG.js → dist-MRZDZ5SX.js} +1 -1
  68. package/dist/{dist-VGFSP3XM.js → dist-OKM6BXTH.js} +1 -1
  69. package/dist/{dist-VXCZWVVJ.js → dist-VWC6FA46.js} +1 -1
  70. package/dist/dist-YUXXIXB3.js +3 -0
  71. package/dist/{docs-EDQ2STFK.js → docs-6WOQILZS.js} +1 -1
  72. package/dist/{docs-5BX2YWYK.js → docs-BI2DO7B2.js} +2 -2
  73. package/dist/doctor-JLTCBMS4.js +2 -0
  74. package/dist/{drift-ILZE5BFJ.js → drift-6QPDKKUO.js} +1 -1
  75. package/dist/{echo-UPTQUEDU.js → echo-3JJDKCNF.js} +1 -1
  76. package/dist/{edit-GUU3HBVW.js → edit-PLCGL5OV.js} +1 -1
  77. package/dist/{enforcement-BEGPQIUN.js → enforcement-5MHSQAXE.js} +1 -1
  78. package/dist/{enforcement-46XWPNSA.js → enforcement-IWABOHMY.js} +1 -1
  79. package/dist/{event-Y3VXC2RV.js → event-5J3GBWKT.js} +1 -1
  80. package/dist/{explain-files-3GPZUETV.js → explain-files-LPHTJL4N.js} +1 -1
  81. package/dist/{export-CV5KCTPS.js → export-NXUFTFPW.js} +1 -1
  82. package/dist/{flow-POQP27WA.js → flow-IT2IVXXT.js} +1 -1
  83. package/dist/{gap-narrator-NTXLUI7I.js → gap-narrator-DVXPWNFN.js} +1 -1
  84. package/dist/{global-C44FW4G2.js → global-J2VTYKCC.js} +1 -1
  85. package/dist/{graduate-3BBSC27A.js → graduate-N2HF4JT6.js} +1 -1
  86. package/dist/graph-VLMP6DW2.js +2 -0
  87. package/dist/{graph-server-COZR5C3Z.js → graph-server-TBHHBFOM.js} +1 -1
  88. package/dist/{habits-GICVMTJL.js → habits-JTMWGVPH.js} +3 -3
  89. package/dist/{history-UW454SDP.js → history-FHS7EC3Z.js} +1 -1
  90. package/dist/{hooks-BNWRGACA.js → hooks-BL6CXRVK.js} +1 -1
  91. package/dist/index.js +9 -9
  92. package/dist/init-ZS7RAR7L.js +2 -0
  93. package/dist/{integrity-UYDOOJDP.js → integrity-UBMZCB77.js} +1 -1
  94. package/dist/{integrity-checker-DHGMZQDG.js → integrity-checker-VSR3ITBL.js} +1 -1
  95. package/dist/journal-loader-EELDB4P2.js +2 -0
  96. package/dist/{lint-IGKE6UPS.js → lint-KQQ2RMSJ.js} +1 -1
  97. package/dist/{list-5IUGP3ZB.js → list-37UCWCOQ.js} +1 -1
  98. package/dist/{list-YKIQNKGB.js → list-6WY4CFUR.js} +1 -1
  99. package/dist/lore-loader-CP5RUJ4A.js +2 -0
  100. package/dist/{lore-loader-XY5MZRR2.js → lore-loader-PBUDKXAJ.js} +1 -1
  101. package/dist/{lore-server-FC2GMDLT.js → lore-server-A3KKZLSY.js} +1 -1
  102. package/dist/{manual-RXSPSFLL.js → manual-HKI6OXB4.js} +1 -1
  103. package/dist/mcp.js +17 -449
  104. package/dist/{migrate-YQG2FG3J.js → migrate-W3KCXLDS.js} +2 -2
  105. package/dist/{migrate-assessments-GEI5WMI2.js → migrate-assessments-D2TOBJ5V.js} +1 -1
  106. package/dist/{model-discovery-HMB3YI4L.js → model-discovery-TWX4A4YD.js} +1 -1
  107. package/dist/{nomination-engine-W6QTQX2P.js → nomination-engine-A24774W4.js} +1 -1
  108. package/dist/{notebook-PE3JSYZI.js → notebook-LXJ2LHUA.js} +1 -1
  109. package/dist/notebook-loader-CF52PNZC.js +2 -0
  110. package/dist/{orchestrate-7CJWHLBA.js → orchestrate-WFCNV2II.js} +1 -1
  111. package/dist/{peers-P2KXU7ZK.js → peers-7TPZTKH7.js} +1 -1
  112. package/dist/{persona-STQWZH5P.js → persona-UGTCFEGT.js} +1 -1
  113. package/dist/{pipeline-MZUITRVN.js → pipeline-7PZ6ILWX.js} +1 -1
  114. package/dist/{platform-server-G6MJIAJS.js → platform-server-YIBX4YDJ.js} +2 -2
  115. package/dist/{plugin-update-checker-M7PW434O.js → plugin-update-checker-2EM4K45U.js} +1 -1
  116. package/dist/{portal-check-Z3OCQEQR.js → portal-check-YSDJRZUR.js} +1 -1
  117. package/dist/{portal-compliance-4MG5F2GI.js → portal-compliance-OBPK2IR5.js} +1 -1
  118. package/dist/{probe-5L5BQDGE.js → probe-WKXR3IN4.js} +1 -1
  119. package/dist/{project-type-AGO6VUKF.js → project-type-MRBJAKC7.js} +1 -1
  120. package/dist/{promote-NJQDZBZA.js → promote-VHBA56KW.js} +2 -2
  121. package/dist/{providers-TBPOE4DI.js → providers-RX7SBLHZ.js} +1 -1
  122. package/dist/{quiz-FE5UGAY2.js → quiz-3SQNPRJ3.js} +1 -1
  123. package/dist/{record-YXPB34MY.js → record-7QJPZZP7.js} +1 -1
  124. package/dist/registry-LR5QACRK.js +20 -0
  125. package/dist/reindex-F7EV3Z34.js +2 -0
  126. package/dist/{remember-MJRNTXYS.js → remember-SFGBTTEE.js} +1 -1
  127. package/dist/{retag-N5XF3KXP.js → retag-GFXUYP7S.js} +1 -1
  128. package/dist/{review-6UAH6V3R.js → review-6KKZWV3A.js} +1 -1
  129. package/dist/{review-77QI6VOC.js → review-GEBSYOZB.js} +1 -1
  130. package/dist/{ripple-ZGDITCGB.js → ripple-4F5ZCXS4.js} +1 -1
  131. package/dist/{roster-TA2GFDR7.js → roster-RI3UC2YI.js} +1 -1
  132. package/dist/scaffold-WA4L2K7J.js +18 -0
  133. package/dist/{scopes-commands-3V5G6NYV.js → scopes-commands-5FFIUDRC.js} +1 -1
  134. package/dist/{sentinel-HYAZ3CO5.js → sentinel-37ZEEWT7.js} +2 -2
  135. package/dist/{sentinel-bridge-VR357PKL.js → sentinel-bridge-EZGFRVFH.js} +1 -1
  136. package/dist/{serve-L52ZUTU6.js → serve-2BXDL35A.js} +2 -2
  137. package/dist/{serve-ZJ3EXVA5.js → serve-2LSTQFFQ.js} +2 -2
  138. package/dist/{serve-OY6XYL7F.js → serve-5JME5QEM.js} +2 -2
  139. package/dist/{server-4YNUIK4W.js → server-AIXFROYL.js} +1 -1
  140. package/dist/{server-2MNROHF6.js → server-XLHIYDTZ.js} +1 -1
  141. package/dist/session-tracker-VSFRNFRL.js +2 -0
  142. package/dist/{session-work-log-SLAPEP3M.js → session-work-log-6GKGUQ5C.js} +1 -1
  143. package/dist/{session-work-log-5UJTJJ22.js → session-work-log-UYMIWWOX.js} +1 -1
  144. package/dist/{setup-KPIMRZ4Q.js → setup-F2N4LUR7.js} +1 -1
  145. package/dist/{setup-3F5IK7MO.js → setup-ZM4JFV5D.js} +2 -2
  146. package/dist/{shift-IKTWYSEQ.js → shift-DDYVQJ75.js} +5 -5
  147. package/dist/{show-PJ5LFLIL.js → show-CZLVYLM5.js} +1 -1
  148. package/dist/{show-BOAVWZPZ.js → show-RFOIR2GQ.js} +1 -1
  149. package/dist/{snapshot-L2G56RPL.js → snapshot-6N564OUJ.js} +1 -1
  150. package/dist/{spawn-7TCAMD6H.js → spawn-HYARN3RL.js} +1 -1
  151. package/dist/{status-A37ECYNJ.js → status-CUG3PKGC.js} +1 -1
  152. package/dist/{status-77M3SDIF.js → status-WBJ6D7BD.js} +1 -1
  153. package/dist/{summary-ZJLQ6KHB.js → summary-2AM4QVPW.js} +1 -1
  154. package/dist/{sweep-HU74OPVW.js → sweep-WHDT7ENV.js} +1 -1
  155. package/dist/{switch-CTW4PDGI.js → switch-HBGIFNF6.js} +1 -1
  156. package/dist/{symphony-IS5TYPXY.js → symphony-CWKKMFAS.js} +25 -25
  157. package/dist/symphony-VTHVTE57.js +2 -0
  158. package/dist/symphony-loader-RYFZOQJS.js +2 -0
  159. package/dist/{symphony-peers-X5NGWXFP.js → symphony-peers-ISJPKX7W.js} +1 -1
  160. package/dist/{symphony-peers-U4KHMKGI.js → symphony-peers-LWBUQ3T4.js} +1 -1
  161. package/dist/symphony-relay-L3BY6RGM.js +3 -0
  162. package/dist/sync-WIFD7UCL.js +2 -0
  163. package/dist/{sync-llms-HL5PPW3M.js → sync-llms-MZ3RQWFX.js} +1 -1
  164. package/dist/{task-loader-NZFDTUQ5.js → task-loader-EU7JLTR3.js} +1 -1
  165. package/dist/team-C3PWO7XL.js +2 -0
  166. package/dist/{test-BQJMS4Y2.js → test-6MUL4EXS.js} +1 -1
  167. package/dist/{thread-HFXK65D4.js → thread-K6UHDIUW.js} +1 -1
  168. package/dist/{timeline-K3ZFKJ3R.js → timeline-S26CQWHT.js} +1 -1
  169. package/dist/tools-4WKLLDFU.js +2 -0
  170. package/dist/{triage-FCWOZASE.js → triage-YF6WYZY4.js} +1 -1
  171. package/dist/{tutorial-UC6YQMNN.js → tutorial-UEBX7Z2G.js} +1 -1
  172. package/dist/{university-FJ7OCOA3.js → university-UMT7PAKE.js} +1 -1
  173. package/dist/university-content/courses/para-201.json +5 -5
  174. package/dist/university-content/courses/para-301.json +10 -10
  175. package/dist/university-content/courses/para-401.json +3 -3
  176. package/dist/university-content/courses/para-501.json +5 -5
  177. package/dist/university-content/courses/para-601.json +1 -1
  178. package/dist/university-content/plsat/v2.0.json +7 -7
  179. package/dist/university-content/plsat/v3.0.json +9 -9
  180. package/dist/university-content/reference.json +4 -4
  181. package/dist/university-ui/assets/{index-DmiLQehB.js → index-CecQrfSn.js} +2 -2
  182. package/dist/university-ui/assets/{index-DmiLQehB.js.map → index-CecQrfSn.js.map} +1 -1
  183. package/dist/university-ui/index.html +1 -1
  184. package/dist/{upgrade-B4IOLZYK.js → upgrade-USW7YJEX.js} +1 -1
  185. package/dist/{validate-LSCDOLBO.js → validate-2PZTNYSS.js} +1 -1
  186. package/dist/{validate-VZXTJHGO.js → validate-KW3YFGTV.js} +1 -1
  187. package/dist/{validate-C6SMKGYD.js → validate-VZGBVTPM.js} +1 -1
  188. package/dist/{watch-LRM5XD46.js → watch-HL3ZOALL.js} +1 -1
  189. package/dist/{watch-PZCCUP6K.js → watch-KQU3S7KE.js} +1 -1
  190. package/dist/{wisdom-XZ3QKPNP.js → wisdom-UU7HOE3M.js} +1 -1
  191. package/dist/{work-log-loader-DL5GZ2BQ.js → work-log-loader-J27XSFCE.js} +1 -1
  192. package/dist/workspace-CE6LNXVI.js +2 -0
  193. package/package.json +5 -1
  194. package/templates/paradigm/specs/context-tracking.md +4 -4
  195. package/dist/agent-UUTYOFTH.js +0 -33
  196. package/dist/ambient-2JZTNXUL.js +0 -35
  197. package/dist/chunk-2Q7RGCJH.js +0 -3
  198. package/dist/chunk-5TAVYPOV.js +0 -2
  199. package/dist/chunk-73R63P7K.js +0 -2
  200. package/dist/chunk-C7ZCCKJT.js +0 -3
  201. package/dist/chunk-CUOEZAVL.js +0 -8
  202. package/dist/chunk-EAZ3EMOZ.js +0 -29
  203. package/dist/chunk-LKFBDUCV.js +0 -11
  204. package/dist/chunk-QGZRM6ZB.js +0 -2
  205. package/dist/chunk-S7K7UPXL.js +0 -3
  206. package/dist/chunk-TXBSTT64.js +0 -111
  207. package/dist/chunk-TZZNHUAR.js +0 -2
  208. package/dist/chunk-UHQLYIRI.js +0 -3
  209. package/dist/chunk-VZLGBGU3.js +0 -8
  210. package/dist/doctor-R4UGMR5N.js +0 -2
  211. package/dist/graph-CNDE5TAT.js +0 -2
  212. package/dist/init-24MAQJFM.js +0 -2
  213. package/dist/journal-loader-GLH7XFTK.js +0 -2
  214. package/dist/lore-loader-RVQI5GXL.js +0 -2
  215. package/dist/notebook-loader-CENTDDUJ.js +0 -2
  216. package/dist/reindex-2MRCAIZG.js +0 -2
  217. package/dist/session-tracker-WSTRV7UP.js +0 -2
  218. package/dist/symphony-43N4R6C2.js +0 -2
  219. package/dist/symphony-loader-XJT43FOS.js +0 -2
  220. package/dist/symphony-relay-CIMRXQHI.js +0 -3
  221. package/dist/sync-QRDSFETO.js +0 -2
  222. package/dist/team-WIJVWLII.js +0 -2
  223. package/dist/workspace-2ODL5WLY.js +0 -2
@@ -8,7 +8,7 @@
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
11
- <script type="module" crossorigin src="/assets/index-DmiLQehB.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-CecQrfSn.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-CMrxD7y5.css">
13
13
  </head>
14
14
  <body>
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {d,c,e as e$1}from'./chunk-HMQ5BHP2.js';import {e as e$2,d as d$1}from'./chunk-JQKKVAAN.js';import'./chunk-5TAVYPOV.js';import*as e from'fs';import*as t from'path';import {fileURLToPath}from'url';import a from'chalk';import z from'ora';var A=["scan","logger","migrate"];function j(){let l=fileURLToPath(import.meta.url),n=t.dirname(l),s=[t.join(n,"..","..","templates","paradigm"),t.join(n,"..","templates","paradigm")];for(let o of s)if(e.existsSync(o))return o;return t.join(n,"..","templates","paradigm")}async function W(l,n){let s=l?t.resolve(l):process.cwd(),o=t.basename(s),c$1=z();if(console.log(a.yellow("\n `paradigm upgrade` is deprecated. Use `paradigm migrate` instead.\n")),console.log(a.blue(`
2
+ import {d,c,e as e$1}from'./chunk-DOCDDDTD.js';import {e as e$2,d as d$1}from'./chunk-JQKKVAAN.js';import'./chunk-XHJ27CER.js';import*as e from'fs';import*as t from'path';import {fileURLToPath}from'url';import a from'chalk';import z from'ora';var A=["scan","logger","migrate"];function j(){let l=fileURLToPath(import.meta.url),n=t.dirname(l),s=[t.join(n,"..","..","templates","paradigm"),t.join(n,"..","templates","paradigm")];for(let o of s)if(e.existsSync(o))return o;return t.join(n,"..","templates","paradigm")}async function W(l,n){let s=l?t.resolve(l):process.cwd(),o=t.basename(s),c$1=z();if(console.log(a.yellow("\n `paradigm upgrade` is deprecated. Use `paradigm migrate` instead.\n")),console.log(a.blue(`
3
3
  \u{1F504} Paradigm Upgrade
4
4
  `)),n.fromHorizon){let r=await M(s,o,n,c$1);console.log(a.blue(`
5
5
  \u{1F4CB} Migration Summary
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {f,o,p}from'./chunk-JIXHEBGK.js';import'./chunk-5TAVYPOV.js';import*as l from'path';import e from'chalk';import P from'ora';async function E(u){let i=process.cwd(),h=l.resolve(i,u);console.log(e.blue(`
2
+ import {f,o,p}from'./chunk-JIXHEBGK.js';import'./chunk-XHJ27CER.js';import*as l from'path';import e from'chalk';import P from'ora';async function E(u){let i=process.cwd(),h=l.resolve(i,u);console.log(e.blue(`
3
3
  \u{1F50D} Validating Purpose Files...
4
4
  `));let a=P("Finding purpose files...").start();try{let s=await f(h);a.succeed(`Found ${s.length} purpose file(s)`);let c=!1,r=0,p$1=0;for(let{filePath:m,data:w}of s){let t=l.relative(i,m),o$1=o(w,t),$=o$1.issues.filter(n=>n.type==="error").length,v=o$1.issues.filter(n=>n.type==="warning").length;p$1+=$,r+=v,o$1.valid||(c=!0),o$1.issues.length>0?(console.log(e.white(`
5
5
  ${t}`)),console.log(p(o$1))):console.log(e.green(` \u2713 ${t}`));}console.log(e.white(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,f,g}from'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as i from'path';import t from'chalk';import d from'ora';async function h(a$1){let c=process.cwd(),g$1=i.resolve(c,a$1);console.log(t.blue(`
2
+ import {a,f,g}from'./chunk-QT2LKB3P.js';import'./chunk-XHJ27CER.js';import*as i from'path';import t from'chalk';import d from'ora';async function h(a$1){let c=process.cwd(),g$1=i.resolve(c,a$1);console.log(t.blue(`
3
3
  \u{1F50D} Validating Gate Configuration...
4
4
  `));let e=d(`Parsing ${a$1}...`).start();try{let o=await a(g$1);e.succeed("Parsed portal.yaml");let s=f(o);console.log(t.white(`
5
5
  Gates: ${o.gates.length}`)),console.log(t.white(`Flows: ${o.flows.length}`)),console.log(g(s)),s.valid||process.exit(1),console.log("");}catch(o){e.fail("Validation failed"),console.log(t.red(`Error: ${o.message}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,c,d}from'./chunk-D34YFK4M.js';import'./chunk-5TAVYPOV.js';import s from'chalk';import*as g from'fs';import*as u from'path';async function x(i){let l=process.cwd(),c$1=a(l);if(!c$1||c$1.totalContent===0){console.log(s.yellow(`
2
+ import {a,c,d}from'./chunk-D34YFK4M.js';import'./chunk-XHJ27CER.js';import s from'chalk';import*as g from'fs';import*as u from'path';async function x(i){let l=process.cwd(),c$1=a(l);if(!c$1||c$1.totalContent===0){console.log(s.yellow(`
3
3
  No university content to validate.
4
4
  `));return}let n=[],r=c$1.entries;i.id&&(r=r.filter(e=>e.id===i.id),r.length===0&&(console.error(s.red(`
5
5
  Content "${i.id}" not found
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {f as f$1,a,d,e}from'./chunk-WR6D3SC6.js';import {c,d as d$1,e as e$1}from'./chunk-HMQ5BHP2.js';import'./chunk-JQKKVAAN.js';import'./chunk-5TAVYPOV.js';import*as t from'fs';import*as f from'path';import c$1 from'chalk';async function P(){let r=process.cwd();f$1("\u{1F440} Paradigm Watch"),a("");let e$2=f.join(r,".paradigm");(!t.existsSync(e$2)||!t.statSync(e$2).isDirectory())&&(d("No .paradigm/ directory found."),e(" Run `paradigm init` first.\n"),process.exit(1));let o=c(r).detected||"cursor";e(`Watching for changes...
2
+ import {f as f$1,a,d,e}from'./chunk-WR6D3SC6.js';import {c,d as d$1,e as e$1}from'./chunk-DOCDDDTD.js';import'./chunk-JQKKVAAN.js';import'./chunk-XHJ27CER.js';import*as t from'fs';import*as f from'path';import c$1 from'chalk';async function P(){let r=process.cwd();f$1("\u{1F440} Paradigm Watch"),a("");let e$2=f.join(r,".paradigm");(!t.existsSync(e$2)||!t.statSync(e$2).isDirectory())&&(d("No .paradigm/ directory found."),e(" Run `paradigm init` first.\n"),process.exit(1));let o=c(r).detected||"cursor";e(`Watching for changes...
3
3
  `),e(" [config] .paradigm/config.yaml"),e(" [specs] .paradigm/specs/*.md"),e(` [target] ${o}
4
4
  `),e(`Press Ctrl+C to stop.
5
5
  `);let n={lastConfigMtime:0,lastSpecsMtime:0},s=f.join(e$2,"config.yaml"),g=f.join(e$2,"specs");t.existsSync(s)&&(n.lastConfigMtime=t.statSync(s).mtime.getTime()),t.existsSync(g)&&(n.lastSpecsMtime=y(g));let D=setInterval(()=>{let p=false,l="";if(t.existsSync(s)){let i=t.statSync(s).mtime.getTime();i>n.lastConfigMtime&&(n.lastConfigMtime=i,p=true,l="config");}if(t.existsSync(g)){let i=y(g);i>n.lastSpecsMtime&&(n.lastSpecsMtime=i,p=true,l=l?"config+specs":"specs");}if(p){let i=new Date().toLocaleTimeString("en-US",{hour12:false});a(c$1.cyan(`${i}`)+c$1.gray(` [${l}]`)+" Changed \u2192 syncing...");let u=d$1(r);if(u){let d=e$1(r,o,u,true);d.success?a(c$1.green(`${i}`)+c$1.gray(" [sync]")+` ${d.outputPath} updated`):a(c$1.red(`${i}`)+c$1.gray(" [sync]")+` Failed: ${d.message}`);}else a(c$1.red(`${i}`)+c$1.gray(" [error]")+" Failed to load .paradigm/ files");}},1e3);process.on("SIGINT",()=>{clearInterval(D),e(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import'./chunk-5TAVYPOV.js';import*as d from'path';import*as f from'fs';import*as y from'js-yaml';import o from'chalk';import h from'ora';import v from'open';async function x(m,r={}){let w=m?d.resolve(m):process.cwd(),c=parseInt(r.port||"42196",10),s=parseInt(r.uiPort||"42195",10),i=r.config||d.join(w,"portal.yaml");console.log(o.magenta(`
2
+ import'./chunk-XHJ27CER.js';import*as d from'path';import*as f from'fs';import*as y from'js-yaml';import o from'chalk';import h from'ora';import v from'open';async function x(m,r={}){let w=m?d.resolve(m):process.cwd(),c=parseInt(r.port||"42196",10),s=parseInt(r.uiPort||"42195",10),i=r.config||d.join(w,"portal.yaml");console.log(o.magenta(`
3
3
  \u{1F6AA} Portal Viewer
4
4
  `));let a=h("Starting Portal Viewer...").start();try{f.existsSync(i)||(a.warn(`No portal.yaml found at ${o.gray(i)}`),console.log(o.gray(` The viewer will start but won't have any predefined gates.
5
5
  `)));let t;try{t=(await import('@a-company/portal-viewer')).ViewerServer;}catch{a.fail("Portal Viewer package not found"),console.log(""),console.log(o.yellow("To use the Portal Viewer, install the package:")),console.log(o.cyan(" npm install @a-company/portal-viewer")),console.log(""),console.log(o.gray("Or build from source in the monorepo:")),console.log(o.gray(" cd packages/portal/viewer && npm run build")),process.exit(1);}await new t({port:c,uiPort:s,configPath:i}).start(),a.succeed("Portal Viewer started"),console.log(""),console.log(o.blue(" \u{1F310} UI: ")+o.cyan.bold(`http://localhost:${s}`)),console.log(o.blue(" \u{1F50C} WebSocket: ")+o.cyan(`ws://localhost:${c}`)),console.log(o.blue(" \u{1F4CB} Config: ")+o.gray(i)),console.log(""),console.log(o.gray(" Connect your app's Portal SDK to the WebSocket URL above.")),console.log(o.gray(" Press Ctrl+C to stop.")),console.log(""),r.open!==!1&&await v(`http://localhost:${s}`),await new Promise(()=>{});}catch(t){a.fail("Failed to start Portal Viewer"),console.error(o.red(t.message)),process.exit(1);}}async function $(m,r={}){m||(console.log(o.red("Error: Session path required")),console.log(""),console.log("Usage: paradigm portal report <session.json> [options]"),console.log(""),console.log("Options:"),console.log(" --format <format> Output format: json, markdown, slack, discord"),console.log(" --output <path> Output file path"),process.exit(1));let w=r.format||"markdown",c=r.output;console.log(o.magenta(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import'./chunk-5TAVYPOV.js';import*as t from'fs';import*as c from'path';import e from'chalk';import*as p from'js-yaml';var f=".paradigm/wisdom";async function j(o,g={}){let i=process.cwd(),r=c.join(i,f);if(!t.existsSync(r)){console.log(e.yellow("No wisdom directory found.")),console.log(e.gray("Run `paradigm wisdom init` to create .paradigm/wisdom/"));return}let a=x(c.join(r,"preferences.yaml")),s=x(c.join(r,"antipatterns.yaml")),d=x(c.join(r,"expertise.yaml")),m=S(r);if(g.json){console.log(JSON.stringify({preferences:a,antipatterns:s?.antipatterns||[],expertise:d?.experts||[],decisions:m},null,2));return}if(console.log(e.magenta(`
2
+ import'./chunk-XHJ27CER.js';import*as t from'fs';import*as c from'path';import e from'chalk';import*as p from'js-yaml';var f=".paradigm/wisdom";async function j(o,g={}){let i=process.cwd(),r=c.join(i,f);if(!t.existsSync(r)){console.log(e.yellow("No wisdom directory found.")),console.log(e.gray("Run `paradigm wisdom init` to create .paradigm/wisdom/"));return}let a=x(c.join(r,"preferences.yaml")),s=x(c.join(r,"antipatterns.yaml")),d=x(c.join(r,"expertise.yaml")),m=S(r);if(g.json){console.log(JSON.stringify({preferences:a,antipatterns:s?.antipatterns||[],expertise:d?.experts||[],decisions:m},null,2));return}if(console.log(e.magenta(`
3
3
  Wisdom
4
4
  `)),o){console.log(e.cyan(` Symbol: ${o}
5
5
  `));let n=a?.by_symbol?.[o];n&&(console.log(e.white(" Preferences:")),n.patterns&&n.patterns.forEach(l=>console.log(e.gray(` - ${l}`))),n.testing&&console.log(e.gray(` Testing: ${n.testing}`)),console.log());let y=(s?.antipatterns||[]).filter(l=>l.symbols.includes(o));y.length>0&&(console.log(e.red(" Antipatterns:")),y.forEach(l=>{console.log(e.gray(` [${l.id}] ${l.description}`)),console.log(e.gray(` Reason: ${l.reason}`)),console.log(e.green(` Alternative: ${l.alternative}`)),console.log();}));let w=m.filter(l=>l.symbols.includes(o));w.length>0&&(console.log(e.blue(" Decisions:")),w.forEach(l=>{console.log(e.gray(` [${l.id}] ${l.title} (${l.status})`));}),console.log());let $=(d?.experts||[]).filter(l=>l.symbols?.includes(o));$.length>0&&(console.log(e.yellow(" Experts:")),$.forEach(l=>{console.log(e.gray(` - ${l.name}${l.contact?` (${l.contact})`:""}`));}));return}if(console.log(e.white(" Global Preferences:")),a?.global){let n=a.global;n.code_style?.length&&(console.log(e.gray(" Code Style:")),n.code_style.forEach(y=>console.log(e.gray(` - ${y}`)))),n.testing?.length&&(console.log(e.gray(" Testing:")),n.testing.forEach(y=>console.log(e.gray(` - ${y}`))));}else console.log(e.gray(" No global preferences defined"));console.log();let h=Object.keys(a?.by_symbol||{});h.length>0&&(console.log(e.white(` Symbol Preferences: ${h.length}`)),h.slice(0,5).forEach(n=>console.log(e.gray(` - ${n}`))),h.length>5&&console.log(e.gray(` ... and ${h.length-5} more`)),console.log());let u=s?.antipatterns||[];u.length>0&&(console.log(e.red(` Antipatterns: ${u.length}`)),u.slice(0,3).forEach(n=>{console.log(e.gray(` [${n.id}] ${n.description.slice(0,60)}...`));}),u.length>3&&console.log(e.gray(` ... and ${u.length-3} more`)),console.log()),m.length>0&&(console.log(e.blue(` Decisions: ${m.length}`)),m.slice(0,3).forEach(n=>{console.log(e.gray(` [${n.id}] ${n.title} (${n.status})`));}),m.length>3&&console.log(e.gray(` ... and ${m.length-3} more`)),console.log());let b=d?.experts||[];b.length>0&&(console.log(e.yellow(` Experts: ${b.length}`)),b.slice(0,3).forEach(n=>{console.log(e.gray(` - ${n.name}: ${n.areas?.join(", ")||n.symbols?.join(", ")}`));}),console.log());}async function D(o={}){let g=process.cwd(),i=c.join(g,f);if(t.existsSync(i)&&!o.force){console.log(e.yellow("Wisdom directory already exists.")),console.log(e.gray("Use --force to reinitialize"));return}t.mkdirSync(i,{recursive:true}),t.mkdirSync(c.join(i,"decisions"),{recursive:true});let r={version:"1.0",updated:new Date().toISOString(),by_symbol:{"@example":{patterns:["Use optimistic UI updates","Show skeleton loaders"],testing:"Require e2e tests for happy path"}},global:{code_style:["Prefer early returns","Named exports only"],testing:["Unit for pure functions","E2E for critical flows"]}},a={version:"1.0",antipatterns:[{id:"example-001",symbols:["@example"],description:"Example antipattern - do NOT do this",reason:"Explain why this is bad",alternative:"Do this instead",added:new Date().toISOString()}]},s={version:"1.0",experts:[{name:"your-name",symbols:["@feature"],areas:["domain-area"],contact:"email or slack"}]};t.writeFileSync(c.join(i,"preferences.yaml"),p.dump(r,{lineWidth:-1})),t.writeFileSync(c.join(i,"antipatterns.yaml"),p.dump(a,{lineWidth:-1})),t.writeFileSync(c.join(i,"expertise.yaml"),p.dump(s,{lineWidth:-1})),console.log(e.green("Wisdom directory initialized!")),console.log(e.gray(` ${i}/`)),console.log(e.gray(" preferences.yaml")),console.log(e.gray(" antipatterns.yaml")),console.log(e.gray(" expertise.yaml")),console.log(e.gray(" decisions/"));}async function P(o){let g=process.cwd(),i=c.join(g,f,"antipatterns.yaml"),r={version:"1.0",antipatterns:[]};if(t.existsSync(i)){let s=t.readFileSync(i,"utf8");r=p.load(s);}else t.mkdirSync(c.join(g,f),{recursive:true});let a={id:o.id,symbols:o.symbols.split(",").map(s=>s.trim()),description:o.description,reason:o.reason,alternative:o.alternative,added:new Date().toISOString()};r.antipatterns.push(a),t.writeFileSync(i,p.dump(r,{lineWidth:-1})),console.log(e.green(`Antipattern ${o.id} added!`));}async function W(o){let g=process.cwd(),i=c.join(g,f,"decisions");t.mkdirSync(i,{recursive:true});let r={id:o.id,title:o.title,status:o.status||"proposed",date:new Date().toISOString().split("T")[0],symbols:o.symbols.split(",").map(d=>d.trim()),context:o.context,decision:o.decision,rationale:{factors:[],conclusion:""},consequences:{positive:[],negative:[]}},a=`${r.id}-${v(r.title)}.yaml`,s=c.join(i,a);t.writeFileSync(s,p.dump(r,{lineWidth:-1})),console.log(e.green(`Decision ${r.id} created!`)),console.log(e.gray(` ${s}`)),console.log(e.gray(" Edit the file to add rationale and consequences"));}async function _(o,g={}){let i=process.cwd(),r=c.join(i,f,"expertise.yaml");if(!t.existsSync(r)){console.log(e.yellow("No expertise file found."));return}let s=x(r)?.experts||[];if(o&&(s=s.filter(d=>d.symbols?.some(m=>m.includes(o))||d.areas?.some(m=>m.toLowerCase().includes(o.toLowerCase())))),g.json){console.log(JSON.stringify({experts:s},null,2));return}if(s.length===0){console.log(e.yellow("No experts found"));return}console.log(e.magenta(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{d as getWorkLogSummary,b as loadWorkLogEntries,c as loadWorkLogEntry,a as recordWorkLog}from'./chunk-JNSJVCTU.js';import'./chunk-5TAVYPOV.js';
2
+ export{d as getWorkLogSummary,b as loadWorkLogEntries,c as loadWorkLogEntry,a as recordWorkLog}from'./chunk-JNSJVCTU.js';import'./chunk-XHJ27CER.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{d as detectProjectRole,a as workspaceInitCommand,c as workspaceReindexCommand,b as workspaceStatusCommand}from'./chunk-DG3VCY43.js';import'./chunk-77WX6HGV.js';import'./chunk-4TXOVRWD.js';import'./chunk-6QKCUEEY.js';import'./chunk-WR6D3SC6.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-LKAT7IAK.js';import'./chunk-XHJ27CER.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-company/paradigm",
3
- "version": "5.34.0",
3
+ "version": "5.37.0",
4
4
  "description": "Unified CLI for Paradigm developer tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -30,9 +30,11 @@
30
30
  "test": "vitest run",
31
31
  "test:watch": "vitest",
32
32
  "typecheck": "tsc --noEmit",
33
+ "lint": "eslint src/commands/",
33
34
  "prepublishOnly": "npm run build"
34
35
  },
35
36
  "dependencies": {
37
+ "@a-company/registry-client": "^0.1.0",
36
38
  "@modelcontextprotocol/sdk": "^1.0.0",
37
39
  "chalk": "^5.3.0",
38
40
  "commander": "^11.1.0",
@@ -49,7 +51,9 @@
49
51
  "zod": "^3.23.0"
50
52
  },
51
53
  "devDependencies": {
54
+ "@eslint/js": "^9.0.0",
52
55
  "@types/js-yaml": "^4.0.9",
56
+ "eslint": "^9.0.0",
53
57
  "@types/node": "^20.10.0",
54
58
  "@types/prompts": "^2.4.9",
55
59
  "tsup": "^8.0.1",
@@ -38,7 +38,7 @@ The MCP server tracks session interactions and provides:
38
38
 
39
39
  ## MCP Tools
40
40
 
41
- ### paradigm_context_check
41
+ ### paradigm_session_health
42
42
 
43
43
  Check if context handoff is recommended.
44
44
 
@@ -133,11 +133,11 @@ Markdown guide for when and how to perform handoffs.
133
133
 
134
134
  ### Periodic Checks
135
135
 
136
- For long sessions, periodically call `paradigm_context_check`:
136
+ For long sessions, periodically call `paradigm_session_health`:
137
137
 
138
138
  ```
139
139
  After every 10-15 significant interactions:
140
- 1. Call paradigm_context_check
140
+ 1. Call paradigm_session_health
141
141
  2. If recommendation != "continue":
142
142
  - Inform user of recommendation
143
143
  - Offer to prepare handoff
@@ -186,7 +186,7 @@ Context tracking complements the Team system:
186
186
 
187
187
  Typical flow:
188
188
  ```
189
- paradigm_context_check → paradigm_handoff_prepare → paradigm team handoff → new session → paradigm team accept
189
+ paradigm_session_health → paradigm_handoff_prepare → paradigm team handoff → new session → paradigm team accept
190
190
  ```
191
191
 
192
192
  ---
@@ -1,33 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as c from'fs';import*as y from'path';import*as P from'os';import o from'chalk';import*as m from'js-yaml';var u=y.join(P.homedir(),".paradigm","agents"),S=".paradigm/agents",$=".agent",k={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"}};async function T(e={}){let s=process.cwd(),r=a.command("agent-list").start("Listing agent profiles",{cwd:s}),t=[];if(!e.project&&c.existsSync(u))try{let i=c.readdirSync(u).filter(l=>l.endsWith($));for(let l of i)try{let d=c.readFileSync(y.join(u,l),"utf-8"),n=m.load(d);n?.id&&t.push(n);}catch{}}catch{}let g=y.join(s,S);if(!e.global&&c.existsSync(g))try{let i=c.readdirSync(g).filter(l=>l.endsWith($));for(let l of i)try{let d=c.readFileSync(y.join(g,l),"utf-8"),n=m.load(d);if(n?.id){let f=t.findIndex(a=>a.id===n.id);f>=0?t[f]=n:t.push(n);}}catch{}}catch{}if(e.json){console.log(JSON.stringify({count:t.length,agents:t.map(C)},null,2)),r.success(`Found ${t.length} agents`);return}if(console.log(o.blue(`
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(o.blue("\u2502")+o.white.bold(" paradigm agent list ")+o.blue("\u2502")),console.log(o.blue("\u2502")+o.gray(" Persistent agent identity profiles ")+o.blue("\u2502")),console.log(o.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
- `)),t.length===0){console.log(o.yellow(" No .agent profiles found.")),console.log(o.gray(` Create one: paradigm agent create <id> --global
5
- `)),r.success("No agents found");return}for(let i of t){let d=(i.expertise||[]).sort((n,f)=>f.confidence-n.confidence).slice(0,3).map(n=>`${n.symbol} (${(n.confidence*100).toFixed(0)}%)`).join(", ")||o.gray("none yet");console.log(` ${o.white.bold(i.id)} \u2014 ${o.gray(i.role)}`),console.log(` Style: ${i.personality?.style||"?"} | Risk: ${i.personality?.risk||"?"} | Verbosity: ${i.personality?.verbosity||"?"}`),console.log(` Top expertise: ${d}`),console.log(` Projects: ${Object.keys(i.contexts||{}).join(", ")||o.gray("none")}`),console.log("");}r.success(`Listed ${t.length} agents`);}async function I(e,s={}){let r=process.cwd(),t=a.command("agent-show").start(`Showing agent ${e}`,{cwd:r}),g=x(r,e);if(!g){s.json?console.log(JSON.stringify({error:`Agent "${e}" not found`})):(console.log(o.red(`
6
- Agent "${e}" not found.`)),console.log(o.gray(` Create: paradigm agent create ${e} --global
7
- `))),t.error(`Agent ${e} not found`);return}if(s.json){console.log(JSON.stringify(g,null,2)),t.success(`Showed agent ${e}`);return}if(console.log(o.blue(`
8
- \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(o.blue("\u2502")+o.white.bold(` Agent: ${e}`.padEnd(50))+o.blue("\u2502")),console.log(o.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
9
- `)),console.log(` ${o.white.bold("Role:")} ${g.role}`),console.log(` ${o.white.bold("Description:")} ${g.description}`),console.log(` ${o.white.bold("Version:")} ${g.version}`),console.log(` ${o.white.bold("Created:")} ${g.created}`),console.log(` ${o.white.bold("Updated:")} ${g.updated}`),console.log(""),g.personality){let f=g.personality;console.log(` ${o.white.bold("Personality")}`),console.log(` Style: ${f.style} | Risk: ${f.risk} | Verbosity: ${f.verbosity}`),console.log("");}let i=(g.expertise||[]).sort((f,a)=>a.confidence-f.confidence);if(i.length>0){console.log(` ${o.white.bold("Expertise")} (${i.length} symbols)`),console.log(` ${"Symbol".padEnd(30)} ${"Confidence".padEnd(12)} ${"Sessions".padEnd(10)} Last Touch`),console.log(` ${"-".repeat(70)}`);for(let f of i.slice(0,20)){let a=`${(f.confidence*100).toFixed(0)}%`.padEnd(12),h=String(f.sessions).padEnd(10),p=f.lastTouch?f.lastTouch.split("T")[0]:"\u2014";console.log(` ${f.symbol.padEnd(30)} ${a} ${h} ${p}`);}i.length>20&&console.log(o.gray(` ... and ${i.length-20} more`)),console.log("");}else console.log(o.gray(" No expertise recorded. Run `paradigm agent sync` to bootstrap from lore.\n"));let l=g.transferable||[];if(l.length>0){console.log(` ${o.white.bold("Transferable Patterns")} (${l.length})`);for(let f of l)console.log(` ${f.id}: ${(f.successRate*100).toFixed(0)}% success \u2014 ${f.description}`),console.log(o.gray(` Learned in: ${f.learnedIn} | Applied in: ${f.appliedIn.join(", ")||"none"}`));console.log("");}let d=Object.entries(g.contexts||{});if(d.length>0){console.log(` ${o.white.bold("Project Contexts")} (${d.length})`);for(let[f,a]of d)console.log(` ${o.white(f)}: ${a.sessionsInProject||0} sessions, last active ${a.lastActive?.split("T")[0]||"\u2014"}`),a.defaultModel&&console.log(` Model: ${a.defaultModel}`),a.focus?.length&&console.log(` Focus: ${a.focus.join(", ")}`);console.log("");}let n=g.permissions;n&&(console.log(` ${o.white.bold("Permissions")}`),n.paths?.read?.length&&console.log(` Read: ${n.paths.read.join(", ")}`),n.paths?.write?.length&&console.log(` Write: ${n.paths.write.join(", ")}`),n.paths?.deny?.length&&console.log(` Deny: ${o.red(n.paths.deny.join(", "))}`),n.tools?.allow?.length&&console.log(` Tools allow: ${n.tools.allow.join(", ")}`),n.tools?.deny?.length&&console.log(` Tools deny: ${o.red(n.tools.deny.join(", "))}`),n.dangerous_actions?.length&&console.log(` Requires approval: ${n.dangerous_actions.join(", ")}`),console.log("")),t.success(`Showed agent ${e}`);}async function D(e,s={}){let r=process.cwd(),t=s.global?"global":"project",g=a.command("agent-create").start(`Creating agent ${e} (${t})`,{cwd:r}),i=t==="global"?u:y.join(r,S);c.existsSync(i)||c.mkdirSync(i,{recursive:true});let l=y.join(i,`${e}${$}`);if(c.existsSync(l)){console.log(o.yellow(`
10
- Agent "${e}" already exists at ${l}`)),console.log(o.gray(" Use `paradigm agent show` to view.\n")),g.error("Agent already exists");return}let d=new Date().toISOString(),n=k[e]||{style:"deliberate",risk:"balanced",verbosity:"concise"},f={id:e,role:s.role||`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:s.description||`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:n,expertise:[],transferable:[],contexts:{},created:d,updated:d};if(s.denyPaths){let h=s.denyPaths.split(",").map(p=>p.trim());f.permissions={paths:{deny:h}};}let a$1=m.dump(f,{lineWidth:120,noRefs:true,sortKeys:false});c.writeFileSync(l,a$1,"utf-8"),console.log(o.green(`
11
- \u2713 Created agent "${e}" at ${l}`)),console.log(o.gray(" Run `paradigm agent sync` to bootstrap expertise from lore.\n")),g.success(`Created agent ${e}`);}async function N(e,s={}){let r=process.cwd(),t=a.command("agent-sync").start(`Syncing expertise for ${e}`,{cwd:r}),g=y.join(r,".paradigm","lore","entries");if(!c.existsSync(g)){console.log(o.yellow(`
12
- No lore directory found. Nothing to sync from.
13
- `)),t.error("No lore found");return}let i=x(r,e);if(!i){if(s.dryRun){console.log(o.yellow(`
14
- Agent "${e}" not found. Would create with --no-dry-run.
15
- `)),t.success("Dry run \u2014 would create");return}let h=(c.existsSync(y.join(u,`${e}${$}`))?"global":"project")==="global"?u:y.join(r,S);c.existsSync(h)||c.mkdirSync(h,{recursive:true});let p=new Date().toISOString(),w=k[e]||{style:"deliberate",risk:"balanced",verbosity:"concise"};i={id:e,role:`${e.charAt(0).toUpperCase()+e.slice(1)} agent`,description:`Persistent identity for the ${e} agent role`,version:"1.0.0",personality:w,expertise:[],transferable:[],contexts:{},created:p,updated:p};}let l=i.expertise||[],d=0,n=new Set,f=F(g);for(let a of f)if(!(!a.symbols_touched||a.symbols_touched.length===0)){d++;for(let h of a.symbols_touched){n.add(h);let p=l.find(w=>w.symbol===h);p?(p.sessions++,p.lastTouch=a.timestamp||p.lastTouch,a.confidence!=null&&(p.confidence=.7*p.confidence+.3*a.confidence)):l.push({symbol:h,confidence:a.confidence??.5,sessions:1,lastTouch:a.timestamp||new Date().toISOString()});}}if(i.expertise=l,s.json)console.log(JSON.stringify({agentId:e,entriesProcessed:d,symbolsUpdated:n.size,dryRun:!!s.dryRun,topExpertise:l.sort((a,h)=>h.confidence-a.confidence).slice(0,10)},null,2));else if(console.log(o.blue(`
16
- Syncing expertise for "${e}" from ${d} lore entries...`)),console.log(` ${o.green("\u2713")} ${n.size} symbols updated`),console.log(` ${o.green("\u2713")} ${d} entries processed`),l.length>0){console.log(`
17
- Top expertise:`);for(let a of l.sort((h,p)=>p.confidence-h.confidence).slice(0,5))console.log(` ${a.symbol}: ${(a.confidence*100).toFixed(0)}% (${a.sessions} sessions)`);}if(s.dryRun)s.json||console.log(o.yellow(`
18
- Dry run \u2014 no changes written.
19
- `));else {i.updated=new Date().toISOString();let a=y.join(r,S,`${e}${$}`),h=y.join(u,`${e}${$}`),p=c.existsSync(a)?"project":"global",w=p==="global"?u:y.join(r,S);c.existsSync(w)||c.mkdirSync(w,{recursive:true});let j=p==="global"?h:a;c.writeFileSync(j,m.dump(i,{lineWidth:120,noRefs:true,sortKeys:false}),"utf-8"),s.json||console.log(o.green(`
20
- \u2713 Saved to ${j}
21
- `));}t.success(`Synced ${n.size} symbols from ${d} entries`);}async function _(e={}){let s=process.cwd(),r=a.command("agent-roster").start("Agent roster",{cwd:s}),t=[];if(c.existsSync(u))for(let d of c.readdirSync(u).filter(n=>n.endsWith($)))try{let n=m.load(c.readFileSync(y.join(u,d),"utf-8"));n?.id&&t.push(n);}catch{}let g=y.join(s,S);if(c.existsSync(g))for(let d of c.readdirSync(g).filter(n=>n.endsWith($)))try{let n=m.load(c.readFileSync(y.join(g,d),"utf-8"));if(n?.id){let f=t.findIndex(a=>a.id===n.id);f>=0?t[f]=n:t.push(n);}}catch{}let i=t.filter(d=>!d.benched),l=t.filter(d=>d.benched);if(e.json){console.log(JSON.stringify({active:i.map(v),benched:l.map(v)},null,2)),r.success(`${i.length} active, ${l.length} benched`);return}if(console.log(o.blue(`
22
- \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(o.blue("\u2502")+o.white.bold(" Agent Roster ")+o.blue("\u2502")),console.log(o.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
23
- `)),i.length>0){console.log(o.green.bold(" Active"));for(let d of i)A(d);}if(l.length>0){console.log(o.gray.bold(`
24
- Benched`));for(let d of l)A(d,true);}t.length===0?console.log(o.yellow(` No agents found.
25
- `)):console.log(""),r.success(`${i.length} active, ${l.length} benched`);}function A(e,s=false){let r=(e.expertise||[]).sort((n,f)=>f.confidence-n.confidence),t=r[0]?`${r[0].symbol} (${(r[0].confidence*100).toFixed(0)}%)`:o.gray("\u2014"),g=s?o.gray:o.white,i=e.nickname?` (${e.nickname})`:"",l=e.attention?.threshold,d=l!=null?` | thr: ${l.toFixed(2)}`:"";console.log(` ${g.bold(e.id)}${o.gray(i)} \u2014 ${o.gray(e.role)}`),console.log(` Top: ${t} | ${r.length} symbols${d}`);}function v(e){let s=(e.expertise||[]).sort((r,t)=>t.confidence-r.confidence);return {id:e.id,role:e.role,nickname:e.nickname,benched:e.benched||false,expertiseCount:s.length,topExpertise:s.slice(0,3).map(r=>({symbol:r.symbol,confidence:parseFloat(r.confidence.toFixed(2))})),threshold:e.attention?.threshold}}async function L(e){let s=process.cwd(),r=a.command("agent-bench").start(`Benching agent ${e}`,{cwd:s}),t=x(s,e);if(!t){console.log(o.red(`
26
- Agent "${e}" not found.
27
- `)),r.error("Not found");return}t.benched=true,t.updated=new Date().toISOString(),R(s,e,t),console.log(o.yellow(`
28
- \u23F8 Agent "${e}" is now benched.`)),console.log(o.gray(` Maestro will skip this agent during orchestration.
29
- `)),r.success(`Benched ${e}`);}async function W(e){let s=process.cwd(),r=a.command("agent-activate").start(`Activating agent ${e}`,{cwd:s}),t=x(s,e);if(!t){console.log(o.red(`
30
- Agent "${e}" not found.
31
- `)),r.error("Not found");return}t.benched=false,t.updated=new Date().toISOString(),R(s,e,t),console.log(o.green(`
32
- \u25B6 Agent "${e}" is now active.`)),console.log(o.gray(` Maestro will include this agent in orchestration.
33
- `)),r.success(`Activated ${e}`);}function R(e,s,r){let t=y.join(e,S,`${s}${$}`);if(c.existsSync(t)){c.writeFileSync(t,m.dump(r,{lineWidth:120,noRefs:true,sortKeys:false}),"utf-8");return}let g=y.join(u,`${s}${$}`),i=u;c.existsSync(i)||c.mkdirSync(i,{recursive:true}),c.writeFileSync(g,m.dump(r,{lineWidth:120,noRefs:true,sortKeys:false}),"utf-8");}function x(e,s){let r=y.join(e,S,`${s}${$}`);if(c.existsSync(r))try{return m.load(c.readFileSync(r,"utf-8"))}catch{}let t=y.join(u,`${s}${$}`);if(c.existsSync(t))try{return m.load(c.readFileSync(t,"utf-8"))}catch{}return null}function C(e){return {id:e.id,role:e.role,personality:e.personality,expertiseCount:(e.expertise||[]).length,topExpertise:(e.expertise||[]).sort((s,r)=>r.confidence-s.confidence).slice(0,3).map(s=>({symbol:s.symbol,confidence:parseFloat(s.confidence.toFixed(2))})),projectContexts:Object.keys(e.contexts||{}),transferableCount:(e.transferable||[]).length}}function F(e){let s=[];try{let r=c.readdirSync(e,{withFileTypes:!0});for(let t of r){if(!t.isDirectory())continue;let g=y.join(e,t.name);try{let i=c.readdirSync(g).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml"));for(let l of i)try{let d=c.readFileSync(y.join(g,l),"utf-8"),n=m.load(d);n?.symbols_touched&&Array.isArray(n.symbols_touched)&&s.push({symbols_touched:n.symbols_touched,confidence:typeof n.confidence=="number"?n.confidence:void 0,timestamp:n.timestamp||t.name});}catch{}}catch{}}}catch{}return s}export{W as agentActivateCommand,L as agentBenchCommand,D as agentCreateCommand,T as agentListCommand,_ as agentRosterCommand,I as agentShowCommand,N as agentSyncCommand};
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- import {f,p,i,j}from'./chunk-C7ZCCKJT.js';import {b as b$2}from'./chunk-32RBX5YV.js';import {b as b$3}from'./chunk-7SWEOPWF.js';import {c,b as b$1,d,a}from'./chunk-5TAVYPOV.js';import*as g from'fs';import*as b from'path';import*as R from'js-yaml';import*as Q from'os';var vt={};c(vt,{getJournalStats:()=>ne,loadAllJournalEntries:()=>ee,loadJournalEntries:()=>O,loadJournalEntry:()=>te,recordJournalEntry:()=>V});function G(n){let t=process.env.HOME||process.env.USERPROFILE||"";return b.join(t,".paradigm","agents",n,"journal")}function Zt(){let n=new Date,t=n.toISOString().slice(0,10),e=n.toISOString().slice(11,19).replace(/:/g,""),o=String(Math.floor(Math.random()*999)+1).padStart(3,"0");return `LJ-${t}-${e}-${o}`}function V(n,t){let e=new Date,o=Zt(),r={id:o,agent:n,timestamp:e.toISOString(),...t},i=G(n);g.mkdirSync(i,{recursive:true});let s=b.join(i,`${o}.yaml`);return g.writeFileSync(s,R.dump(r,{lineWidth:120,noRefs:true}),"utf8"),r}function O(n,t){let e=G(n);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return t?.trigger&&(i=i.filter(s=>s.trigger===t.trigger)),t?.project&&(i=i.filter(s=>s.project===t.project)),t?.transferable!==void 0&&(i=i.filter(s=>s.transferable===t.transferable)),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}function te(n,t){let e=G(n),o=b.join(e,`${t}.yaml`);if(!g.existsSync(o))return null;let r=g.readFileSync(o,"utf8");return R.load(r)}function ee(n){let t=process.env.HOME||process.env.USERPROFILE||"",e=b.join(t,".paradigm","agents");if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory());for(let i of r){if(n?.agent&&i.name!==n.agent)continue;let s=O(i.name,n);o.push(...s);}return o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),n?.limit?o.slice(0,n.limit):o}function ne(n){let t=O(n),e={},o={},r=0;for(let i of t)e[i.trigger]=(e[i.trigger]||0)+1,o[i.project]=(o[i.project]||0)+1,i.transferable&&r++;return {total:t.length,byTrigger:e,byProject:o,transferableCount:r,recentInsights:t.slice(0,5).map(i=>({id:i.id,trigger:i.trigger,insight:i.insight.slice(0,200),timestamp:i.timestamp}))}}var z=b$1(()=>{});var xt={};c(xt,{addNotebookEntry:()=>kt,incrementApplied:()=>se,loadNotebookEntries:()=>Dt,promoteFromLore:()=>re,searchNotebooks:()=>ie});function Dt(n,t,e){let o=new Map,r=b.join(K,n);jt(r,o);let i=b.join(t,X,n);jt(i,o);let s=Array.from(o.values());if(e?.concepts&&e.concepts.length>0){let a=new Set(e.concepts.map(c=>c.toLowerCase()));s=s.filter(c=>c.concepts.some(d=>a.has(d.toLowerCase())));}if(e?.tags&&e.tags.length>0){let a=new Set(e.tags.map(c=>c.toLowerCase()));s=s.filter(c=>c.tags.some(d=>a.has(d.toLowerCase())));}return s.sort((a,c)=>c.appliedCount-a.appliedCount)}function jt(n,t){if(g.existsSync(n))try{let e=g.readdirSync(n).filter(o=>o.startsWith(oe)&&o.endsWith(Y));for(let o of e)try{let r=g.readFileSync(b.join(n,o),"utf-8"),i=R.load(r);i?.id&&t.set(i.id,i);}catch{}}catch{}}function ie(n,t,e){let o=Dt(n,e),r=t.toLowerCase();return o.filter(i=>i.context.toLowerCase().includes(r)||i.snippet.toLowerCase().includes(r)||i.concepts.some(s=>s.toLowerCase().includes(r))||i.tags.some(s=>s.toLowerCase().includes(r)))}function kt(n,t,e,o){let r=new Date().toISOString(),i=(t.concepts[0]||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),s=Date.now().toString(36),a=`nb-${i}-${s}`,c={...t,id:a,appliedCount:0,created:r,updated:r},d=e==="global"?b.join(K,n):b.join(o||process.cwd(),X,n);g.existsSync(d)||g.mkdirSync(d,{recursive:true});let u=`${a}${Y}`,l=b.join(d,u),m=R.dump(c,{lineWidth:120,noRefs:true,sortKeys:false});return g.writeFileSync(l,m,"utf-8"),{entry:c,filePath:l}}async function re(n,t,e,o="global"){let{loadLoreEntry:r}=await import('./lore-loader-XY5MZRR2.js'),i=await r(e,t);if(!i)return null;let s=[];if(i.symbols_touched)for(let d of i.symbols_touched){let u=d.replace(/^[#$^!~]/,"").toLowerCase();s.push(u);}let a=i.summary||"";i.body&&(a+=`
3
-
4
- `+i.body);let c={source:"lore",loreEntryId:t,originProject:b.basename(e),createdBy:n};return kt(n,{context:i.title||`Promoted from ${t}`,snippet:a,provenance:c,confidence:i.confidence??.7,concepts:s,tags:i.tags||[]},o,e)}function se(n,t,e){let o=b.join(e,X,n),r=b.join(K,n);for(let i of [o,r]){let s=b.join(i,`${t}${Y}`);if(g.existsSync(s))try{let a=g.readFileSync(s,"utf-8"),c=R.load(a);if(c)return c.appliedCount=(c.appliedCount||0)+1,c.updated=new Date().toISOString(),g.writeFileSync(s,R.dump(c,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var K,X,oe,Y,Nt=b$1(()=>{K=b.join(Q.homedir(),".paradigm","notebooks"),X=".paradigm/notebooks",oe="nb-",Y=".yaml";});var gt=".paradigm/events",Vt="stream.jsonl",J=1e3,$=[];function pt(n){return b.join(n,gt,Vt)}function zt(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${n}-${t}`}function M(n,t){let e={id:zt(),timestamp:new Date().toISOString(),...t};$.push(e),$.length>J&&($=$.slice(-J));try{let o=b.join(n,gt);g.mkdirSync(o,{recursive:!0});let r=pt(n);g.appendFileSync(r,JSON.stringify(e)+`
5
- `,"utf8"),Kt(r);}catch{}return e}function Kt(n){try{if(g.statSync(n).size>512*1024){let o=g.readFileSync(n,"utf8").trim().split(`
6
- `);if(o.length>J){let r=o.slice(-J);g.writeFileSync(n,r.join(`
7
- `)+`
8
- `,"utf8");}}}catch{}}function yt(n,t){let e=Xt(n);return t?.type&&(e=e.filter(o=>o.type===t.type)),t?.source&&(e=e.filter(o=>o.source===t.source)),t?.symbol&&(e=e.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(e=e.filter(o=>o.agent===t.agent)),t?.since&&(e=e.filter(o=>o.timestamp>=t.since)),e.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(e=e.slice(0,t.limit)),e}function Xt(n){let t=pt(n);if(!g.existsSync(t))return [...$];try{return g.readFileSync(t,"utf8").trim().split(`
9
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [...$]}}function ht(n,t,e){let o=0,r=0,i=0,s=0;if(e.symbols?.length&&n.symbols?.length)for(let u of e.symbols)for(let l of n.symbols)ft(u,l)&&(o=Math.max(o,1));if(e.paths?.length&&n.path){for(let u of e.paths)if(ft(u,n.path)){r=1;break}}if(e.concepts?.length){let u=[n.context||"",...n.keywords||[],n.type].join(" ").toLowerCase(),l=0;for(let m of e.concepts)u.includes(m.toLowerCase())&&l++;e.concepts.length>0&&(i=l/e.concepts.length);}if(e.signals?.length){for(let u of e.signals)if(u.type===n.type){s=1;break}}let a=[o,r,i,s].sort((u,l)=>l-u),c=a[0]*.5+a[1]*.2+a[2]*.15+a[3]*.15,d=e.threshold??.6;return {agentId:t,score:c,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:c>=d,quietReason:c<d?"below-threshold":void 0}}function ft(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var Yt=".paradigm/data-policy.yaml";function wt(n){let t=b.join(n,Yt);if(!g.existsSync(t))return {...b$3};try{let e=g.readFileSync(t,"utf8"),o=R.load(e);return Qt(b$3,o)}catch{return {...b$3}}}function Qt(n,t){let e={...n};if(t.version&&(e.version=t.version),t.default_ring&&(e.default_ring=t.default_ring),t.observation&&(e.observation={allow:t.observation.allow||n.observation?.allow,deny:[...n.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){e.streams={...n.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(e.streams[o]={...n.streams?.[o],...t.streams[o],deny_content:[...n.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(e.upstream={...n.upstream,...t.upstream}),t.network&&(e.network={...n.network,...t.network}),t.agent_overrides&&(e.agent_overrides={...n.agent_overrides,...t.agent_overrides}),t.deployment&&(e.deployment={...n.deployment,...t.deployment}),e}function _t(n,t,e){return e&&n.agent_overrides?.[e]?.observation&&n.agent_overrides[e].observation.deny?.some(r=>q(r,t))||n.observation?.deny?.some(o=>q(o,t))?false:n.observation?.allow?.length?n.observation.allow.some(o=>q(o,t)):true}function q(n,t){if(n===t)return true;let e=n.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${e}$`).test(t)}catch{return false}}var N=".paradigm/events",ae="nominations.jsonl",ce="debates.jsonl",le=500,de=200,ue=7,me=14,fe=100;function ge(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${n}-${t}`}function pe(){let n=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${n}-${t}`}function ye(n,t){let e=i(n),o=wt(n),r=[];for(let d of e){if(!d.attention||d.benched||t.path&&!_t(o,t.path,d.id))continue;let u=ht(t,d.id,d.attention);u.shouldNominate&&r.push({profile:d,score:u});}if(r.length===0)return {nominations:[],debates:[]};let i$1=E(n,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:d})=>!i$1.find(l=>l.agent===d.id&&l.brief===$t(d,t,{...r.find(m=>m.profile.id===d.id).score})));if(s.length===0)return {nominations:[],debates:[]};let a=s.map(({profile:d,score:u})=>{let l=he(t,u),m=be(d,t);return {id:ge(),agent:d.id,relevance:u.score,urgency:l,type:m,brief:$t(d,t,u),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});we(n,a);let c=Se(n,a);return c.length>0&&_e(n,c),{nominations:a,debates:c}}function he(n,t){return n.severity==="critical"?"critical":n.severity==="error"||n.type==="compliance-violation"||n.type==="error-encountered"?"high":n.type==="gate-added"||n.type==="route-created"||t.score>=.9?"medium":"low"}function be(n,t){let e=n.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":e==="advisory"||e==="lead"?"suggestion":"observation"}function $t(n,t,e){let o=n.role||n.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${n.id==="security"?"security implications":n.id==="tester"?"test coverage":n.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${n.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${n.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=e.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:e.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function Se(n,t){if(t.length<2)return [];let e=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(d=>d.agent)).size<2)continue;let a=new Set(i.map(d=>d.type)),c=a.size>1&&a.has("warning")&&a.has("suggestion");e.push({id:pe(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(d=>d.id),type:c?"conflicting":"complementary",overlap_events:[r]});}return e}function Z(n){return b.join(n,N,ae)}function tt(n){return b.join(n,N,ce)}function we(n,t){try{let e=b.join(n,N);g.mkdirSync(e,{recursive:!0});let o=Z(n),r=t.map(s=>JSON.stringify(s)).join(`
10
- `)+`
11
- `;g.appendFileSync(o,r,"utf8"),Tt(o,le);let{nominationTtlDays:i}=H(n);Rt(o,i*24*60*60*1e3);}catch{}}function _e(n,t){try{let e=b.join(n,N);g.mkdirSync(e,{recursive:!0});let o=tt(n),r=t.map(s=>JSON.stringify(s)).join(`
12
- `)+`
13
- `;g.appendFileSync(o,r,"utf8"),Tt(o,de);let{debateTtlDays:i}=H(n);Rt(o,i*24*60*60*1e3);}catch{}}function Tt(n,t){try{let o=g.readFileSync(n,"utf8").trim().split(`
14
- `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);g.writeFileSync(n,r.join(`
15
- `)+`
16
- `,"utf8");}}catch{}}function H(n){let t={nominationTtlDays:ue,debateTtlDays:me};try{let e=b.join(n,".paradigm","config.yaml");if(!g.existsSync(e))return t;let o=a("js-yaml"),r=g.readFileSync(e,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function Rt(n,t){try{if(!g.existsSync(n))return;let o=g.readFileSync(n,"utf8").trim().split(`
17
- `).filter(s=>s.trim());if(o.length<=fe)return;let r=Date.now()-t,i=o.filter(s=>{try{let a=JSON.parse(s);return (a.timestamp?new Date(a.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&g.writeFileSync(n,i.join(`
18
- `)+`
19
- `,"utf8");}catch{}}function E(n,t){let e=Z(n);if(!g.existsSync(e))return [];try{let r=g.readFileSync(e,"utf8").trim().split(`
20
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Pt(n){let t=tt(n);if(!g.existsSync(t))return [];try{return g.readFileSync(t,"utf8").trim().split(`
21
- `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Ot(n,t,e,o){let r=Z(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
22
- `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);return u.id===t?(u.engaged=!0,u.response=e,o&&(u.reason=o),a=!0,JSON.stringify(u)):d}catch{return d}});if(a&&(g.writeFileSync(r,c.join(`
23
- `)+`
24
- `,"utf8"),e==="accepted"||e==="dismissed")){let d=JSON.parse(s.find(l=>{try{return JSON.parse(l).id===t}catch{return !1}}));i(n).find(l=>l.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&M(n,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${e} \u2014 feedback for learning`,data:{nomination_id:t,response:e}});}return a}catch{return false}}function Ft(n,t,e,o){let r=tt(n);if(!g.existsSync(r))return false;try{let s=g.readFileSync(r,"utf8").trim().split(`
25
- `),a=!1,c=s.map(d=>{try{let u=JSON.parse(d);if(u.id===t){u.resolution={chosen:e,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},a=!0;let l=u.nominations.filter(m=>m!==e);for(let m of l){let y=E(n).find(f=>f.id===m);y&&M(n,{type:"work-completed",source:"agent-action",agent:y.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:e,reason:o}});}return JSON.stringify(u)}return d}catch{return d}});return a&&g.writeFileSync(r,c.join(`
26
- `)+`
27
- `,"utf8"),a}catch{return false}}function At(n){let t=b.join(n,N,".last-processed"),e="";try{g.existsSync(t)&&(e=g.readFileSync(t,"utf8").trim());}catch{}let o=b.join(n,N,"stream.jsonl");if(!g.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=g.readFileSync(o,"utf8").trim().split(`
28
- `).filter(l=>l.trim()).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(l=>l!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(e){let u=r.findIndex(l=>l.id===e);u>=0&&(i=u+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let a=[],c=s.slice(0,50);for(let u of c){let{nominations:l}=ye(n,u);a.push(...l);}let d=c[c.length-1];try{g.mkdirSync(b.join(n,N),{recursive:!0}),g.writeFileSync(t,d.id,"utf8");}catch{}return {processed:c.length,nominations:a}}function It(n,t){let e=f(n,t);if(!e?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=e.attention.threshold??.6,{nominationTtlDays:r}=H(n),i=r*24*60*60*1e3,c=E(n,{agent:t}).filter(j=>j.engaged||Date.now()-new Date(j.timestamp).getTime()<i).filter(j=>j.engaged);if(c.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${c.length}/5 engaged nominations)`};let d=c.filter(j=>j.response==="accepted").length,u=c.filter(j=>j.response==="dismissed").length,l=d/c.length,m=u/c.length,y=o,f$1="No adjustment needed";if(m>.6?(y=Math.min(.95,o+.05),f$1=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):l>.8&&(y=Math.max(.2,o-.05),f$1=`High accept rate (${(l*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),y===o)return {adjusted:false,oldThreshold:o,newThreshold:y,reason:f$1};e.attention.threshold=y;let p=b.join(n,".paradigm/agents",`${t}.agent`),x=g.existsSync(p)?"project":"global";return j(t,e,x,n),M(n,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${y.toFixed(2)} (${f$1})`,data:{old_threshold:o,new_threshold:y,accept_rate:l,dismiss_rate:m}}),{adjusted:true,oldThreshold:o,newThreshold:y,reason:f$1}}function et(n,t){let{nominationTtlDays:e}=H(n),o=e*24*60*60*1e3,i=E(n,{agent:t}).filter(l=>l.engaged||Date.now()-new Date(l.timestamp).getTime()<o),s=i.filter(l=>l.response==="accepted").length,a=i.filter(l=>l.response==="dismissed").length,c=i.filter(l=>l.response==="deferred").length,d=i.filter(l=>!l.engaged).length,u=s+a+c;return {total:i.length,accepted:s,dismissed:a,deferred:c,pending:d,acceptRate:u>0?s/u:0}}function Ct(n){let e=i(n).filter(l=>!l.benched).map(l=>{let m=et(n,l.id),y=0;try{let f=b.join(Q.homedir(),".paradigm","notebooks",l.id);g.existsSync(f)&&(y=g.readdirSync(f).filter(p=>p.endsWith(".yaml")).length);}catch{}return {id:l.id,acceptRate:m.acceptRate,threshold:l.attention?.threshold??.5,expertiseCount:(l.expertise||[]).length,notebookCount:y,transferableCount:(l.transferable||[]).length,totalNominations:m.total}}),o=e.length||1,r=e.reduce((l,m)=>l+m.acceptRate,0)/o,i$1=e.reduce((l,m)=>l+m.threshold,0)/o,s=e.reduce((l,m)=>l+m.expertiseCount,0),a=e.reduce((l,m)=>l+m.notebookCount,0),c=e.reduce((l,m)=>l+m.transferableCount,0),d=e.reduce((l,m)=>l+m.totalNominations,0),u;return d<10?u="cold-start":r<.5?u="accumulating":r<.7?u="calibrating":u="mature",{agents:e,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:a,totalTransferable:c},healthStatus:u}}function nt(n,t){let e,o;try{let c=(z(),d(vt)),d$1=(Nt(),d(xt));e=c.loadJournalEntries,o=d$1.addNotebookEntry;}catch{return {promoted:0,entries:[]}}let r=e(t,{trigger:"pattern_discovered",limit:100}),i=e(t,{trigger:"human_feedback",limit:100}),s=[...r,...i],a=[];for(let c of s)if(!c.promoted_to_notebook&&!((c.confidence_after??0)<.8))try{let{entry:d}=o(t,{context:c.pattern?.applies_when||c.insight.slice(0,80),snippet:c.pattern?.correct_approach||c.insight,concepts:c.tags||[c.pattern?.id||"learned-pattern"],provenance:{source:"journal-auto-promote",sourceId:c.id,createdBy:t}},"global",n);a.push({journalId:c.id,notebookId:d.id});try{let u=b.join(Q.homedir(),".paradigm","agents",t,"journal");if(g.existsSync(u)){let l=g.readdirSync(u).filter(m=>m.endsWith(".yaml"));for(let m of l){let y=b.join(u,m),f=g.readFileSync(y,"utf8");if(f.includes(c.id)){let p=f.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${d.id}"`);if(p===f){let x=f.trimEnd().split(`
29
- `);x.push(`promoted_to_notebook: "${d.id}"`),g.writeFileSync(y,x.join(`
30
- `)+`
31
- `,"utf8");}else g.writeFileSync(y,p,"utf8");break}}}}catch{}}catch{}return {promoted:a.length,entries:a}}var ve=".paradigm/surfacing.yaml";function Jt(n){let t=b.join(n,ve),e={default_min_urgency:"low",enable_debates:true};if(!g.existsSync(t))return e;try{let o=a("js-yaml"),r=g.readFileSync(t,"utf8"),i=o.load(r);return {...e,...i}}catch{return e}}function Mt(n,t){let e={critical:0,high:1,medium:2,low:3},o=e[t.default_min_urgency||"low"]??3;return n.filter(r=>{let i=e[r.urgency]??3;if(t.preferences){let s=t.preferences.find(a=>a.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(c=>r.urgency===c||r.type===c))return false;if(s.min_urgency){let a=e[s.min_urgency]??3;return i<=a}}}return i<=o})}var je=".paradigm/decisions";function Lt(n,t){let e=b.join(n,je);if(!g.existsSync(e))return [];let o=[],r=g.readdirSync(e).filter(s=>s.endsWith(".yaml"));for(let s of r)try{let a=g.readFileSync(b.join(e,s),"utf8"),c=R.load(a);c&&c.id&&o.push(c);}catch{}let i=o;return (i=i.filter(s=>s.status===t.status)),t?.participant&&(i=i.filter(s=>s.participants.some(a=>a.id===t.participant))),t?.symbol&&(i=i.filter(s=>s.symbols_affected?.includes(t.symbol))),t?.tag&&(i=i.filter(s=>s.tags?.some(a=>a.startsWith(t.tag)))),t?.dateFrom&&(i=i.filter(s=>s.timestamp>=t.dateFrom)),t?.dateTo&&(i=i.filter(s=>s.timestamp<=t.dateTo)),i.sort((s,a)=>a.timestamp.localeCompare(s.timestamp)),t?.limit&&(i=i.slice(0,t.limit)),i}z();function qe(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_neverland",description:"Neverland Validation \u2014 aggregate learning metrics across all agents. Shows acceptance rates, threshold drift, expertise growth, notebook counts, cross-project transfer, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature). ~200 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function Ee(n){let t=Date.now(),e=n.match(/^(\d+)(m|h|d)$/);if(e){let o=parseInt(e[1],10),r=e[2],i=r==="m"?o*6e4:r==="h"?o*36e5:o*864e5;return new Date(t-i).toISOString()}return n}async function Ge(n,t,e){let o=r=>JSON.stringify(r,null,2);switch(n){case "paradigm_ambient_nominations":{At(e.rootDir);let i=t.pending_only!==false,s=t.limit||20,a=E(e.rootDir,{agent:t.agent,urgency:t.urgency,pending_only:i,limit:s+20}),c=Jt(e.rootDir);a=Mt(a,c).slice(0,s);let d=b.join(e.rootDir,".paradigm/events/nominations.jsonl");if(g.existsSync(d))try{let l=g.readFileSync(d,"utf8"),m=new Set(a.map(f=>f.id)),y=l.trim().split(`
32
- `).map(f=>{try{let p=JSON.parse(f);return m.has(p.id)?(p.surfaced=!0,JSON.stringify(p)):f}catch{return f}});g.writeFileSync(d,y.join(`
33
- `)+`
34
- `,"utf8");}catch{}let u={count:a.length,nominations:a.map(l=>({id:l.id,agent:l.agent,urgency:l.urgency,type:l.type,brief:l.brief,relevance:l.relevance,timestamp:l.timestamp,engaged:l.engaged,response:l.response}))};if(t.include_debates){let m=Pt(e.rootDir).filter(y=>!y.resolution);u.debates=m.map(y=>({id:y.id,topic:y.topic,type:y.type,nominations:y.nominations})),u.debate_count=m.length;}return {text:o(u),handled:true}}case "paradigm_ambient_events":{let r=t.since?Ee(t.since):void 0,i=t.limit||50,s=yt(e.rootDir,{type:t.type,source:t.source,symbol:t.symbol,agent:t.agent,since:r,limit:i});return {text:o({count:s.length,events:s.map(a=>({id:a.id,type:a.type,source:a.source,timestamp:a.timestamp,path:a.path,symbols:a.symbols,context:a.context,agent:a.agent,tool:a.tool,severity:a.severity}))}),handled:true}}case "paradigm_ambient_engage":{let r=t.nomination_id,i=t.response,s=t.reason,a=Ot(e.rootDir,r,i,s);if(a)try{let{appendSessionWorkEntry:d}=await import('./session-work-log-5UJTJJ22.js'),l=E(e.rootDir,{limit:500}).find(m=>m.id===r);d(e.rootDir,{timestamp:new Date().toISOString(),type:"user-verdict",agent:l?.agent,nominationId:r,verdict:i,reason:s});}catch{}let c=false;return t.resolve_debate&&a&&(c=Ft(e.rootDir,t.resolve_debate,r,t.reason)),{text:o({engaged:a,nomination_id:r,response:i,debate_resolved:c||void 0}),handled:true}}case "paradigm_context_compose":{let r=t.agent,i=t.symbols||[],s=t.include_nominations!==false,a=t.include_decisions!==false,c=t.include_journal!==false,d=t.max_decisions||5,u=t.max_journal||5,l=f(e.rootDir,r);if(!l)return {text:o({error:`Agent profile not found: ${r}`}),handled:true};let m=[],y=p(l,i);if(y.trim()&&m.push(y),a){let f=Lt(e.rootDir,{status:"active",limit:d});if(f.length>0){m.push("## Recent Team Decisions");for(let p of f)m.push(`- **${p.title}**: ${p.decision.slice(0,150)}${p.decision.length>150?"...":""}`);m.push("");}}if(c){let f=O(r,{transferable:true,limit:u});if(f.length>0){m.push("## Transferable Insights");for(let p of f)m.push(`- [${p.trigger}] ${p.insight.slice(0,150)}${p.insight.length>150?"...":""}`);m.push("");}}if(s){let f=E(e.rootDir,{pending_only:true,limit:10});if(f.length>0){m.push("## Pending Nominations");for(let p of f)m.push(`- [${p.urgency}] ${p.brief}`);m.push("");}}return {text:o({agent:r,context:m.join(`
35
- `),sections_included:{profile:true,decisions:a,journal:c,nominations:s}}),handled:true}}case "paradigm_ambient_promote":{let r=t.agent,i=nt(e.rootDir,r);return {text:o({agent:r,promoted:i.promoted,entries:i.entries}),handled:true}}case "paradigm_ambient_learn":{let r=t.agent,i=t.dry_run===true,s=et(e.rootDir,r);if(i)return {text:o({agent:r,dry_run:true,stats:s,note:s.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(s.acceptRate*100).toFixed(0)}% \u2014 ${s.acceptRate>.8?"would lower threshold":s.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let a=It(e.rootDir,r);return {text:o({agent:r,...a,stats:s}),handled:true}}case "paradigm_ambient_neverland":{let r=Ct(e.rootDir);return {text:o(r),handled:true}}case "paradigm_ambient_learn_postflight":return {text:o(await xe(e.rootDir,t)),handled:true};default:return {text:`Unknown ambient tool: ${n}`,handled:false}}}var De={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ke(n){try{let t=b.join(n,".paradigm","config.yaml");if(g.existsSync(t)){let o=g.readFileSync(t,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(o)return o[1].trim()}}catch{}return b.basename(n)}async function xe(n,t={}){let e=t.dry_run===true,o=ke(n),r=b$2(n),i=r.filter(f=>f.type==="user-verdict"&&f.verdict&&f.agent);if(i.length===0)return {sessionEntries:r.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:e,details:[]};let s=new Map;for(let f of i){let p=f.agent;s.has(p)||s.set(p,[]),s.get(p).push(f);}let a=r.filter(f=>f.type==="agent-contribution"),c=new Map;for(let f of a)f.agent&&(c.has(f.agent)||c.set(f.agent,[]),c.get(f.agent).push(f));let d=[],u={},l=0;for(let[f,p]of s){u[f]=0;let x=p.filter(h=>h.verdict==="accepted").length;p.filter(h=>h.verdict==="dismissed").length;p.filter(h=>h.verdict==="revised").length;let U=p.length,Ut=U>0?x/U:0;for(let h of p){let B=De[h.verdict];if(!B)continue;let Bt=c.get(f)?.shift(),rt=Ne(h,Bt,{acceptRate:Ut,total:U,accepted:x}),Wt=h.verdict==="accepted"?.85:h.verdict==="revised"?.6:.4,qt={agent:f,verdict:h.verdict,trigger:B,insight:rt,symbols:h.symbols};if(d.push(qt),e)u[f]++,l++;else try{V(f,{trigger:B,insight:rt,confidence_before:h.verdict==="accepted"?.7:.8,confidence_after:Wt,project:o,transferable:h.verdict==="dismissed",tags:["postflight",`verdict:${h.verdict}`,...(h.symbols||[]).map(Gt=>`symbol:${Gt}`)]}),u[f]++,l++;}catch{}}}let m={},y=0;if(!e)for(let f of s.keys())try{let p=nt(n,f);p.promoted>0&&(m[f]=p.promoted,y+=p.promoted);}catch{}return {sessionEntries:r.length,agentsProcessed:Array.from(s.keys()),journalsWritten:l,journalsByAgent:u,promoted:y,promotedByAgent:m,dryRun:e,details:d}}function Ne(n,t,e){let o=n.symbols?.length?` (symbols: ${n.symbols.join(", ")})`:"",r=n.reason?` Reason: ${n.reason}.`:"";switch(n.verdict){case "accepted":return `Contribution accepted by user${o}.${r}`+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "dismissed":return `Contribution dismissed by user${o}.${r}`+(t?.contribution?` Rejected contribution: "${t.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;case "revised":return `Contribution revised by user${o}.${r}`+(n.revisionDelta?` Delta: "${n.revisionDelta.slice(0,120)}".`:"")+(t?.contribution?` Original: "${t.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(e.acceptRate*100).toFixed(0)}% (${e.accepted}/${e.total}).`;default:return `Unknown verdict "${n.verdict}"${o}.${r}`}}export{qe as getAmbientToolsList,Ge as handleAmbientTool,xe as runPostflightLearning};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b as b$1}from'./chunk-5TAVYPOV.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 S,j,$,R=b$1(()=>{S={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"}},j={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 b(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)/D);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 X(t,e){let o=W(e);return o?o.includes(t):true}function K(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 Q(){if(!l.existsSync(m))return [];try{return l.readdirSync(m).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function P(t,e){let o=g.join(t,_,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=x(n);return n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`),n}}catch{}let s=g.join(m,`${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=F(n,f),a=x(r);return r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification after merge \u2014 profile may have been tampered with`),r}catch{}if(n){let c=x(n);n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`);}return n}catch{}return null}function G(t,e){let o=C(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function Z(t,e){let o=P(t,e);return o||(G(t,e)[0]??null)}function C(t){let e=new Map;if(l.existsSync(m))try{let s=l.readdirSync(m).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(m,i),"utf-8"),c=h.load(n);if(c?.id){let f=x(c);c.__integrityStatus=f,f==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,_);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=F(f,c),a=x(r);r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${r.id}" failed integrity verification after merge \u2014 profile may have been tampered with`),e.set(c.id,r);}else {let r=x(c);c.__integrityStatus=r,r==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function w(t,e,o,s){let i=o==="global"?m:g.join(s||process.cwd(),_);l.existsSync(i)||l.mkdirSync(i,{recursive:true});let n=g.join(i,`${t}${y}`);e.permissions&&(e.integrityHash=I(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 q(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:S[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};S[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),j[t]&&(s.attention={...j[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=w(t,s,i,e.rootDir);return {profile:s,filePath:n}}function ee(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)=>b(n.entry.confidence,n.entry.lastTouch)-b(i.entry.confidence,i.entry.lastTouch))}function te(t,e,o){let s=P(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-A)*p.confidence+A*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=B(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,_,`${e}${y}`),r=l.existsSync(f)?"project":"global";return w(e,s,r,t),true}function ne(t,e,o){let s=P(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)*a.confidence+A*n);}let c=g.join(t,_,`${e}${y}`),f=l.existsSync(c)?"project":"global";return w(e,s,f,t),true}function se(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>b(i.confidence,i.lastTouch)-b(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 re(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)=>b(a.confidence,a.lastTouch)-b(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-b(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>M?" (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 ie(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-RVQI5GXL.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=P(t,e)||q(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(O=>O.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-A)*u.confidence+A*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,_,`${e}${y}`),p=l.existsSync(a)?"project":"global";w(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 x(t){let e=Y(t);return e.valid?e.reason&&e.reason.includes("No integrity hash")?"missing":"valid":"invalid"}function U(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(v(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(v(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(v(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(v(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function oe(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 ae(t,e){return e.type==="path"?U(t,e.path,e.mode):H(t,e.name)}function I(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?I(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 v(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function F(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 B(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 m,_,y,N,A,D,E,M,J=b$1(()=>{R();m=g.join(k.homedir(),".paradigm","agents"),_=".paradigm/agents",y=".agent",N=".paradigm/roster.yaml",A=.3,D=60,E=7,M=.2;});export{b as a,W as b,X as c,K as d,Q as e,P as f,G as g,Z as h,C as i,w as j,q as k,ee as l,te as m,ne as n,se as o,re as p,ie as q,d as r,x as s,U as t,H as u,oe as v,ae as w,I as x,Y as y,J as z};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- var e=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var i=Object.prototype.hasOwnProperty;var k=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var l=(a,b)=>()=>(a&&(b=a(a=0)),b);var m=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:true});},j=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of h(b))!i.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=g(b,d))||f.enumerable});return a};var n=a=>j(e({},"__esModule",{value:true}),a);export{k as a,l as b,m as c,n as d};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b as b$1,c as c$1,d}from'./chunk-5TAVYPOV.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={};c$1(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_context_check","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(),d(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_validate","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_context_check","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,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as l from'fs';import*as g from'path';import*as R from'os';import*as E from'crypto';import*as h from'js-yaml';var S={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"}},j={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 m=g.join(R.homedir(),".paradigm","agents"),_=".paradigm/agents",y=".agent",k=".paradigm/roster.yaml",A=.3,F=60,T=7,O=.2;function b(t,e){let s=(Date.now()-new Date(e).getTime())/(1e3*60*60*24);if(s<=T)return t;let i=Math.pow(.5,(s-T)/F);return t*i}function D(t){let e=g.join(t,k);if(!l.existsSync(e))return null;try{return h.load(l.readFileSync(e,"utf8"))?.active??null}catch{return null}}function J(t,e){let o=D(e);return o?o.includes(t):true}function z(t,e){let o=g.join(t,k),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 V(){if(!l.existsSync(m))return [];try{return l.readdirSync(m).filter(t=>t.endsWith(y)).map(t=>t.replace(y,""))}catch{return []}}function P(t,e){let o=g.join(t,_,`${e}${y}`);if(l.existsSync(o))try{let i=l.readFileSync(o,"utf-8"),n=h.load(i);if(n){let c=x(n);return n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`),n}}catch{}let s=g.join(m,`${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=C(n,f),a=x(r);return r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification after merge \u2014 profile may have been tampered with`),r}catch{}if(n){let c=x(n);n.__integrityStatus=c,c==="invalid"&&console.error(`[paradigm] WARNING: Agent "${e}" failed integrity verification \u2014 profile may have been tampered with`);}return n}catch{}return null}function M(t,e){let o=L(t),s=e.toLowerCase();return o.filter(i=>i.nickname?.toLowerCase()===s)}function X(t,e){let o=P(t,e);return o||(M(t,e)[0]??null)}function L(t){let e=new Map;if(l.existsSync(m))try{let s=l.readdirSync(m).filter(i=>i.endsWith(y));for(let i of s)try{let n=l.readFileSync(g.join(m,i),"utf-8"),c=h.load(n);if(c?.id){let f=x(c);c.__integrityStatus=f,f==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}let o=g.join(t,_);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=C(f,c),a=x(r);r.__integrityStatus=a,a==="invalid"&&console.error(`[paradigm] WARNING: Agent "${r.id}" failed integrity verification after merge \u2014 profile may have been tampered with`),e.set(c.id,r);}else {let r=x(c);c.__integrityStatus=r,r==="invalid"&&console.error(`[paradigm] WARNING: Agent "${c.id}" failed integrity verification \u2014 profile may have been tampered with`),e.set(c.id,c);}}catch{}}catch{}return Array.from(e.values())}function w(t,e,o,s){let i=o==="global"?m:g.join(s||process.cwd(),_);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 W(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:S[t]||{style:"balanced",risk:"balanced",verbosity:"concise"},expertise:[],transferable:[],contexts:{},created:o,updated:o};S[t]||(s.personality={style:"deliberate",risk:"balanced",verbosity:"concise"}),j[t]&&(s.attention={...j[t]}),$[t]&&(s.collaboration={...$[t]});let i=e.scope||"global",n=w(t,s,i,e.rootDir);return {profile:s,filePath:n}}function K(t,e){let o=L(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)=>b(n.entry.confidence,n.entry.lastTouch)-b(i.entry.confidence,i.entry.lastTouch))}function Q(t,e,o){let s=P(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-A)*p.confidence+A*o.confidence)):n.push({symbol:a,confidence:o.confidence??.5,sessions:1,lastTouch:i});}s.expertise=n;let c=H(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,_,`${e}${y}`),r=l.existsSync(f)?"project":"global";return w(e,s,r,t),true}function Z(t,e,o){let s=P(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)*a.confidence+A*n);}let c=g.join(t,_,`${e}${y}`),f=l.existsSync(c)?"project":"global";return w(e,s,f,t),true}function ee(t,e,o){return e?{personality:e.personality||null,topExpertise:(e.expertise||[]).sort((s,i)=>b(i.confidence,i.lastTouch)-b(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 te(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)=>b(a.confidence,a.lastTouch)-b(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-b(r.confidence,r.lastTouch)/r.confidence,u=r.confidence>0&&p>O?" (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 ne(t,e,o=false){let{loadLoreEntries:s}=await import('./lore-loader-XY5MZRR2.js'),i=await s(t,{limit:500}),n=0,c=new Set,f=P(t,e)||W(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(I=>I.symbol===p);u?(u.sessions++,u.lastTouch=a.timestamp,a.confidence!=null&&(u.confidence=(1-A)*u.confidence+A*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,_,`${e}${y}`),p=l.existsSync(a)?"project":"global";w(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 x(t){let e=U(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(v(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(v(f,e))return {allowed:true};return {allowed:false,reason:`No ${o} pattern matches: ${e}`}}return {allowed:true}}function q(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(v(i,e))return {allowed:false,reason:`Tool denied by pattern: ${i}`}}if(o&&o.length>0){for(let i of o)if(v(i,e))return {allowed:true};return {allowed:false,reason:`Tool not in allow list: ${e}`}}return {allowed:true}}function se(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 re(t,e){return e.type==="path"?G(t,e.path,e.mode):q(t,e.name)}function N(t){let e=JSON.stringify({id:t.id,role:t.role,permissions:t.permissions||null});return E.createHash("sha256").update(e).digest("hex")}function U(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 v(t,e){let o=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}function C(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 H(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{b as a,D as b,J as c,z as d,V as e,P as f,M as g,X as h,L as i,w as j,W as k,K as l,Q as m,Z as n,ee as o,te as p,ne as q,d as r,x as s,G as t,q as u,se as v,re as w,N as x,U as y};
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as s from'fs';import*as a from'path';import*as v from'os';import*as l from'crypto';var g=a.join(v.homedir(),".paradigm","score"),q=a.join(v.homedir(),".paradigm","mail"),y=a.join(g,"agents"),h=a.join(g,"threads"),S=a.join(g,"file-requests"),M=a.join(g,"trust.yaml"),H=3600*1e3,F={users:{},defaults:{level:"restricted",autoApprove:[],neverApprove:[".env*","**/*.key","**/*.pem","**/credentials*","**/secrets/**"]}};function K(){if(s.existsSync(q)&&!s.existsSync(g))try{s.renameSync(q,g);}catch{}}function d(){K();for(let t of [y,h,S])s.existsSync(t)||s.mkdirSync(t,{recursive:true});}function p(t){return a.join(y,t)}function A(t){let n=p(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 N(t,n){let e=a.dirname(t);s.existsSync(e)||s.mkdirSync(e,{recursive:true}),s.appendFileSync(t,JSON.stringify(n)+`
4
- `,"utf-8");}function D(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"unknown"}function E(t){try{let n=a.join(t,".paradigm","config.yaml");if(s.existsSync(n)){let r=s.readFileSync(n,"utf-8").match(/^project:\s*(.+)$/m);if(r)return D(r[1].trim().replace(/["']/g,""))}}catch{}return D(a.basename(t))}function C(t,n){return `${E(t)}/${n||"core"}`}function X(t,n,e){d();let r=C(t,n),i=A(r),o=E(t),c={id:r,name:e||`${o} (${n||"core"})`,type:"agent",project:o,role:n||"core",pid:process.pid,startedAt:new Date().toISOString(),label:e};return s.writeFileSync(a.join(i,"identity.json"),JSON.stringify(c,null,2),"utf-8"),c}function Y(t){let n=p(t);if(!s.existsSync(n))return false;try{return s.rmSync(n,{recursive:!0,force:!0}),!0}catch{return false}}function R(){if(d(),!s.existsSync(y))return [];let t=[],n=s.readdirSync(y,{withFileTypes:true}).filter(e=>e.isDirectory());for(let e of n){let r=a.join(y,e.name),i=s.readdirSync(r,{withFileTypes:true}).filter(o=>o.isDirectory());for(let o of i){let c=a.join(r,o.name,"identity.json");if(s.existsSync(c))try{let u=s.readFileSync(c,"utf-8"),f=JSON.parse(u);t.push(f);}catch{}}}return t}function tt(){let t=R(),n=0;for(let e of t)T(e.pid)||(Y(e.id),n++);return n}function et(t){let n=C(t),e=a.join(p(n),"identity.json");if(!s.existsSync(e))return null;try{return JSON.parse(s.readFileSync(e,"utf-8"))}catch{return null}}function nt(t,n){let e=a.join(p(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 rt(t,n=6e4){if(!t.lastPoll)return true;let e=new Date(t.lastPoll).getTime();return Date.now()-e>n}function st(){let n=R().filter(e=>T(e.pid));try{let e=a.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 o=s.readFileSync(a.join(e,i),"utf-8"),c=JSON.parse(o),u=parseInt(a.basename(i,".json"),10);!n.some(f=>f.pid===u)&&T(u)&&n.push({id:`conductor/${u}`,name:c.label||`Session ${u}`,type:"agent",project:c.projectDir?a.basename(c.projectDir):"unknown",role:"conductor",pid:u,startedAt:c.registeredAt||new Date().toISOString()});}catch{}}}catch{}return n}function P(t){return a.join(p(t),"inbox.jsonl")}function b(t){return a.join(p(t),"outbox.jsonl")}function J(t){return a.join(p(t),"ack.json")}function O(t,n){A(t),N(P(t),n);}function it(t,n){let e=x(P(t));if(!n){let i=$(t);if(i){let o=e.findIndex(c=>c.id===i);if(o>=0)return e.slice(o+1)}return e}let r=e.findIndex(i=>i.id===n);return r>=0?e.slice(r+1):e}function Q(t,n){A(t),N(b(t),n);}function ot(t){return x(b(t))}function at(t,n){let e=J(t);A(t),s.writeFileSync(e,JSON.stringify({lastAck:n}),"utf-8");}function $(t){let n=J(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8")).lastAck||null}catch{return null}}function ct(t){let n=$(t);if(!n)return 0;let e=P(t),r=x(e),i=r.findIndex(u=>u.id===n);if(i<0)return 0;let o=r.slice(i+1),c=r.length-o.length;return o.length===0?s.existsSync(e)&&s.writeFileSync(e,"","utf-8"):s.writeFileSync(e,o.map(u=>JSON.stringify(u)).join(`
5
- `)+`
6
- `,"utf-8"),c}function j(t){return a.join(h,`${t}.json`)}function ut(t,n){d();let e="thr-"+l.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(j(e),JSON.stringify(i,null,2),"utf-8"),i}function z(t){let n=j(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function ft(t){if(d(),!s.existsSync(h))return [];let n=s.readdirSync(h).filter(r=>r.endsWith(".json")),e=[];for(let r of n)try{let i=s.readFileSync(a.join(h,r),"utf-8"),o=JSON.parse(i);(!t||o.status===t)&&e.push(o);}catch{}return e.sort((r,i)=>i.lastActivity.localeCompare(r.lastActivity))}function _(t,n){let e=z(t);if(!e)return false;let r={...e,...n};return s.writeFileSync(j(t),JSON.stringify(r,null,2),"utf-8"),true}function lt(t,n){return _(t,{status:"resolved",resolvedAt:new Date().toISOString(),decision:n})}function dt(t){let n=R(),e=[];for(let r of n){let i=x(P(r.id)),o=x(b(r.id));for(let c of [...i,...o])(c.threadRoot===t||c.id===t)&&(e.some(u=>u.id===c.id)||e.push(c));}return e.sort((r,i)=>r.timestamp.localeCompare(i.timestamp))}function B(t){return {id:l.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 L(t){d(),Q(t.sender.id,t);let n=0;if(t.recipients&&t.recipients.length>0)for(let e of t.recipients)O(e.id,t),n++;else {let e=R();for(let r of e)r.id!==t.sender.id&&(O(r.id,t),n++);}if(t.threadRoot){let e=z(t.threadRoot);if(e){let i=e.participants.some(o=>o.id===t.sender.id)?e.participants:[...e.participants,t.sender];_(t.threadRoot,{participants:i,lastActivity:t.timestamp,messageCount:e.messageCount+1});}}return n}function m(t){return a.join(S,`${t}.json`)}function V(){if(!s.existsSync(M))return F;try{let t=s.readFileSync(M,"utf-8");try{return JSON.parse(t)}catch{return F}}catch{return F}}function pt(t){d();let n="freq-"+l.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(m(n),JSON.stringify(e,null,2),"utf-8"),e}function U(t){let n=m(t);if(!s.existsSync(n))return null;try{return JSON.parse(s.readFileSync(n,"utf-8"))}catch{return null}}function Z(t){if(d(),!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(a.join(S,r),"utf-8"),o=JSON.parse(i);(!t||o.status===t)&&e.push(o);}catch{}return e.sort((r,i)=>i.createdAt.localeCompare(r.createdAt))}function gt(t,n,e){let r=U(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=a.resolve(n,r.request.filePath);if(!i.startsWith(a.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 o=s.readFileSync(i,"utf-8"),c="utf8";if(e){let G=[/(?: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-----/];o=o.split(`
7
- `).map(I=>{for(let W of G)if(W.test(I))return "[REDACTED]";return I}).join(`
8
- `);}let u=l.createHash("sha256").update(o).digest("hex"),f={requestId:t,filePath:r.request.filePath,content:o,encoding:c,size:Buffer.byteLength(o),hash:u};r.status="approved",r.resolvedAt=new Date().toISOString(),r.delivery=f,s.writeFileSync(m(t),JSON.stringify(r,null,2),"utf-8");let k=B({sender:{id:"system",name:"File Transfer",type:"human"},recipients:[r.request.requester],intent:"fileDelivery",text:`File delivered: ${r.request.filePath} (${f.size} bytes, SHA-256: ${u.slice(0,12)}...)`,threadRoot:r.request.threadRoot,symbols:[]});return k.attachments=[{name:a.basename(r.request.filePath),type:"file",content:f.content,encoding:f.encoding}],L(k),{success:!0,delivery:f}}catch(o){return {success:false,error:`Failed to read file: ${o.message}`}}}function yt(t,n){let e=U(t);if(!e||e.status!=="pending")return false;e.status="denied",e.resolvedAt=new Date().toISOString(),e.denyReason=n,s.writeFileSync(m(t),JSON.stringify(e,null,2),"utf-8");let r=B({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 L(r),true}function w(t,n){let e=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\{\{GLOBSTAR\}\}/g,".*");return new RegExp(`^${e}$`).test(t)}function ht(t,n,e){let r=n||V();if(e&&r.users[e]){for(let i of r.users[e].neverApprove)if(w(t,i))return true}for(let i of r.defaults.neverApprove)if(w(t,i))return true;return false}function St(){let t=Z("pending"),n=0;for(let e of t)Date.now()-new Date(e.createdAt).getTime()>H&&(e.status="expired",e.resolvedAt=new Date().toISOString(),s.writeFileSync(m(e.request.requestId),JSON.stringify(e,null,2),"utf-8"),n++);return n}function T(t){try{return process.kill(t,0),!0}catch{return false}}export{ht as A,St as B,C as a,X as b,Y as c,R as d,tt as e,et as f,nt as g,rt as h,st as i,O as j,it as k,ot as l,at as m,ct as n,ut as o,z as p,ft as q,lt as r,dt as s,B as t,L as u,V as v,pt as w,Z as x,gt as y,yt as z};