agentix-cli 0.25.0 → 0.27.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 (269) hide show
  1. package/README.md +2 -0
  2. package/dist/{App-6Y7B3YQH.js → App-U52IPUK2.js} +2 -2
  3. package/dist/{ChatApp-KIEUJ2DS.js → ChatApp-XP4OMHPL.js} +2 -2
  4. package/dist/agent-V2CA4TXD.js +2 -0
  5. package/dist/article-fields-L4D2BOGY.js +2 -0
  6. package/dist/article-quality-44ONVGLN.js +3 -0
  7. package/dist/article-quality-44ONVGLN.js.map +1 -0
  8. package/dist/{audit-JU3HWISB.js → audit-4245CX6P.js} +2 -2
  9. package/dist/backfill-MTD2B62I.js +6 -0
  10. package/dist/backfill-MTD2B62I.js.map +1 -0
  11. package/dist/{board-dashboard-CQ5F4GPD.js → board-dashboard-TTMAYRLG.js} +2445 -519
  12. package/dist/board-dashboard-TTMAYRLG.js.map +1 -0
  13. package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
  14. package/dist/calibration-ILS5OI44.js +2 -0
  15. package/dist/chunk-2T5W3ETS.js +5 -0
  16. package/dist/{chunk-FDMWOPEL.js.map → chunk-2T5W3ETS.js.map} +1 -1
  17. package/dist/chunk-3SCPRYJB.js +5 -0
  18. package/dist/chunk-3SCPRYJB.js.map +1 -0
  19. package/dist/chunk-4BR7D2OU.js +36 -0
  20. package/dist/chunk-4BR7D2OU.js.map +1 -0
  21. package/dist/{chunk-P4VWIVKN.js → chunk-52ZPELD2.js} +403 -29
  22. package/dist/chunk-52ZPELD2.js.map +1 -0
  23. package/dist/{chunk-5U35WAZF.js → chunk-77OV7346.js} +6 -6
  24. package/dist/chunk-77OV7346.js.map +1 -0
  25. package/dist/chunk-AJ5RMU7X.js +2 -0
  26. package/dist/chunk-AJ5RMU7X.js.map +1 -0
  27. package/dist/chunk-AJONZWLT.js +2 -0
  28. package/dist/chunk-AJONZWLT.js.map +1 -0
  29. package/dist/chunk-AX2PWSRT.js +114 -0
  30. package/dist/chunk-AX2PWSRT.js.map +1 -0
  31. package/dist/chunk-BH3GTCZ6.js +2 -0
  32. package/dist/chunk-BH3GTCZ6.js.map +1 -0
  33. package/dist/chunk-BPIRO4YD.js +126 -0
  34. package/dist/chunk-BPIRO4YD.js.map +1 -0
  35. package/dist/chunk-CJQQIRPD.js +13 -0
  36. package/dist/chunk-CJQQIRPD.js.map +1 -0
  37. package/dist/chunk-DCDQZR7I.js +24 -0
  38. package/dist/chunk-DCDQZR7I.js.map +1 -0
  39. package/dist/chunk-EVWEG3VD.js +3 -0
  40. package/dist/chunk-EVWEG3VD.js.map +1 -0
  41. package/dist/chunk-F4HZTZHW.js +2 -0
  42. package/dist/chunk-F4HZTZHW.js.map +1 -0
  43. package/dist/chunk-F6CNF7V3.js +25 -0
  44. package/dist/chunk-F6CNF7V3.js.map +1 -0
  45. package/dist/chunk-FIEJDZVC.js +121 -0
  46. package/dist/chunk-FIEJDZVC.js.map +1 -0
  47. package/dist/chunk-FIOB3MEX.js +2 -0
  48. package/dist/{chunk-H5D7ATXS.js → chunk-FKBGJYWQ.js} +5 -5
  49. package/dist/chunk-FKBGJYWQ.js.map +1 -0
  50. package/dist/chunk-GDWJUGB5.js +9 -0
  51. package/dist/chunk-GDWJUGB5.js.map +1 -0
  52. package/dist/{chunk-TRJTTBE2.js → chunk-IB3F7VBE.js} +7 -7
  53. package/dist/{chunk-TRJTTBE2.js.map → chunk-IB3F7VBE.js.map} +1 -1
  54. package/dist/chunk-IBUSGCLQ.js +109 -0
  55. package/dist/chunk-IBUSGCLQ.js.map +1 -0
  56. package/dist/{chunk-LDHPMJ7M.js → chunk-IWMW5432.js} +3 -3
  57. package/dist/chunk-IWMW5432.js.map +1 -0
  58. package/dist/chunk-K33GIBSE.js +2 -0
  59. package/dist/chunk-K33GIBSE.js.map +1 -0
  60. package/dist/chunk-L2IZPR6P.js +45 -0
  61. package/dist/chunk-L2IZPR6P.js.map +1 -0
  62. package/dist/chunk-L2WSPY6S.js +2 -0
  63. package/dist/chunk-L2WSPY6S.js.map +1 -0
  64. package/dist/chunk-LCIREYTD.js +54 -0
  65. package/dist/chunk-LCIREYTD.js.map +1 -0
  66. package/dist/chunk-LNRB5MCU.js +530 -0
  67. package/dist/chunk-LNRB5MCU.js.map +1 -0
  68. package/dist/chunk-OPHIXXGI.js +157 -0
  69. package/dist/chunk-OPHIXXGI.js.map +1 -0
  70. package/dist/{chunk-JTJIPNXY.js → chunk-PNWNVOEZ.js} +1 -1
  71. package/dist/chunk-PNWNVOEZ.js.map +1 -0
  72. package/dist/{chunk-LNXCJWOU.js → chunk-UFAGYX73.js} +45 -47
  73. package/dist/chunk-UFAGYX73.js.map +1 -0
  74. package/dist/{chunk-DJEZ2HVU.js → chunk-VDMYBPYB.js} +1 -1
  75. package/dist/chunk-VDMYBPYB.js.map +1 -0
  76. package/dist/chunk-VTE7L6LO.js +5 -0
  77. package/dist/{chunk-G57RZCXM.js.map → chunk-VTE7L6LO.js.map} +1 -1
  78. package/dist/chunk-W5C2GDNC.js +32 -0
  79. package/dist/{chunk-JP5IEXR7.js.map → chunk-W5C2GDNC.js.map} +1 -1
  80. package/dist/chunk-WPMX3VGI.js +3 -0
  81. package/dist/chunk-WPMX3VGI.js.map +1 -0
  82. package/dist/chunk-WZ72HX5C.js +1182 -0
  83. package/dist/chunk-WZ72HX5C.js.map +1 -0
  84. package/dist/chunk-ZTEU5JVQ.js +2 -0
  85. package/dist/chunk-ZTEU5JVQ.js.map +1 -0
  86. package/dist/{chunk-2WVX3LEC.js → chunk-ZVP6GB4G.js} +1 -1
  87. package/dist/chunk-ZVP6GB4G.js.map +1 -0
  88. package/dist/cli.js +1 -1
  89. package/dist/cli.js.map +1 -1
  90. package/dist/client-PX25MD47.js +2 -0
  91. package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
  92. package/dist/config-HL5F36V4.js +2 -0
  93. package/dist/config-mutator-HBX53OMJ.js +2 -0
  94. package/dist/{conflict-detector-D7VIYPDI.js → conflict-detector-ZPOT3M2C.js} +2 -2
  95. package/dist/conflict-detector-ZPOT3M2C.js.map +1 -0
  96. package/dist/context-planner-AQHJMVY2.js +17 -0
  97. package/dist/context-planner-AQHJMVY2.js.map +1 -0
  98. package/dist/debug-3MEUO2P2.js +2 -0
  99. package/dist/{discover-XJXQXXIO.js → discover-D4VVRNAI.js} +2 -2
  100. package/dist/discover-D4VVRNAI.js.map +1 -0
  101. package/dist/doctor-PBAH6XL3.js +2 -0
  102. package/dist/editor-chat-OB7IQOB5.js +137 -0
  103. package/dist/editor-chat-OB7IQOB5.js.map +1 -0
  104. package/dist/entry-triage-LK34TSQD.js +2 -0
  105. package/dist/entry-triage-LK34TSQD.js.map +1 -0
  106. package/dist/facts-YVEJOM7O.js +22 -0
  107. package/dist/facts-YVEJOM7O.js.map +1 -0
  108. package/dist/heal-FVLBHYP7.js +2 -0
  109. package/dist/index.d.ts +1073 -65
  110. package/dist/index.js +13 -13
  111. package/dist/index.js.map +1 -1
  112. package/dist/{ingest-whatsapp-LZE62INA.js → ingest-whatsapp-NS4OWDOU.js} +2 -2
  113. package/dist/loader-4ZGTK7LD.js +2 -0
  114. package/dist/loader-BOKE5M5S.js +2 -0
  115. package/dist/memory-extract-F5ZHWY5E.js +2 -0
  116. package/dist/{migrate-v2-QO7SLKIM.js → migrate-v2-V4WN2VVM.js} +2 -2
  117. package/dist/ntfy-X7EPB3TG.js +4 -0
  118. package/dist/ntfy-X7EPB3TG.js.map +1 -0
  119. package/dist/processes-WU23U2OJ.js +2 -0
  120. package/dist/program-YGXVCV2Y.js +2 -0
  121. package/dist/{projects-api-KRME2YKZ.js → projects-api-QE6L65SK.js} +2 -2
  122. package/dist/{projects-mutate-3NHVG437.js → projects-mutate-MY7JTLSZ.js} +2 -2
  123. package/dist/providers-KO2DODIO.js +2 -0
  124. package/dist/query-ZKTFJMNE.js +2 -0
  125. package/dist/questions-4B4KSPXG.js +3 -0
  126. package/dist/questions-4B4KSPXG.js.map +1 -0
  127. package/dist/recipes-7S4MC5OJ.js +2 -0
  128. package/dist/registry-PSZDPFZK.js +2 -0
  129. package/dist/review-candidates-AEUXRQQC.js +4 -0
  130. package/dist/review-candidates-AEUXRQQC.js.map +1 -0
  131. package/dist/review-store-B4YE3EFK.js +4 -0
  132. package/dist/review-store-B4YE3EFK.js.map +1 -0
  133. package/dist/{rotation-memo-B3EXXSEH.js → rotation-memo-7T75BLEX.js} +2 -2
  134. package/dist/routing-4PV66BK6.js +2 -0
  135. package/dist/routing-4PV66BK6.js.map +1 -0
  136. package/dist/runner-YRBVNYTY.js +2 -0
  137. package/dist/scheduler-GZZAN6ZG.js +2 -0
  138. package/dist/seat-VZ7AVO27.js +2 -0
  139. package/dist/select-F5I5PO2O.js +2 -0
  140. package/dist/select-F5I5PO2O.js.map +1 -0
  141. package/dist/store-MCOA6N4F.js +2 -0
  142. package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
  143. package/dist/{surface-usage-PRL6Z4U3.js → surface-usage-NS74AXSE.js} +2 -2
  144. package/dist/timers-PCB4ZIBD.js +2 -0
  145. package/dist/triage-backtest-JNO7RKX7.js +2 -0
  146. package/dist/triage-backtest-JNO7RKX7.js.map +1 -0
  147. package/dist/types-H5ENIUIT.js +2 -0
  148. package/dist/types-OIFU3KSQ.js +2 -0
  149. package/dist/web/workflow-editor.global.js +1542 -0
  150. package/dist/web/workflow-editor.global.js.map +1 -0
  151. package/dist/{whatsapp-state-XMTCSRXU.js → whatsapp-state-6D6FHHD2.js} +2 -2
  152. package/dist/wiki-N5SMP3DT.js +2 -0
  153. package/dist/wiki-N5SMP3DT.js.map +1 -0
  154. package/dist/workflows/templates/branching.yaml +1 -1
  155. package/dist/{workspace-setup-TBQAHYHJ.js → workspace-setup-B3F3TUDE.js} +2 -2
  156. package/dist/workspace-setup-B3F3TUDE.js.map +1 -0
  157. package/package.json +1 -1
  158. package/dist/agent-QGZIAZMY.js +0 -2
  159. package/dist/architect-SEPWMWS4.js +0 -2
  160. package/dist/board-dashboard-CQ5F4GPD.js.map +0 -1
  161. package/dist/chunk-2WVX3LEC.js.map +0 -1
  162. package/dist/chunk-3WQFCIB6.js +0 -24
  163. package/dist/chunk-3WQFCIB6.js.map +0 -1
  164. package/dist/chunk-4YCH6IZV.js +0 -2
  165. package/dist/chunk-53GCFZPR.js +0 -116
  166. package/dist/chunk-53GCFZPR.js.map +0 -1
  167. package/dist/chunk-53NRX2NA.js +0 -2
  168. package/dist/chunk-53NRX2NA.js.map +0 -1
  169. package/dist/chunk-5U35WAZF.js.map +0 -1
  170. package/dist/chunk-BFXONUUN.js +0 -108
  171. package/dist/chunk-BFXONUUN.js.map +0 -1
  172. package/dist/chunk-BFZUG66X.js +0 -45
  173. package/dist/chunk-BFZUG66X.js.map +0 -1
  174. package/dist/chunk-DJEZ2HVU.js.map +0 -1
  175. package/dist/chunk-FDMWOPEL.js +0 -5
  176. package/dist/chunk-FDWOECJY.js +0 -54
  177. package/dist/chunk-FDWOECJY.js.map +0 -1
  178. package/dist/chunk-G57RZCXM.js +0 -5
  179. package/dist/chunk-H5D7ATXS.js.map +0 -1
  180. package/dist/chunk-HA3XI7Z2.js +0 -155
  181. package/dist/chunk-HA3XI7Z2.js.map +0 -1
  182. package/dist/chunk-HR4JSRZS.js +0 -3
  183. package/dist/chunk-HR4JSRZS.js.map +0 -1
  184. package/dist/chunk-ISEBLHWX.js +0 -118
  185. package/dist/chunk-ISEBLHWX.js.map +0 -1
  186. package/dist/chunk-JP5IEXR7.js +0 -32
  187. package/dist/chunk-JTJIPNXY.js.map +0 -1
  188. package/dist/chunk-JXWAGMI2.js +0 -13
  189. package/dist/chunk-JXWAGMI2.js.map +0 -1
  190. package/dist/chunk-KUCCW2VG.js +0 -431
  191. package/dist/chunk-KUCCW2VG.js.map +0 -1
  192. package/dist/chunk-LDHPMJ7M.js.map +0 -1
  193. package/dist/chunk-LNXCJWOU.js.map +0 -1
  194. package/dist/chunk-NGSIRE4X.js +0 -126
  195. package/dist/chunk-NGSIRE4X.js.map +0 -1
  196. package/dist/chunk-P4VWIVKN.js.map +0 -1
  197. package/dist/chunk-Q6YO7LYE.js +0 -47
  198. package/dist/chunk-Q6YO7LYE.js.map +0 -1
  199. package/dist/chunk-SR3X25TN.js +0 -3
  200. package/dist/chunk-SR3X25TN.js.map +0 -1
  201. package/dist/chunk-TMKLHTCG.js +0 -971
  202. package/dist/chunk-TMKLHTCG.js.map +0 -1
  203. package/dist/chunk-VJUTQAPJ.js +0 -2
  204. package/dist/chunk-VJUTQAPJ.js.map +0 -1
  205. package/dist/client-GGVVLOOF.js +0 -2
  206. package/dist/config-7FSZFRTQ.js +0 -2
  207. package/dist/config-mutator-POCOYYJ4.js +0 -2
  208. package/dist/conflict-detector-D7VIYPDI.js.map +0 -1
  209. package/dist/context-planner-45GEWKGL.js +0 -17
  210. package/dist/context-planner-45GEWKGL.js.map +0 -1
  211. package/dist/debug-N3B5NVJU.js +0 -2
  212. package/dist/discover-XJXQXXIO.js.map +0 -1
  213. package/dist/doctor-DHLBEKA4.js +0 -2
  214. package/dist/heal-HZ3EQD52.js +0 -2
  215. package/dist/loader-5CA3O5GM.js +0 -2
  216. package/dist/loader-6IHUCPVO.js +0 -2
  217. package/dist/memory-extract-AENFVVO5.js +0 -2
  218. package/dist/processes-UIC4XXA6.js +0 -2
  219. package/dist/program-WVAVJFND.js +0 -2
  220. package/dist/providers-L27BJ5A6.js +0 -2
  221. package/dist/query-HZYYRCLU.js +0 -2
  222. package/dist/recipes-EPLE2SNT.js +0 -2
  223. package/dist/registry-T36ZIAWV.js +0 -2
  224. package/dist/runner-BFYDWPUO.js +0 -2
  225. package/dist/scheduler-GH7TIKYS.js +0 -2
  226. package/dist/store-I3HEWVLQ.js +0 -2
  227. package/dist/timers-5LPZN55J.js +0 -2
  228. package/dist/types-VECTMYTO.js +0 -2
  229. package/dist/types-Y6ZCZ52Z.js +0 -2
  230. package/dist/wiki-M6YNRFC4.js +0 -2
  231. /package/dist/{App-6Y7B3YQH.js.map → App-U52IPUK2.js.map} +0 -0
  232. /package/dist/{ChatApp-KIEUJ2DS.js.map → ChatApp-XP4OMHPL.js.map} +0 -0
  233. /package/dist/{agent-QGZIAZMY.js.map → agent-V2CA4TXD.js.map} +0 -0
  234. /package/dist/{architect-SEPWMWS4.js.map → article-fields-L4D2BOGY.js.map} +0 -0
  235. /package/dist/{audit-JU3HWISB.js.map → audit-4245CX6P.js.map} +0 -0
  236. /package/dist/{builtin-FRKAQMFS.js.map → builtin-B67DMJ3M.js.map} +0 -0
  237. /package/dist/{chunk-4YCH6IZV.js.map → calibration-ILS5OI44.js.map} +0 -0
  238. /package/dist/{client-GGVVLOOF.js.map → chunk-FIOB3MEX.js.map} +0 -0
  239. /package/dist/{config-7FSZFRTQ.js.map → client-PX25MD47.js.map} +0 -0
  240. /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
  241. /package/dist/{config-mutator-POCOYYJ4.js.map → config-HL5F36V4.js.map} +0 -0
  242. /package/dist/{debug-N3B5NVJU.js.map → config-mutator-HBX53OMJ.js.map} +0 -0
  243. /package/dist/{doctor-DHLBEKA4.js.map → debug-3MEUO2P2.js.map} +0 -0
  244. /package/dist/{heal-HZ3EQD52.js.map → doctor-PBAH6XL3.js.map} +0 -0
  245. /package/dist/{loader-5CA3O5GM.js.map → heal-FVLBHYP7.js.map} +0 -0
  246. /package/dist/{ingest-whatsapp-LZE62INA.js.map → ingest-whatsapp-NS4OWDOU.js.map} +0 -0
  247. /package/dist/{loader-6IHUCPVO.js.map → loader-4ZGTK7LD.js.map} +0 -0
  248. /package/dist/{memory-extract-AENFVVO5.js.map → loader-BOKE5M5S.js.map} +0 -0
  249. /package/dist/{processes-UIC4XXA6.js.map → memory-extract-F5ZHWY5E.js.map} +0 -0
  250. /package/dist/{migrate-v2-QO7SLKIM.js.map → migrate-v2-V4WN2VVM.js.map} +0 -0
  251. /package/dist/{program-WVAVJFND.js.map → processes-WU23U2OJ.js.map} +0 -0
  252. /package/dist/{providers-L27BJ5A6.js.map → program-YGXVCV2Y.js.map} +0 -0
  253. /package/dist/{projects-api-KRME2YKZ.js.map → projects-api-QE6L65SK.js.map} +0 -0
  254. /package/dist/{projects-mutate-3NHVG437.js.map → projects-mutate-MY7JTLSZ.js.map} +0 -0
  255. /package/dist/{query-HZYYRCLU.js.map → providers-KO2DODIO.js.map} +0 -0
  256. /package/dist/{recipes-EPLE2SNT.js.map → query-ZKTFJMNE.js.map} +0 -0
  257. /package/dist/{registry-T36ZIAWV.js.map → recipes-7S4MC5OJ.js.map} +0 -0
  258. /package/dist/{runner-BFYDWPUO.js.map → registry-PSZDPFZK.js.map} +0 -0
  259. /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
  260. /package/dist/{scheduler-GH7TIKYS.js.map → runner-YRBVNYTY.js.map} +0 -0
  261. /package/dist/{store-I3HEWVLQ.js.map → scheduler-GZZAN6ZG.js.map} +0 -0
  262. /package/dist/{surface-usage-PRL6Z4U3.js.map → seat-VZ7AVO27.js.map} +0 -0
  263. /package/dist/{timers-5LPZN55J.js.map → store-MCOA6N4F.js.map} +0 -0
  264. /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
  265. /package/dist/{types-VECTMYTO.js.map → surface-usage-NS74AXSE.js.map} +0 -0
  266. /package/dist/{types-Y6ZCZ52Z.js.map → timers-PCB4ZIBD.js.map} +0 -0
  267. /package/dist/{wiki-M6YNRFC4.js.map → types-H5ENIUIT.js.map} +0 -0
  268. /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-OIFU3KSQ.js.map} +0 -0
  269. /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/crons/scheduler.ts","../src/intent/mode.ts","../src/intent/ledger.ts","../src/intent/ulid.ts","../src/intent/instance.ts","../src/intent/governance.ts","../src/intent/decide.ts","../src/intent/divergence.ts","../src/intent/sources/cron.ts"],"sourcesContent":["import type { DaemonConfig, CronJobDef } from \"@/daemon/config\"\nimport type { AgentRegistry } from \"@/agents/registry\"\nimport type { HookRegistry } from \"@/hooks\"\nimport type { CronJobState, CronRunResult } from \"./types\"\nimport { writeFileSync, mkdirSync, existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { applyConfigMutation, setAtPath } from \"@/daemon/config-mutator\"\nimport { getLedgerMode } from \"@/intent/mode\"\nimport { getDefaultLedger } from \"@/intent/instance\"\nimport { recordCronDispatch } from \"@/intent/sources/cron\"\n\n// --- Cron Scheduler: lightweight cron engine with timezone support ---\n// No external dependencies — uses setTimeout-based scheduling.\n\n/**\n * Append a soft output-length cap to a cron prompt when the job configured\n * `maxOutputTokens`. Claude Code CLI has no hard flag for output length,\n * but a clear instruction at the end of the prompt is reliably honored by\n * the model. Keeps a cheap knob available for operators without us needing\n * to invent our own token counter or hack a post-response truncate.\n */\nfunction withOutputCap(prompt: string, maxOutputTokens?: number): string {\n if (!maxOutputTokens) return prompt\n const approxChars = maxOutputTokens * 4\n return `${prompt}\\n\\n[Response budget]\\nKeep your response under ~${maxOutputTokens} tokens (~${approxChars} chars). Be concise — this is automated batch work, not a conversation.`\n}\n\n/**\n * Parse a cron expression into next-fire timestamp.\n * Supports standard 5-field format: minute hour day-of-month month day-of-week\n */\nfunction parseCronField(field: string, min: number, max: number): number[] {\n const values: number[] = []\n\n for (const part of field.split(\",\")) {\n if (part === \"*\") {\n for (let i = min; i <= max; i++) values.push(i)\n } else if (part.includes(\"/\")) {\n const [range, stepStr] = part.split(\"/\")\n const step = parseInt(stepStr, 10)\n const start = range === \"*\" ? min : parseInt(range, 10)\n for (let i = start; i <= max; i += step) values.push(i)\n } else if (part.includes(\"-\")) {\n const [a, b] = part.split(\"-\").map(Number)\n for (let i = a; i <= b; i++) values.push(i)\n } else {\n values.push(parseInt(part, 10))\n }\n }\n\n return [...new Set(values)].sort((a, b) => a - b)\n}\n\nexport function getNextCronDate(expression: string, after: Date, timezone: string): Date {\n const fields = expression.trim().split(/\\s+/)\n if (fields.length !== 5) throw new Error(`Invalid cron: ${expression}`)\n\n const minutes = parseCronField(fields[0], 0, 59)\n const hours = parseCronField(fields[1], 0, 23)\n const daysOfMonth = parseCronField(fields[2], 1, 31)\n const months = parseCronField(fields[3], 1, 12)\n const daysOfWeek = parseCronField(fields[4], 0, 6)\n\n // Convert to timezone-aware date\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n })\n\n // Start searching from next minute\n const candidate = new Date(after.getTime() + 60_000)\n candidate.setSeconds(0, 0)\n\n // Search up to 1 year ahead\n const limit = new Date(candidate.getTime() + 366 * 24 * 60 * 60 * 1000)\n\n while (candidate < limit) {\n const parts = fmt.formatToParts(candidate)\n const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value || \"0\", 10)\n\n const m = get(\"minute\")\n const h = get(\"hour\")\n const dom = get(\"day\")\n const mon = get(\"month\")\n const dow = candidate.getDay()\n\n if (\n minutes.includes(m) &&\n hours.includes(h) &&\n daysOfMonth.includes(dom) &&\n months.includes(mon) &&\n daysOfWeek.includes(dow)\n ) {\n return candidate\n }\n\n // Advance by 1 minute\n candidate.setTime(candidate.getTime() + 60_000)\n }\n\n throw new Error(`No next run found for cron \"${expression}\" within 1 year`)\n}\n\n// Retry config (inspired by OpenClaw's exponential backoff)\nconst MAX_RETRIES = 5\nconst RETRY_DELAYS = [30_000, 60_000, 300_000, 900_000, 3_600_000] // 30s, 1m, 5m, 15m, 60m\n\n/** Notification callback — injected by daemon to send alerts via channels */\nexport type CronNotifyCallback = (jobId: string, agent: string, error: string, consecutiveErrors: number) => Promise<void>\n\nexport class CronScheduler {\n private jobs: Map<string, CronJobState> = new Map()\n private timers: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private registry: AgentRegistry\n private hooks?: HookRegistry\n private runsDir: string\n private lastRunFile: string\n private running = false\n private notifyCallback?: CronNotifyCallback\n private log: (...args: unknown[]) => void\n\n constructor(\n config: DaemonConfig,\n registry: AgentRegistry,\n hooks?: HookRegistry,\n log: (...args: unknown[]) => void = console.error.bind(console, \"[cron]\"),\n ) {\n this.registry = registry\n this.hooks = hooks\n this.log = log\n this.runsDir = resolve(process.cwd(), \".agentx/cron/runs\")\n this.lastRunFile = resolve(process.cwd(), \".agentx/cron/last-runs.json\")\n\n for (const [id, def] of Object.entries(config.crons)) {\n this.jobs.set(id, {\n id,\n enabled: def.enabled,\n schedule: def.schedule,\n timezone: def.timezone,\n agent: def.agent,\n prompt: def.prompt,\n timeout: def.timeout,\n model: def.model,\n maxOutputTokens: def.maxOutputTokens,\n onError: def.onError,\n consecutiveErrors: 0,\n totalRuns: 0,\n totalFailures: 0,\n })\n }\n }\n\n /**\n * Set a notification callback for failed crons.\n * Called when onError is \"notify\" or after multiple consecutive failures.\n */\n setNotifyCallback(cb: CronNotifyCallback): void {\n this.notifyCallback = cb\n }\n\n async start(): Promise<void> {\n this.running = true\n\n if (!existsSync(this.runsDir)) {\n mkdirSync(this.runsDir, { recursive: true })\n }\n\n // Detect missed runs before scheduling\n const missedRuns = this.detectMissedRuns()\n if (missedRuns.length > 0) {\n this.log(`Detected ${missedRuns.length} missed cron run(s) while daemon was down:`)\n for (const { jobId, missedAt } of missedRuns) {\n this.log(` \"${jobId}\" should have run at ${missedAt.toISOString()}`)\n }\n // Execute missed runs (fire-and-forget, don't block startup)\n this.executeMissedRuns(missedRuns).catch((e) => {\n this.log(`Error executing missed runs: ${e.message}`)\n })\n }\n\n for (const [id, job] of this.jobs) {\n if (!job.enabled) {\n this.log(`Job \"${id}\" is disabled, skipping`)\n continue\n }\n this.scheduleNext(id)\n }\n\n this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter((j) => j.enabled).length} enabled`)\n }\n\n async stop(): Promise<void> {\n this.running = false\n for (const timer of this.timers.values()) {\n clearTimeout(timer)\n }\n this.timers.clear()\n\n // Persist last run times for missed run detection on next start\n this.saveLastRuns()\n }\n\n private scheduleNext(jobId: string): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n\n // Clear any existing timer\n const existing = this.timers.get(jobId)\n if (existing) clearTimeout(existing)\n\n try {\n const nextRun = getNextCronDate(job.schedule, new Date(), job.timezone)\n job.nextRun = nextRun\n job.retryPending = false\n const delay = nextRun.getTime() - Date.now()\n\n this.log(`Job \"${jobId}\" next run: ${nextRun.toISOString()} (in ${Math.round(delay / 1000)}s)`)\n\n const timer = setTimeout(() => this.executeJob(jobId), delay)\n this.timers.set(jobId, timer)\n } catch (e: any) {\n this.log(`Failed to schedule \"${jobId}\": ${e.message}`)\n }\n }\n\n private scheduleRetry(jobId: string, attempt: number): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n if (attempt >= MAX_RETRIES) {\n this.log(`Job \"${jobId}\" exhausted all ${MAX_RETRIES} retries, scheduling next regular run`)\n this.scheduleNext(jobId)\n return\n }\n\n const delay = RETRY_DELAYS[attempt] || RETRY_DELAYS[RETRY_DELAYS.length - 1]\n job.retryPending = true\n\n this.log(`Job \"${jobId}\" retry ${attempt + 1}/${MAX_RETRIES} in ${Math.round(delay / 1000)}s`)\n\n const timer = setTimeout(() => this.executeJob(jobId, attempt + 1), delay)\n this.timers.set(jobId, timer)\n }\n\n /**\n * Phase 1 commit 6.d — record one cron-fire decision in the ledger\n * when the source is enabled. Wrapped in try/catch so a ledger\n * failure can never break cron dispatch — legacy stays authoritative\n * until the 1c per-source promotion lands.\n */\n private recordCronDecisionInLedger(\n jobId: string,\n agentId: string,\n firedAt: Date,\n legacy: import(\"@/intent/divergence\").LegacyOutcome,\n ): { eventId: string; decidedBy: string } | undefined {\n if (getLedgerMode(\"cron\") === \"off\") return undefined\n try {\n const decision = recordCronDispatch(\n getDefaultLedger(),\n { jobId, agentId, firedAt },\n JSON.stringify({ jobId, agentId, firedAt: firedAt.toISOString() }),\n legacy,\n )\n if (decision.outcome === \"dispatched\") {\n return { eventId: decision.eventId, decidedBy: decision.decidedBy }\n }\n return undefined\n } catch (e: any) {\n this.log(`[ledger] cron \"${jobId}\" record failed: ${e?.message ?? e}`)\n return undefined\n }\n }\n\n private async executeJob(jobId: string, retryAttempt: number = 0): Promise<void> {\n const job = this.jobs.get(jobId)\n if (!job || !this.running) return\n\n const isRetry = retryAttempt > 0\n // firedAt is captured here (rather than below at the original\n // `startedAt` declaration) so the ledger event has a stable\n // sourceEventId regardless of whether we record at the hook-block\n // path or the dispatch path.\n const firedAt = new Date()\n\n // Pre-hook\n if (this.hooks?.has(\"pre:cron-run\" as any)) {\n const hookResult = await this.hooks.execute(\"pre:cron-run\" as any, {\n event: \"pre:cron-run\" as any,\n jobId,\n agent: job.agent,\n prompt: job.prompt,\n })\n if (hookResult.blocked) {\n this.log(`Job \"${jobId}\" blocked by hook: ${hookResult.message}`)\n this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: null, outcome: \"halted\",\n reason: `pre-hook blocked: ${hookResult.message ?? \"\"}`.trim(),\n })\n this.scheduleNext(jobId)\n return\n }\n }\n\n this.log(`${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> agent \"${job.agent}\"`)\n const startedAt = firedAt\n job.lastRun = startedAt\n job.totalRuns++\n\n // Phase 1 commit 6.d — record the dispatch decision before the\n // (potentially long-running) registry.execute call. The returned\n // intentRef threads through to registry.execute so it records a\n // resolution on completion.\n const intentRef = this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: job.agent, outcome: \"dispatched\", reason: isRetry ? `retry ${retryAttempt}` : null,\n })\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(job.prompt, job.maxOutputTokens),\n agentId: job.agent,\n model: job.model,\n intentRef,\n // chatId per-job so different cron jobs for the same agent don't\n // collide in one \"default\" session. Without this, the marketing\n // daily-brief and the marketing weekly-report cron share history,\n // and one job's prompt context bleeds into the other.\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt,\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || Date.now() - startedAt.getTime(),\n isRetry,\n retryAttempt,\n }\n\n if (response.error) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = response.error\n this.log(`Job \"${jobId}\" failed (${job.consecutiveErrors} consecutive): ${response.error}`)\n\n // Notify on failure\n await this.notifyFailure(job, response.error)\n\n if (job.onError.includes(\"disable\") && job.consecutiveErrors >= 3) {\n job.enabled = false\n this.log(`Job \"${jobId}\" disabled after ${job.consecutiveErrors} consecutive errors`)\n // Persist to agentx.json so a daemon restart doesn't resurrect the\n // broken cron (previously this was in-memory only — a repeatedly\n // failing cron would keep burning money across restarts).\n try {\n const res = await applyConfigMutation(\n (cfg) => setAtPath(cfg, `crons.${jobId}.enabled`, false),\n { reload: false },\n )\n if (!res.success) {\n this.log(`Failed to persist disable for \"${jobId}\": ${res.error}`)\n }\n } catch (e: any) {\n this.log(`Failed to persist disable for \"${jobId}\": ${e.message}`)\n }\n await this.notifyDisabled(job)\n }\n\n // Retry\n this.logRun(result)\n this.scheduleRetry(jobId, retryAttempt)\n return\n } else {\n // Success — reset error state\n if (job.consecutiveErrors > 0) {\n this.log(`Job \"${jobId}\" recovered after ${job.consecutiveErrors} failure(s)`)\n }\n job.consecutiveErrors = 0\n job.lastSuccess = new Date()\n job.lastError = undefined\n job.retryPending = false\n this.log(`Job \"${jobId}\" completed in ${result.duration}ms`)\n }\n\n // Log run\n this.logRun(result)\n\n // Post-hook\n if (this.hooks?.has(\"post:cron-run\" as any)) {\n await this.hooks.execute(\"post:cron-run\" as any, {\n event: \"post:cron-run\" as any,\n jobId,\n success: result.success,\n duration: result.duration,\n error: result.error ? new Error(result.error) : undefined,\n })\n }\n } catch (e: any) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = e.message\n this.log(`Job \"${jobId}\" threw: ${e.message}`)\n\n await this.notifyFailure(job, e.message)\n this.scheduleRetry(jobId, retryAttempt)\n return\n }\n\n // Persist last run time\n this.saveLastRuns()\n\n // Schedule next regular run\n this.scheduleNext(jobId)\n }\n\n // --- Missed run detection ---\n\n /**\n * Detect cron jobs that should have fired while the daemon was down.\n * Compares saved last-run times against the cron schedule.\n */\n private detectMissedRuns(): Array<{ jobId: string; missedAt: Date }> {\n const missed: Array<{ jobId: string; missedAt: Date }> = []\n\n const lastRuns = this.loadLastRuns()\n if (!lastRuns) return missed // First boot — no history\n\n for (const [jobId, job] of this.jobs) {\n if (!job.enabled) continue\n\n const lastRunStr = lastRuns[jobId]\n if (!lastRunStr) continue // Never ran before\n\n const lastRun = new Date(lastRunStr)\n try {\n // What SHOULD the next run have been after the last recorded run?\n const shouldHaveRun = getNextCronDate(job.schedule, lastRun, job.timezone)\n if (shouldHaveRun.getTime() < Date.now()) {\n missed.push({ jobId, missedAt: shouldHaveRun })\n }\n } catch {\n // Invalid schedule — skip\n }\n }\n\n return missed\n }\n\n /**\n * Execute missed runs (catch-up). Runs sequentially to avoid overwhelming agents.\n */\n private async executeMissedRuns(missed: Array<{ jobId: string; missedAt: Date }>): Promise<void> {\n for (const { jobId, missedAt } of missed) {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled) continue\n\n this.log(`Running missed job \"${jobId}\" (was due at ${missedAt.toISOString()})`)\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(\n `[MISSED RUN — was scheduled for ${missedAt.toISOString()}]\\n\\n${job.prompt}`,\n job.maxOutputTokens,\n ),\n agentId: job.agent,\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt: new Date(),\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || 0,\n isRetry: false,\n }\n\n this.logRun(result)\n\n if (response.error) {\n this.log(`Missed job \"${jobId}\" failed: ${response.error}`)\n } else {\n this.log(`Missed job \"${jobId}\" completed`)\n job.lastSuccess = new Date()\n }\n job.lastRun = new Date()\n job.totalRuns++\n } catch (e: any) {\n this.log(`Missed job \"${jobId}\" threw: ${e.message}`)\n }\n }\n\n this.saveLastRuns()\n }\n\n // --- Notification ---\n\n private async notifyFailure(job: CronJobState, error: string): Promise<void> {\n if (!job.onError.includes(\"notify\") && job.consecutiveErrors < 2) return\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" failed (${job.consecutiveErrors}x): ${error.slice(0, 200)}`)\n return\n }\n\n try {\n await this.notifyCallback(job.id, job.agent, error, job.consecutiveErrors)\n } catch {\n // Don't fail on notification errors\n }\n }\n\n private async notifyDisabled(job: CronJobState): Promise<void> {\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" has been DISABLED after ${job.consecutiveErrors} consecutive failures`)\n return\n }\n\n try {\n await this.notifyCallback(\n job.id,\n job.agent,\n `AUTO-DISABLED after ${job.consecutiveErrors} consecutive failures. Last error: ${job.lastError || \"unknown\"}`,\n job.consecutiveErrors,\n )\n } catch {\n // Don't fail on notification errors\n }\n }\n\n // --- Persistence ---\n\n private saveLastRuns(): void {\n try {\n const data: Record<string, string> = {}\n for (const [id, job] of this.jobs) {\n if (job.lastRun) data[id] = job.lastRun.toISOString()\n }\n const dir = resolve(process.cwd(), \".agentx/cron\")\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n writeFileSync(this.lastRunFile, JSON.stringify(data, null, 2))\n } catch {\n // Best-effort\n }\n }\n\n private loadLastRuns(): Record<string, string> | null {\n try {\n if (!existsSync(this.lastRunFile)) return null\n return JSON.parse(readFileSync(this.lastRunFile, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n private logRun(result: CronRunResult): void {\n try {\n const runDir = resolve(this.runsDir, result.jobId)\n if (!existsSync(runDir)) {\n mkdirSync(runDir, { recursive: true })\n }\n\n const filename = `${result.startedAt.toISOString().replace(/[:.]/g, \"-\")}.json`\n writeFileSync(\n resolve(runDir, filename),\n JSON.stringify(result, null, 2),\n )\n } catch {\n // Don't fail on logging errors\n }\n }\n\n /**\n * List all jobs and their status (including failure info).\n */\n list(): CronJobState[] {\n return Array.from(this.jobs.values())\n }\n\n /**\n * Get a health summary of cron jobs.\n */\n health(): { healthy: number; failing: number; disabled: number; missed: number; jobs: Array<{ id: string; status: string; consecutiveErrors: number; lastError?: string }> } {\n const jobs = Array.from(this.jobs.values())\n const missed = this.detectMissedRuns()\n\n return {\n healthy: jobs.filter(j => j.enabled && j.consecutiveErrors === 0).length,\n failing: jobs.filter(j => j.enabled && j.consecutiveErrors > 0).length,\n disabled: jobs.filter(j => !j.enabled).length,\n missed: missed.length,\n jobs: jobs.map(j => ({\n id: j.id,\n status: !j.enabled ? \"disabled\" : j.retryPending ? \"retrying\" : j.consecutiveErrors > 0 ? \"failing\" : \"healthy\",\n consecutiveErrors: j.consecutiveErrors,\n lastError: j.lastError,\n })),\n }\n }\n}\n","import type { IntentSource } from \"./types\"\n\n// Mode-flag plumbing — Phase 1 commit 4 of the architectural rescue.\n//\n// The staged rollout in research-rescue-plan.md §7 needs three states:\n//\n// off ledger code is unreachable; legacy paths are authoritative.\n// This is the default and stays the default through 1a.\n// shadow decideAndCommit runs alongside the legacy paths on every\n// dispatch and records what *would* have happened. Legacy\n// remains authoritative; a divergence reporter (commit 5)\n// compares the two. The ≥7-day soak in 1b lives here.\n// authoritative ledger decision is the dispatch decision. Legacy paths\n// remain only as fallback gated by INTENT_LEDGER_FALLBACK\n// (commit 1c → 1d removes the legacy paths entirely).\n//\n// Mode is resolved per-source so 1c can flip sources one at a time\n// (gitlab → workflow → telegram → cron → mesh, ≥48h soak between each).\n//\n// This commit is plumbing only. No call site reads the mode yet —\n// commit 6 wires the readers behind the flag, defaulting to \"off\" so\n// production behaviour is unchanged at deploy time.\n\nexport type LedgerMode = \"off\" | \"shadow\" | \"authoritative\"\n\nconst VALID_MODES = [\"off\", \"shadow\", \"authoritative\"] as const satisfies readonly LedgerMode[]\n\n/** Per-source env-var names. Lifted to a constant so the call site (commit 6)\n * doesn't need to construct strings, and so the test matrix can drive them\n * by table rather than guessing the naming convention. */\nconst PER_SOURCE_ENV_VAR: Record<IntentSource, string> = {\n telegram: \"INTENT_LEDGER_MODE_TELEGRAM\",\n slack: \"INTENT_LEDGER_MODE_SLACK\",\n whatsapp: \"INTENT_LEDGER_MODE_WHATSAPP\",\n discord: \"INTENT_LEDGER_MODE_DISCORD\",\n gitlab: \"INTENT_LEDGER_MODE_GITLAB\",\n github: \"INTENT_LEDGER_MODE_GITHUB\",\n workflow: \"INTENT_LEDGER_MODE_WORKFLOW\",\n cron: \"INTENT_LEDGER_MODE_CRON\",\n mesh: \"INTENT_LEDGER_MODE_MESH\",\n}\n\nconst GLOBAL_ENV_VAR = \"INTENT_LEDGER_MODE\"\n\n/**\n * Resolve the ledger mode for one source. Resolution order:\n *\n * 1. Per-source env var (e.g. INTENT_LEDGER_MODE_GITLAB)\n * 2. Global env var (INTENT_LEDGER_MODE)\n * 3. Default — \"off\"\n *\n * Invalid values at any level (typos, foreign strings) are ignored — that\n * level falls through to the next. Defaulting to \"off\" on garbage means an\n * operator typo never accidentally promotes a source to authoritative; the\n * cost is silence on misconfig, but the cost of the alternative\n * (mis-promoted source) is much higher in production.\n *\n * The accepted values are case-insensitive (\"Shadow\", \"SHADOW\", \"shadow\"\n * all parse) so config copied from a doc or shell history doesn't surprise.\n *\n * Read every call rather than cached. Per-dispatch overhead is one or two\n * `process.env` lookups — negligible — and runtime flips (operator SIGHUPs\n * the daemon and changes `EnvironmentFile=` on systemd) take effect on the\n * next event without a restart.\n */\nexport function getLedgerMode(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): LedgerMode {\n const perSource = parseLedgerMode(env[PER_SOURCE_ENV_VAR[source]])\n if (perSource) return perSource\n const global = parseLedgerMode(env[GLOBAL_ENV_VAR])\n if (global) return global\n return \"off\"\n}\n\n/** Parse a value into a LedgerMode, or return null for invalid / unset. */\nexport function parseLedgerMode(value: unknown): LedgerMode | null {\n if (typeof value !== \"string\") return null\n const normalized = value.trim().toLowerCase()\n return (VALID_MODES as readonly string[]).includes(normalized)\n ? (normalized as LedgerMode)\n : null\n}\n\n/** Convenience: is this source consulting the ledger at all? Equivalent to\n * `getLedgerMode(source) !== \"off\"`, named for callsite readability. */\nexport function isLedgerActive(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n return getLedgerMode(source, env) !== \"off\"\n}\n","import Database from \"better-sqlite3\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentEvent,\n IntentEventInput,\n IntentResolution,\n IntentSource,\n} from \"./types\"\n\n// Intent ledger — Phase 1 of the architectural rescue.\n//\n// Append-only SQLite store that becomes the single source of truth for\n// dispatch decisions across all sources (channel router, workflow\n// dispatcher, gitlab handler, cron, mesh). This commit only opens the db\n// and runs the schema migrations. The read/write API arrives in commit 2;\n// the `decideAndCommit` skeleton in commit 3.\n//\n// Lives in its own database file (`.agentx/intent/ledger.sqlite`) rather\n// than sharing the existing observability db at `.agentx/db.sqlite`:\n// - Different lifecycle: dispatch is hotter than observability, no point\n// making fsync compete.\n// - Different durability story: the ledger is canonical state; the\n// observability tables are derived. Different backup/retention policies.\n// - Cleaner schema separation — ledger migrations don't entangle with the\n// observability ones.\n//\n// WAL mode + synchronous=NORMAL — same balance the observability db uses.\n\nexport interface OpenLedgerOptions {\n /** Resolved relative to cwd. Default: .agentx/intent/ledger.sqlite */\n path?: string\n}\n\n/**\n * IntentLedger handle. One instance per database file. Tests open per-test\n * tmp instances; the daemon opens one process-global instance (added in a\n * later commit when daemon wiring lands).\n */\nexport class IntentLedger {\n readonly db: Database.Database\n readonly path: string\n\n constructor(opts: OpenLedgerOptions = {}) {\n this.path = resolve(process.cwd(), opts.path ?? \".agentx/intent/ledger.sqlite\")\n mkdirSync(dirname(this.path), { recursive: true })\n this.db = new Database(this.path)\n this.db.pragma(\"journal_mode = WAL\")\n this.db.pragma(\"synchronous = NORMAL\")\n this.db.pragma(\"foreign_keys = ON\")\n runMigrations(this.db)\n }\n\n /** Test-only — production never closes. */\n close(): void {\n this.db.close()\n }\n\n /** Current schema version. New migrations append to the runMigrations\n * list and bump the version. Useful for tests + diagnostics. */\n schemaVersion(): number {\n const row = this.db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }\n return row.v ?? 0\n }\n\n // -------------------------------------------------------------------------\n // Events\n // -------------------------------------------------------------------------\n\n /**\n * Append an event. Idempotent on `(source, sourceEventId)` — a re-delivery\n * with the same external id returns the previously-stored row without\n * inserting a duplicate. Events with `sourceEventId === null` (cron tics,\n * ad-hoc internal events) are NOT deduplicated; each call writes a new row.\n *\n * Returns the canonical (existing or new) event row including its id.\n */\n recordEvent(input: IntentEventInput): IntentEvent {\n if (input.sourceEventId !== null) {\n const existing = this.findEventBySourceId(input.source, input.sourceEventId)\n if (existing) return existing\n }\n const event: IntentEvent = {\n id: input.id ?? newEventId(input.ts),\n ts: input.ts,\n source: input.source,\n sourceEventId: input.sourceEventId,\n project: input.project,\n subject: input.subject,\n intent: input.intent,\n rawJson: input.rawJson,\n }\n this.db\n .prepare(\n `INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n event.id,\n event.ts,\n event.source,\n event.sourceEventId,\n event.project,\n event.subject,\n event.intent,\n event.rawJson,\n )\n return event\n }\n\n /** Idempotency probe — used by `recordEvent` and by external callers that\n * want to check existence before constructing a full event payload. */\n findEventBySourceId(source: IntentSource, sourceEventId: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE source = ? AND source_event_id = ?`,\n )\n .get(source, sourceEventId) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n /** Lookup by primary key. Returns null when not found. */\n getEventById(id: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE id = ?`,\n )\n .get(id) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Decisions\n // -------------------------------------------------------------------------\n\n /**\n * Append a decision. Throws on `(eventId, decidedBy)` conflict — decisions\n * are once-and-only-once per decider. Idempotency for the *event* is the\n * caller's responsibility (use `recordEvent` for that); decisions\n * intentionally do not retry-coalesce so a buggy caller surfaces loudly\n * instead of silently overwriting prior judgement.\n */\n recordDecision(decision: IntentDecision): void {\n this.db\n .prepare(\n `INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n decision.eventId,\n decision.decidedAt,\n decision.decidedBy,\n decision.agentId,\n decision.outcome,\n decision.reason,\n )\n }\n\n /** All decisions for one event, oldest first. The chain (channel-router →\n * pm-gate → workflow) reads naturally in insertion order. */\n getDecisionsForEvent(eventId: string): IntentDecision[] {\n const rows = this.db\n .prepare(\n `SELECT event_id, decided_at, decided_by, agent_id, outcome, reason\n FROM intent_decisions WHERE event_id = ? ORDER BY decided_at ASC`,\n )\n .all(eventId) as DecisionRow[]\n return rows.map(rowToDecision)\n }\n\n /**\n * The active-task-safety check. Returns the most recent `dispatched`\n * decision for `(project, subject)` that has not yet been resolved\n * (no row in `intent_resolutions`). `decideAndCommit` (commit 3) consults\n * this to enforce the at-most-one-in-flight invariant.\n *\n * Returns null when project or subject is null — the active-task concept\n * is meaningless without both axes pinned.\n */\n getActiveDecisionForSubject(project: string | null, subject: string | null): IntentDecision | null {\n if (project === null || subject === null) return null\n const row = this.db\n .prepare(\n `SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason\n FROM intent_decisions d\n JOIN intent_events e ON e.id = d.event_id\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE e.project = ? AND e.subject = ?\n AND d.outcome = 'dispatched'\n AND r.decision_event_id IS NULL\n ORDER BY d.decided_at DESC\n LIMIT 1`,\n )\n .get(project, subject) as DecisionRow | undefined\n return row ? rowToDecision(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Resolutions\n // -------------------------------------------------------------------------\n\n /**\n * Append a resolution. Throws if a resolution already exists for the\n * decision — the ledger is append-only, so revising an outcome is a new\n * event, not an overwrite. The FK to `intent_decisions` ensures the\n * decision exists.\n */\n recordResolution(resolution: IntentResolution): void {\n this.db\n .prepare(\n `INSERT INTO intent_resolutions (decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n resolution.decisionEventId,\n resolution.decisionDecidedBy,\n resolution.resolvedAt,\n resolution.status,\n resolution.durationMs,\n resolution.resultSummary,\n )\n }\n\n /**\n * Close every dispatched-and-unresolved decision by writing a\n * resolution with status \"canceled\" and the given reason. Used at\n * daemon startup to clean up dispatches whose agent execution died\n * with the previous process — without this, those decisions sit\n * in-flight forever and Inv-ActiveTaskSafety blocks legitimate\n * re-dispatches on the same slot.\n *\n * Returns the count of resolutions written. Idempotent — repeated\n * calls write 0 the second time because nothing remains in-flight.\n */\n cleanupOrphanedDispatches(reason: string = \"daemon-restart\", now: () => number = Date.now): number {\n const rows = this.db\n .prepare(`\n SELECT d.event_id, d.decided_by FROM intent_decisions d\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL\n `)\n .all() as Array<{ event_id: string; decided_by: string }>\n const ts = now()\n let count = 0\n for (const row of rows) {\n try {\n this.recordResolution({\n decisionEventId: row.event_id,\n decisionDecidedBy: row.decided_by,\n resolvedAt: ts,\n status: \"canceled\",\n durationMs: null,\n resultSummary: reason,\n })\n count++\n } catch {\n // Skip — resolution already exists (race with normal completion).\n }\n }\n return count\n }\n\n /** Returns the resolution for a decision, or null if still in-flight. */\n getResolution(eventId: string, decidedBy: string): IntentResolution | null {\n const row = this.db\n .prepare(\n `SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary\n FROM intent_resolutions WHERE decision_event_id = ? AND decision_decided_by = ?`,\n )\n .get(eventId, decidedBy) as ResolutionRow | undefined\n return row ? rowToResolution(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Divergences (shadow-mode soak surface)\n // -------------------------------------------------------------------------\n\n /**\n * Append a divergence record. Throws on duplicate `id`. The composite FK\n * to `intent_decisions` (`event_id`, `decided_by`) enforces that a\n * divergence cannot exist without its ledger-side decision — so callers\n * must record the decision before reporting the divergence.\n */\n recordDivergence(divergence: IntentDivergence): void {\n this.db\n .prepare(\n `INSERT INTO intent_divergences (\n id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n divergence.id,\n divergence.ts,\n divergence.source,\n divergence.eventId,\n divergence.decidedBy,\n divergence.ledgerAgentId,\n divergence.ledgerOutcome,\n divergence.ledgerReason,\n divergence.legacyAgentId,\n divergence.legacyOutcome,\n divergence.legacyReason,\n )\n }\n\n /**\n * Recent divergences, newest first. Filters compose: `source` narrows to\n * one dispatch source, `since` to a recency window, `limit` to top-N.\n * The intended consumer is the soak dashboard (commit 8) and `agentx\n * audit --divergence` queries; per-record introspection is rare so we\n * don't expose a single-id getter.\n */\n getDivergences(opts: {\n source?: IntentSource\n since?: number\n limit?: number\n } = {}): IntentDivergence[] {\n const wheres: string[] = []\n const params: Array<string | number> = []\n if (opts.source !== undefined) {\n wheres.push(\"source = ?\")\n params.push(opts.source)\n }\n if (opts.since !== undefined) {\n wheres.push(\"ts >= ?\")\n params.push(opts.since)\n }\n const whereSql = wheres.length ? `WHERE ${wheres.join(\" AND \")}` : \"\"\n const limitSql = opts.limit !== undefined ? \"LIMIT ?\" : \"\"\n if (opts.limit !== undefined) params.push(opts.limit)\n\n const rows = this.db\n .prepare(\n `SELECT id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n FROM intent_divergences\n ${whereSql}\n ORDER BY ts DESC\n ${limitSql}`,\n )\n .all(...params) as DivergenceRow[]\n return rows.map(rowToDivergence)\n }\n}\n\n// --- Row → typed-object adapters --------------------------------------------\n//\n// SQLite returns snake_case rows; the typed surface uses camelCase. Mapping\n// once here keeps every consumer in TS-ergonomic shape and makes column\n// renames a single-file refactor.\n\ninterface EventRow {\n id: string\n ts: number\n source: string\n source_event_id: string | null\n project: string | null\n subject: string | null\n intent: string | null\n raw_json: string\n}\n\ninterface DecisionRow {\n event_id: string\n decided_at: number\n decided_by: string\n agent_id: string | null\n outcome: string\n reason: string | null\n}\n\ninterface ResolutionRow {\n decision_event_id: string\n decision_decided_by: string\n resolved_at: number\n status: string\n duration_ms: number | null\n result_summary: string | null\n}\n\ninterface DivergenceRow {\n id: string\n ts: number\n source: string\n event_id: string\n decided_by: string\n ledger_agent_id: string | null\n ledger_outcome: string\n ledger_reason: string | null\n legacy_agent_id: string | null\n legacy_outcome: string\n legacy_reason: string | null\n}\n\nfunction rowToEvent(row: EventRow): IntentEvent {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n sourceEventId: row.source_event_id,\n project: row.project,\n subject: row.subject,\n intent: row.intent,\n rawJson: row.raw_json,\n }\n}\n\nfunction rowToDecision(row: DecisionRow): IntentDecision {\n return {\n eventId: row.event_id,\n decidedAt: row.decided_at,\n decidedBy: row.decided_by,\n agentId: row.agent_id,\n outcome: row.outcome as IntentDecision[\"outcome\"],\n reason: row.reason,\n }\n}\n\nfunction rowToResolution(row: ResolutionRow): IntentResolution {\n return {\n decisionEventId: row.decision_event_id,\n decisionDecidedBy: row.decision_decided_by,\n resolvedAt: row.resolved_at,\n status: row.status as IntentResolution[\"status\"],\n durationMs: row.duration_ms,\n resultSummary: row.result_summary,\n }\n}\n\nfunction rowToDivergence(row: DivergenceRow): IntentDivergence {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n eventId: row.event_id,\n decidedBy: row.decided_by,\n ledgerAgentId: row.ledger_agent_id,\n ledgerOutcome: row.ledger_outcome as IntentDivergence[\"ledgerOutcome\"],\n ledgerReason: row.ledger_reason,\n legacyAgentId: row.legacy_agent_id,\n legacyOutcome: row.legacy_outcome as IntentDivergence[\"legacyOutcome\"],\n legacyReason: row.legacy_reason,\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration\n * function — never mutate an old one. Each step is idempotent so re-running\n * on an already-current db is safe.\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n if (current < 1) migrationV1(db)\n if (current < 2) migrationV2(db)\n}\n\nfunction migrationV1(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_events (\n -- TEXT PRIMARY KEY isn't auto-NOT-NULL in SQLite; spell it out so the\n -- ULID invariant is enforced at the schema level rather than relying on\n -- the application layer.\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_event_id TEXT,\n project TEXT,\n subject TEXT,\n intent TEXT,\n raw_json TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_events_subject\n ON intent_events (project, subject);\n CREATE INDEX IF NOT EXISTS idx_intent_events_source_event_id\n ON intent_events (source, source_event_id);\n CREATE INDEX IF NOT EXISTS idx_intent_events_ts\n ON intent_events (ts);\n\n CREATE TABLE IF NOT EXISTS intent_decisions (\n event_id TEXT NOT NULL REFERENCES intent_events(id),\n decided_at INTEGER NOT NULL,\n decided_by TEXT NOT NULL,\n agent_id TEXT,\n outcome TEXT NOT NULL,\n reason TEXT,\n PRIMARY KEY (event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_agent\n ON intent_decisions (agent_id, decided_at);\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_outcome\n ON intent_decisions (outcome, decided_at);\n\n CREATE TABLE IF NOT EXISTS intent_resolutions (\n decision_event_id TEXT NOT NULL,\n decision_decided_by TEXT NOT NULL,\n resolved_at INTEGER NOT NULL,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n result_summary TEXT,\n PRIMARY KEY (decision_event_id, decision_decided_by),\n FOREIGN KEY (decision_event_id, decision_decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_resolutions_status\n ON intent_resolutions (status, resolved_at);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (1)\").run()\n}\n\nfunction migrationV2(db: Database.Database): void {\n // Phase 1 commit 5 — divergence reporter surface. Each row records one\n // observed mismatch between the ledger's decision and the legacy path's\n // outcome during shadow-mode operation. The composite FK to\n // intent_decisions ensures a divergence cannot exist without its\n // ledger-side decision row.\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_divergences (\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n event_id TEXT NOT NULL,\n decided_by TEXT NOT NULL,\n ledger_agent_id TEXT,\n ledger_outcome TEXT NOT NULL,\n ledger_reason TEXT,\n legacy_agent_id TEXT,\n legacy_outcome TEXT NOT NULL,\n legacy_reason TEXT,\n FOREIGN KEY (event_id, decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n -- \"show me recent divergences from gitlab\" — the soak's primary query\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_source_ts\n ON intent_divergences (source, ts);\n -- \"are any deciders consistently wrong\" — per-decider analysis\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_decided_by\n ON intent_divergences (decided_by, ts);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (2)\").run()\n}\n\n// existsSync is imported for symmetry with src/storage/sqlite.ts; the\n// ledger constructor doesn't currently branch on file presence (the\n// migration is idempotent regardless), but keeping the import documents\n// the intent should later code need to distinguish first-open from re-open.\nvoid existsSync\n","import { randomBytes } from \"crypto\"\n\n// In-tree ULID generator — Phase 1 of the architectural rescue.\n//\n// The ledger demands monotonically-sortable ids so chronological queries\n// can use ID ranges and the audit trail reads coherently. ULIDs give us\n// that (10-char Crockford-base32 timestamp + 16-char randomness, total\n// 26 chars). The full `ulid` npm package is overkill for the few hundred\n// lines of generation logic we need, and adding a dep means another\n// `pnpm install --prod` step on clawd-server. So we inline.\n//\n// This is not a cryptographic primitive — its job is to be a unique,\n// time-sortable identifier. Random bytes come from `crypto.randomBytes`\n// purely because it's the right tool for \"give me bytes\" and there's no\n// reason to use weaker randomness.\n\nconst ENCODING = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\" // Crockford base32\n\nconst TIME_LEN = 10\nconst RAND_LEN = 16\n\nfunction encodeTime(ms: number): string {\n let out = \"\"\n for (let i = TIME_LEN - 1; i >= 0; i--) {\n out = ENCODING[ms & 31] + out\n ms = Math.floor(ms / 32)\n }\n return out\n}\n\nfunction encodeRandom(): string {\n const bytes = randomBytes(RAND_LEN)\n let out = \"\"\n for (let i = 0; i < RAND_LEN; i++) {\n out += ENCODING[bytes[i] & 31]\n }\n return out\n}\n\n/** Generate a new ULID. Pass `now` for deterministic tests. */\nexport function newEventId(now: number = Date.now()): string {\n return encodeTime(now) + encodeRandom()\n}\n\n/** Extract the timestamp portion from a ULID. Inverse of `newEventId`'s\n * time prefix. Useful for sanity checks; not load-bearing. */\nexport function decodeTime(id: string): number {\n let ms = 0\n for (let i = 0; i < TIME_LEN; i++) {\n const v = ENCODING.indexOf(id[i])\n if (v < 0) throw new Error(`invalid ULID character at position ${i}: ${id[i]}`)\n ms = ms * 32 + v\n }\n return ms\n}\n","import { IntentLedger } from \"./ledger\"\n\n// Daemon-process singleton accessor for the IntentLedger.\n//\n// Phase 1 commit 6.0 — scaffolding for the call-site wiring that lands in\n// 6.a (gitlab), 6.b (router), 6.c (workflow), 6.d (cron + mesh). Each\n// source's wrapper will read this singleton when the mode is non-\"off\".\n//\n// The singleton is lazy because the ledger isn't needed in production\n// until the operator flips INTENT_LEDGER_MODE off the default. Avoiding\n// eager construction means an unflipped agentx process never opens the\n// ledger db, never holds the file, never writes WAL pages — exactly what\n// \"deploy-time default is off\" means in practice.\n//\n// Tests use `setLedgerForTesting` to inject an in-memory or tmp-dir\n// ledger and `resetLedgerForTesting` to release it between cases. Outside\n// of tests, callers go through `getDefaultLedger()`.\n\nlet _ledger: IntentLedger | undefined\n\nexport interface DefaultLedgerOptions {\n /** Path override. Default: `.agentx/intent/ledger.sqlite` (resolved\n * against cwd by the IntentLedger constructor). */\n path?: string\n}\n\n/**\n * Lazy singleton getter. Idempotent — repeated calls return the same\n * handle. Constructs the ledger on first call.\n *\n * Throws on construction failure (file unwritable, native binding broken,\n * etc.). Call sites should gate the call behind `getLedgerMode(...) !== \"off\"`\n * so a bad ledger never reaches construction in normal \"off\" production.\n *\n * The decision to throw rather than fail-soft (return null like\n * src/storage/sqlite.ts does) is deliberate: the ledger is canonical\n * state once `mode !== \"off\"`, so a silent failure would leave the\n * dispatcher in an undefined \"I tried to record but didn't\" state. Loud\n * failure surfaces misconfig at startup rather than days into a soak.\n */\nexport function getDefaultLedger(opts: DefaultLedgerOptions = {}): IntentLedger {\n if (_ledger) return _ledger\n _ledger = new IntentLedger({ path: opts.path })\n return _ledger\n}\n\n/** Test-only: inject a pre-built ledger so per-test tmp dirs work without\n * fighting the singleton. Production code MUST NOT call this. */\nexport function setLedgerForTesting(ledger: IntentLedger): void {\n _ledger = ledger\n}\n\n/** Test-only: drop the singleton reference. Use in `afterEach` so the\n * next test's `setLedgerForTesting` or `getDefaultLedger` starts fresh.\n * Does NOT close the underlying db — the caller (test) owns close(). */\nexport function resetLedgerForTesting(): void {\n _ledger = undefined\n}\n","import type { DispatchGovernance } from \"./decide\"\n\n// Daemon-level governance singleton — Phase 3 of the architectural rescue.\n//\n// `decideAndCommit` reads this when its caller doesn't pass an explicit\n// `governance` argument. The daemon initializes it at startup from the\n// `BusinessLayer.organization` instance, gated by the\n// `INTENT_PM_GATE_ENABLED` env var. When the var is unset (the deploy\n// default), the singleton stays undefined and no PM gate / canHandle\n// check fires — production behaviour is unchanged.\n//\n// This indirection keeps governance an opt-in concern: call sites and\n// helpers (`recordGitLabTargetDispatch`, `recordRouterDispatch`, etc.)\n// don't need to know about Organization. The daemon plumbs Organization\n// → DispatchGovernance once at startup; everything else stays generic.\n//\n// Tests reset between cases via `setDefaultGovernance(undefined)` to\n// avoid leakage from one test's fixture into another's behaviour.\n\nlet _governance: DispatchGovernance | undefined\n\n/** Set the process-wide default governance. Called once at daemon\n * startup (or never, if INTENT_PM_GATE_ENABLED is off). */\nexport function setDefaultGovernance(g: DispatchGovernance | undefined): void {\n _governance = g\n}\n\n/** Read the current default. `decideAndCommit` falls back to this when\n * its caller didn't pass an explicit governance arg. Returns undefined\n * in test contexts that haven't set anything (no governance fires). */\nexport function getDefaultGovernance(): DispatchGovernance | undefined {\n return _governance\n}\n","import type { IntentLedger } from \"./ledger\"\nimport type { IntentDecision, IntentEventInput, IntentEvent } from \"./types\"\nimport { getDefaultGovernance } from \"./governance\"\n\n// decideAndCommit — Phase 1 of the architectural rescue.\n//\n// The single function every dispatch source will route through. Every event\n// entering the system flows: source-adapter → decideAndCommit → (optional\n// agent dispatch). The function's job is to:\n//\n// 1. Record the event idempotently (Inv-Idempotence)\n// 2. Consult the ledger for active-task state (Inv-ActiveTaskSafety)\n// 3. Ask the policy for a tentative decision\n// 4. Commit a single decision row to the ledger (Inv-NoSilentDrops)\n//\n// The four invariants are spelled out below and named so that Phase 2's\n// TLA+ spec can reference them by string. Tests in test/intent-decide.test.ts\n// cite these names in their assertion comments.\n//\n// **Phase 2 status**: three of the four invariants are formally verified\n// by TLC against `docs/architecture/DispatchSpec.tla` (410K distinct\n// states, depth 7, 0 violations as of 2026-04-29). The fourth\n// (Inv-Determinism) is a meta-property over traces, checked by code\n// review + the test in `intent-decide.test.ts`. See\n// `docs/architecture/dispatch-properties.md` for the full mapping\n// between code paths, invariants, and TLC results.\n//\n// Inv-Idempotence calling decideAndCommit twice with the same\n// (source, sourceEventId) and the same policy\n// produces one event row + one decision row;\n// the second call returns the row from the first.\n// Inv-Determinism given a fixed ledger snapshot, a fixed policy,\n// and a fixed clock, the resulting decision is a\n// pure function of the input event.\n// Inv-ActiveTaskSafety at most one decision with outcome=dispatched\n// that has not yet been resolved exists for any\n// (project, subject) at any point in the ledger.\n// Inv-NoSilentDrops every call to decideAndCommit appends exactly\n// one decision row to the ledger (or returns an\n// existing one under Inv-Idempotence). No code\n// path returns without a row visible in the ledger.\n//\n// What this commit does NOT do:\n// - Wire decideAndCommit into any real call site (commit 6).\n// - Add the mode flag (commit 4) — this function is reachable only from\n// tests until commit 6 wires it up behind a flag that defaults off.\n// - Read or expose the divergence reporter (commit 5).\n// - Run async or call out to network. Policies are sync; if a real call\n// site needs an LLM in the loop, that's a refactor for a later phase.\n\n/**\n * A pluggable dispatch policy. Each call site (channel router, workflow\n * dispatcher, gitlab handler, cron firing, mesh receiver) supplies its own\n * policy — the function below is purely the orchestration around the\n * policy's decision.\n *\n * The policy's `decidedBy` is the ledger's attribution string (\"who decided\n * this?\") and is what the ledger uses to scope idempotency: re-delivery of\n * the same event to the same `decidedBy` returns the existing row, while\n * the same event reaching a different `decidedBy` is a separate decision\n * (the chain-of-command case).\n */\nexport interface DispatchPolicy {\n /** Stable attribution string. Examples: `\"channel-router\"`,\n * `\"workflow:gitlab-sdlc-loop\"`, `\"gitlab-handler\"`. Must be stable\n * across calls — the ledger uses it as the per-policy idempotency key. */\n readonly decidedBy: string\n\n /**\n * Inspect the (already-recorded) event and return a tentative decision.\n * Return `null` to mean \"I have no opinion\" — the caller will record a\n * `halted` decision with reason `\"no policy match\"`.\n *\n * The policy MUST NOT write to the ledger directly. It MUST be a pure\n * function of `event` plus any read-only context the caller closed over\n * when constructing the policy. (Determinism — Inv-Determinism — depends\n * on this.)\n */\n decide(event: IntentEvent): PolicyDecision | null\n}\n\n/** What a policy returns. The `outcome` set excludes `\"deduped\"` because\n * dedup is the ledger's call, not the policy's. */\nexport interface PolicyDecision {\n agentId: string | null\n outcome: \"dispatched\" | \"halted\" | \"queued\"\n reason: string | null\n}\n\n/**\n * Phase 3 — Org-chart governance hooks. Optional. When supplied,\n * decideAndCommit consults them AFTER the policy decides:\n *\n * canHandle(agentId, project, intent) returns false → halt the\n * dispatch with reason \"org-chart: agent cannot handle\". Use to\n * enforce per-agent capability constraints (Phase 5 will add\n * typed capabilities; the v0 here is permissive).\n *\n * pmFor(project) returns the agentId of the\n * PM for `project`, or undefined when no PM is configured. When\n * defined AND the policy decided \"dispatched\", the decision's\n * `decidedBy` is rewritten to `pm:<pmId>` so the audit trail\n * attributes the dispatch to the PM gate. Per the kickoff:\n * \"a dispatch decision for (project, ...) where business.projects[].pm\n * is set never resolves to an agent without going through the PM\n * first (PM may rubber-stamp, but the decision row records\n * decided_by='pm:pm-mtgl')\".\n *\n * The full async-PM gate (synchronously dispatch to the PM agent,\n * wait up to 60s for approval, fall back to escalation on timeout)\n * is a future-phase refactor. The v0 here is the paper-trail gate:\n * the decision row is attributed to the PM, but no real call-out\n * happens. This satisfies the kickoff's property and unblocks the\n * 1c per-source promotions.\n */\nexport interface DispatchGovernance {\n canHandle?(agentId: string, project: string | null, intent: string | null): boolean\n pmFor?(project: string | null): string | undefined\n /** Phase 8 — capability-bounded security. Returns false when\n * dispatching `agentId` on `(project, subject)` would exceed the\n * agent's delegation-depth budget. Blocks cascade loops by\n * walking the ledger's prior decisions on the same slot. */\n withinDelegationBudget?(agentId: string, project: string | null, subject: string | null): boolean\n}\n\n/**\n * Append-only dispatch primitive. Returns the canonical decision row —\n * either freshly written or recovered from a prior call (Inv-Idempotence).\n *\n * The whole call runs inside a single SQLite transaction so the lookup\n * (`getDecisionsForEvent` + `getActiveDecisionForSubject`) and the write\n * (`recordDecision`) are atomic with respect to the same database. This\n * matters under concurrent-call scenarios; in the single-process daemon\n * use case, better-sqlite3 already serialises writes so the transaction\n * is belt-and-braces. Adding it now means the call-site wiring (commit 6)\n * can call decideAndCommit from anywhere without worrying about races.\n */\nexport function decideAndCommit(\n ledger: IntentLedger,\n input: IntentEventInput,\n policy: DispatchPolicy,\n now: () => number = Date.now,\n governance?: DispatchGovernance,\n): IntentDecision {\n const tx = ledger.db.transaction((decidedAt: number): IntentDecision => {\n // Step 1 — record the event. recordEvent is itself idempotent on\n // (source, sourceEventId), so this is safe under re-delivery.\n const event = ledger.recordEvent(input)\n\n // Phase 3 governance: compute the EFFECTIVE decidedBy upfront so\n // it threads through idempotency + recording. When a PM is\n // configured for the project, the decision is attributed to the\n // PM (pm:<id>) regardless of outcome — the PM is the gate, even\n // for halts and queues. canHandle is a veto applied later (forces\n // outcome=halted) but doesn't change decidedBy.\n //\n // Falls back to the daemon-level singleton (`getDefaultGovernance`)\n // when the caller doesn't pass an explicit governance — this is\n // the production path. Tests pass governance directly.\n const gov = governance ?? getDefaultGovernance()\n const pm = gov?.pmFor?.(event.project)\n const effectiveDecidedBy = pm ? `pm:${pm}` : policy.decidedBy\n\n // Step 2 — Inv-Idempotence. If this policy has already decided on this\n // event, return that decision unchanged. Two callers who race the same\n // event-policy pair are reduced to a single decision row.\n const prior = ledger\n .getDecisionsForEvent(event.id)\n .find((d) => d.decidedBy === effectiveDecidedBy)\n if (prior) return prior\n\n // Step 3 — Inv-ActiveTaskSafety. If a dispatched-and-unresolved\n // decision already exists for (project, subject), this event must\n // dedupe. The dedup outcome is ledger-managed; the policy never sees\n // a chance to override it.\n const active = ledger.getActiveDecisionForSubject(event.project, event.subject)\n if (active) {\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId: null,\n outcome: \"deduped\",\n reason: `active dispatch in flight: ${active.decidedBy} → ${active.agentId ?? \"?\"}`,\n }\n ledger.recordDecision(decision)\n return decision\n }\n\n // Step 4 — consult the policy. A null result is a halt with explicit\n // reason rather than a silent drop (Inv-NoSilentDrops). A halted /\n // queued / dispatched policy decision flows through unchanged.\n const policyResult = policy.decide(event)\n let agentId: string | null = policyResult ? policyResult.agentId : null\n let outcome: \"dispatched\" | \"halted\" | \"queued\" = policyResult ? policyResult.outcome : \"halted\"\n let reason: string | null = policyResult ? policyResult.reason : \"no policy match\"\n\n // Step 5 — canHandle veto. Dispatches to agents the org chart says\n // can't handle the event get forced to halted.\n if (gov?.canHandle && outcome === \"dispatched\" && agentId) {\n const allowed = gov.canHandle(agentId, event.project, event.intent)\n if (!allowed) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `org-chart: agent \"${blocked}\" cannot handle (${event.project ?? \"no-project\"}/${event.intent ?? \"no-intent\"})`\n }\n }\n\n // Step 5b — Phase 8 delegation-depth check. Walks the ledger's\n // prior decisions on (project, subject) and refuses dispatches\n // that would push the chain past the agent's\n // `maxDelegationDepth`. Prevents cascade loops where A → B → A → ...\n // blows past sane chain depth.\n if (gov?.withinDelegationBudget && outcome === \"dispatched\" && agentId) {\n if (!gov.withinDelegationBudget(agentId, event.project, event.subject)) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `delegation-budget: agent \"${blocked}\" depth-limit exceeded on ${event.project ?? \"?\"}/${event.subject ?? \"?\"}`\n }\n }\n\n // Annotate the reason when PM-gate took effect, so the audit trail\n // distinguishes pm-gated dispatches from regular ones.\n if (pm && outcome === \"dispatched\" && agentId) {\n reason = reason\n ? `${reason} (pm-gate: rubber-stamped by ${pm})`\n : `pm-gate: rubber-stamped by ${pm}`\n }\n\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId,\n outcome,\n reason,\n }\n ledger.recordDecision(decision)\n return decision\n })\n\n return tx(now())\n}\n","import { logger } from \"../utils/logger\"\nimport type { IntentLedger } from \"./ledger\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentOutcomeKind,\n IntentSource,\n} from \"./types\"\n\n// Divergence reporter — Phase 1 commit 5 of the architectural rescue.\n//\n// During shadow mode (1b in research-rescue-plan.md §7), every dispatch\n// runs through both the legacy path and decideAndCommit. The legacy path\n// remains authoritative; the ledger's decision is recorded but does not\n// drive behaviour. The reporter compares the two and:\n//\n// - on agreement: no-op (the soak's success criterion is \"zero\n// divergences for ≥7 days\" — quiet operation IS the signal).\n// - on mismatch: log a structured warning AND write a row to\n// intent_divergences so the soak dashboard has a queryable surface.\n//\n// The shape of \"the legacy outcome\" is deliberately structural rather\n// than tied to any one source's existing output type — that lets the\n// commit-6 wiring adapt each call site (channel-router's `Routed`, the\n// workflow dispatcher's `DispatchResult`, etc.) into a common\n// LegacyOutcome at the comparison boundary instead of carrying source-\n// specific shapes through the reporter.\n\n/** Minimal projection of a legacy dispatch path's outcome — only the\n * fields we compare against the ledger decision. */\nexport interface LegacyOutcome {\n agentId: string | null\n outcome: IntentOutcomeKind\n /** Optional human-readable reason; recorded for forensics, never\n * compared. (Legacy reasons and ledger reasons phrase the same\n * decision differently — comparing them would produce noise.) */\n reason?: string | null\n}\n\n/**\n * Compare a ledger decision against the legacy path's outcome. On mismatch,\n * append a divergence row and emit a `[ledger-divergence]` log line.\n * Returns `true` when a divergence was recorded, `false` on agreement.\n *\n * Comparison is structural on the load-bearing fields: `outcome` and\n * `agentId`. `reason` strings differ harmlessly between paths and are\n * forensic-only — comparing them would produce noise that drowns out\n * the actual semantic mismatches we care about.\n */\nexport function reportDivergence(\n ledger: IntentLedger,\n source: IntentSource,\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n now: () => number = Date.now,\n): boolean {\n if (decisionsAgree(ledgerDecision, legacy)) return false\n\n const ts = now()\n const record: IntentDivergence = {\n id: newEventId(ts),\n ts,\n source,\n eventId: ledgerDecision.eventId,\n decidedBy: ledgerDecision.decidedBy,\n ledgerAgentId: ledgerDecision.agentId,\n ledgerOutcome: ledgerDecision.outcome,\n ledgerReason: ledgerDecision.reason,\n legacyAgentId: legacy.agentId,\n legacyOutcome: legacy.outcome,\n legacyReason: legacy.reason ?? null,\n }\n ledger.recordDivergence(record)\n\n // Single-line structured log so journalctl + grep are sufficient triage\n // tools during the soak (commit 8 adds a UI; until then, journal is it).\n logger.warn(\n `[ledger-divergence] source=${source} ` +\n `event=${ledgerDecision.eventId} ` +\n `decided_by=${ledgerDecision.decidedBy} ` +\n `ledger=${ledgerDecision.outcome}/${ledgerDecision.agentId ?? \"null\"} ` +\n `legacy=${legacy.outcome}/${legacy.agentId ?? \"null\"}`,\n )\n return true\n}\n\n/** Two outcomes agree iff they pick the same target with the same outcome\n * kind. Reasons (free-form) are not part of agreement.\n *\n * AgentIds that wrap a fresh-per-call instance id (workflow-run:<uuid>,\n * mesh-fwd:<id>) are normalized to the prefix before comparison — both\n * paths legitimately dispatch the same kind of work but with different\n * instance handles, and treating those as divergences buries the real\n * semantic mismatches in noise (Phase 1 soak finding: ~290 false\n * positives across both nodes pre-fix). */\nexport function decisionsAgree(\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n): boolean {\n return (\n ledgerDecision.outcome === legacy.outcome &&\n normalizeSyntheticAgentId(ledgerDecision.agentId) === normalizeSyntheticAgentId(legacy.agentId)\n )\n}\n\nfunction normalizeSyntheticAgentId(id: string | null): string | null {\n if (!id) return null\n const m = id.match(/^(workflow-run|mesh-fwd):/)\n return m ? `${m[1]}:*` : id\n}\n","import type { IntentLedger } from \"../ledger\"\nimport { decideAndCommit, type DispatchPolicy } from \"../decide\"\nimport { reportDivergence, type LegacyOutcome } from \"../divergence\"\nimport type { IntentDecision, IntentEventInput } from \"../types\"\n\n// Source adapter — cron scheduler. Phase 1 commit 6.d.\n//\n// Cron is the cleanest 1:1 dispatch source: one fire → one agent. The\n// scheduler's `executeJob(jobId)` is the dispatch entry point. We\n// instrument the two decision branches (hook-blocked vs hook-approved)\n// and pass the legacy outcome to a pass-through policy.\n\nexport interface CronJobProjection {\n jobId: string\n agentId: string\n /** When the job fired (used as part of the ULID-friendly sourceEventId). */\n firedAt: Date\n}\n\n/** Build the IntentEventInput for one cron fire. sourceEventId is\n * per-(jobId, firedAt) so concurrent re-fires (shouldn't happen but)\n * collapse via idempotency. Subject scopes active-task safety to one\n * fire-in-flight per job — but project=null disables Inv-ActiveTaskSafety,\n * so successive fires of the same job both dispatch (matches legacy). */\nexport function buildCronEventInput(\n proj: CronJobProjection,\n rawJson: string,\n now: () => number = Date.now,\n): IntentEventInput {\n return {\n ts: now(),\n source: \"cron\",\n sourceEventId: `${proj.jobId}:${proj.firedAt.getTime()}`,\n project: null,\n subject: `cron:${proj.jobId}`,\n intent: \"cron.fired\",\n rawJson,\n }\n}\n\n/** Pass-through policy. Same shape as router/workflow: divergences come\n * from ledger MECHANICS, not policy disagreement. */\nexport function buildCronPolicyFromLegacy(legacy: LegacyOutcome): DispatchPolicy {\n return {\n decidedBy: \"cron-scheduler\",\n decide: () => ({\n agentId: legacy.agentId,\n outcome: legacy.outcome === \"deduped\" ? \"halted\" : legacy.outcome,\n reason:\n legacy.outcome === \"deduped\"\n ? `legacy-dedup: ${legacy.reason ?? \"\"}`.trim()\n : legacy.reason ?? null,\n }),\n }\n}\n\nexport function recordCronDispatch(\n ledger: IntentLedger,\n proj: CronJobProjection,\n rawJson: string,\n legacyOutcome: LegacyOutcome,\n now: () => number = Date.now,\n): IntentDecision {\n const eventInput = buildCronEventInput(proj, rawJson, now)\n const policy = buildCronPolicyFromLegacy(legacyOutcome)\n const ledgerDecision = decideAndCommit(ledger, eventInput, policy, now)\n reportDivergence(ledger, \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jF,WACrB,kBAAmBA,EAAE,kBACrB,UAAWA,EAAE,SACf,EAAE,CACJ,CACF,CACF","names":["writeFileSync","mkdirSync","existsSync","readFileSync","resolve","VALID_MODES","PER_SOURCE_ENV_VAR","GLOBAL_ENV_VAR","getLedgerMode","source","env","perSource","parseLedgerMode","global","value","normalized","Database","existsSync","mkdirSync","dirname","resolve","randomBytes","ENCODING","TIME_LEN","RAND_LEN","encodeTime","ms","out","i","encodeRandom","bytes","newEventId","now","IntentLedger","opts","resolve","mkdirSync","dirname","Database","runMigrations","input","existing","event","newEventId","source","sourceEventId","row","rowToEvent","id","decision","eventId","rowToDecision","project","subject","resolution","reason","now","rows","ts","count","decidedBy","rowToResolution","divergence","wheres","params","whereSql","limitSql","rowToDivergence","db","current","migrationV1","migrationV2","_ledger","getDefaultLedger","opts","IntentLedger","_governance","setDefaultGovernance","g","getDefaultGovernance","decideAndCommit","ledger","input","policy","now","governance","decidedAt","event","gov","getDefaultGovernance","pm","effectiveDecidedBy","prior","d","active","decision","policyResult","agentId","outcome","reason","blocked","reportDivergence","ledger","source","ledgerDecision","legacy","now","decisionsAgree","ts","record","newEventId","logger","normalizeSyntheticAgentId","id","m","buildCronEventInput","proj","rawJson","now","buildCronPolicyFromLegacy","legacy","recordCronDispatch","ledger","legacyOutcome","eventInput","policy","ledgerDecision","decideAndCommit","reportDivergence","withOutputCap","prompt","maxOutputTokens","approxChars","parseCronField","field","min","max","values","part","i","range","stepStr","step","start","a","b","getNextCronDate","expression","after","timezone","fields","minutes","hours","daysOfMonth","months","daysOfWeek","fmt","candidate","limit","parts","get","type","p","m","h","dom","mon","dow","MAX_RETRIES","RETRY_DELAYS","CronScheduler","config","registry","hooks","log","resolve","id","def","cb","existsSync","mkdirSync","missedRuns","jobId","missedAt","e","job","j","timer","existing","nextRun","delay","attempt","agentId","firedAt","legacy","getLedgerMode","decision","recordCronDispatch","getDefaultLedger","retryAttempt","isRetry","hookResult","startedAt","intentRef","response","result","res","applyConfigMutation","cfg","setAtPath","missed","lastRuns","lastRunStr","lastRun","shouldHaveRun","error","data","dir","writeFileSync","readFileSync","runDir","filename","jobs"]}
@@ -1,2 +0,0 @@
1
- import{a as u}from"./chunk-VJUTQAPJ.js";import{existsSync as R,promises as y}from"fs";import m from"path";import x from"js-yaml";import I from"fast-glob";import{z as e}from"zod";var w=e.object({id:e.string(),priority:e.number().default(0),when:e.object({agentIds:e.array(e.string()).optional(),intentTags:e.array(e.string()).optional(),messageRegex:e.array(e.string()).optional(),requireTags:e.array(e.string()).optional()}).default({}),references:e.array(e.string()).default([]),skills:e.array(e.string()).default([]),maxChars:e.number().int().min(100).max(8e3).optional()}),C=e.object({recipes:e.array(w)}),v=["references/recipes",".references/recipes",".agentx/references/recipes",".agentx/recipes"];async function $(o){let t={recipes:[],sourceById:new Map};for(let r of v){let s=m.resolve(o,r);if(!R(s))continue;let n=await I.glob("**/*.{yaml,yml}",{cwd:s,deep:5});for(let d of n){let a=m.resolve(s,d);try{let f=await y.readFile(a,"utf8"),i=x.load(f),c=C.parse(i);for(let p of c.recipes){if(t.sourceById.has(p.id))throw new Error(`recipe id "${p.id}" duplicated in ${a}`);t.recipes.push(p),t.sourceById.set(p.id,a)}}catch(f){u.warn({file:a,error:f?.message},"recipes: failed to load file")}}}return t}function z(o,t,r){let s=[];for(let i of t.recipes)S(i,o)&&s.push(i);s.sort((i,c)=>c.priority-i.priority||i.id.localeCompare(c.id));let n=new Set,d=[],a=new Set,f=[];for(let i of s){for(let c of i.references){let p=b(c,r);p.length===0&&f.push(c);for(let l of p){if(n.has(l))continue;let g=r.byId.get(l);if(!g){f.push(l);continue}i.when.requireTags?.length&&!i.when.requireTags.every(h=>g.tags.includes(h))||(n.add(l),d.push(g))}}for(let c of i.skills)a.add(c)}return{matched:s,cards:d,requiredSkills:[...a],unresolvedIds:[...new Set(f)]}}function S(o,t){let r=o.when;if(r.agentIds?.length&&!r.agentIds.includes(t.agentId))return!1;if(r.intentTags?.length){let s=t.intentTags??[];if(!r.intentTags.some(d=>s.includes(d)))return!1}return!(r.messageRegex?.length&&!r.messageRegex.some(n=>{try{return new RegExp(n,"i").test(t.message)}catch{return t.message.toLowerCase().includes(n.toLowerCase())}}))}function b(o,t){if(!o.endsWith(".*"))return[o];let r=o.slice(0,-2),s=[];for(let n of t.byId.keys())(n===r||n.startsWith(`${r}.`))&&s.push(n);return s}export{$ as a,z as b};
2
- //# sourceMappingURL=chunk-53NRX2NA.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/agents/references/recipes.ts"],"sourcesContent":["import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport yaml from \"js-yaml\"\nimport fg from \"fast-glob\"\nimport { z } from \"zod\"\nimport { logger } from \"@/utils/logger\"\nimport type { ReferenceCard, ReferenceIndex } from \"./types\"\n\n// --- Recipes ---\n//\n// Map (agentId, optional intent tag, optional message keyword) to a bundle of\n// reference card ids and skill names. Pure deterministic lookup — no LLM in\n// the hot path. Multiple recipes can match a single turn; the resolver merges\n// their reference sets and de-duplicates.\n\nconst recipeSchema = z.object({\n id: z.string(),\n /** Higher = picked first when budgets bite. Default 0. */\n priority: z.number().default(0),\n when: z\n .object({\n agentIds: z.array(z.string()).optional(),\n intentTags: z.array(z.string()).optional(),\n /** OR'd, case-insensitive regex sources. */\n messageRegex: z.array(z.string()).optional(),\n /** Tags to require on the card pool. Cards must carry every tag. */\n requireTags: z.array(z.string()).optional(),\n })\n .default({}),\n /** Card ids OR \".*\" glob suffixes — \"ksi.contacts.*\" matches all under that prefix. */\n references: z.array(z.string()).default([]),\n /** Skill names that should be considered required for this intent (audit lint\n * flags FAILING when a referenced skill has no SKILL.md). */\n skills: z.array(z.string()).default([]),\n /** Per-recipe char budget. Total is enforced by the layer; this is advisory. */\n maxChars: z.number().int().min(100).max(8000).optional(),\n})\nexport type Recipe = z.infer<typeof recipeSchema>\n\nconst recipeFileSchema = z.object({\n recipes: z.array(recipeSchema),\n})\n\nexport interface RecipeIndex {\n recipes: Recipe[]\n /** Source path per recipe id. */\n sourceById: Map<string, string>\n}\n\nconst RECIPE_DIRS = [\n \"references/recipes\",\n \".references/recipes\",\n \".agentx/references/recipes\",\n \".agentx/recipes\",\n]\n\nexport async function loadRecipes(cwd: string): Promise<RecipeIndex> {\n const index: RecipeIndex = { recipes: [], sourceById: new Map() }\n for (const dir of RECIPE_DIRS) {\n const abs = path.resolve(cwd, dir)\n if (!existsSync(abs)) continue\n const files = await fg.glob(\"**/*.{yaml,yml}\", { cwd: abs, deep: 5 })\n for (const rel of files) {\n const file = path.resolve(abs, rel)\n try {\n const raw = await fs.readFile(file, \"utf8\")\n const parsed = yaml.load(raw)\n const validated = recipeFileSchema.parse(parsed)\n for (const recipe of validated.recipes) {\n if (index.sourceById.has(recipe.id)) {\n throw new Error(`recipe id \"${recipe.id}\" duplicated in ${file}`)\n }\n index.recipes.push(recipe)\n index.sourceById.set(recipe.id, file)\n }\n } catch (e: any) {\n logger.warn({ file, error: e?.message }, \"recipes: failed to load file\")\n }\n }\n }\n return index\n}\n\nexport interface RecipeContext {\n agentId: string\n intentTags?: string[]\n message: string\n}\n\nexport interface ResolvedRecipes {\n matched: Recipe[]\n cards: ReferenceCard[]\n /** Skill names required by the matched recipes. */\n requiredSkills: string[]\n /** Reference ids in the recipes that did NOT resolve — used by audit lint. */\n unresolvedIds: string[]\n}\n\n/**\n * Match recipes deterministically. AND within a `when` clause, OR across\n * recipes. A recipe with no `when` always matches (use sparingly).\n */\nexport function resolveRecipes(\n ctx: RecipeContext,\n recipeIndex: RecipeIndex,\n referenceIndex: ReferenceIndex,\n): ResolvedRecipes {\n const matched: Recipe[] = []\n for (const recipe of recipeIndex.recipes) {\n if (recipeMatches(recipe, ctx)) matched.push(recipe)\n }\n // Highest priority first, then stable by id.\n matched.sort((a, b) => b.priority - a.priority || a.id.localeCompare(b.id))\n\n const seen = new Set<string>()\n const cards: ReferenceCard[] = []\n const skills = new Set<string>()\n const unresolvedIds: string[] = []\n\n for (const recipe of matched) {\n for (const ref of recipe.references) {\n const ids = expandReferenceIds(ref, referenceIndex)\n if (ids.length === 0) unresolvedIds.push(ref)\n for (const id of ids) {\n if (seen.has(id)) continue\n const card = referenceIndex.byId.get(id)\n if (!card) {\n unresolvedIds.push(id)\n continue\n }\n if (recipe.when.requireTags?.length) {\n const has = recipe.when.requireTags.every(t => card.tags.includes(t))\n if (!has) continue\n }\n seen.add(id)\n cards.push(card)\n }\n }\n for (const s of recipe.skills) skills.add(s)\n }\n\n return {\n matched,\n cards,\n requiredSkills: [...skills],\n unresolvedIds: [...new Set(unresolvedIds)],\n }\n}\n\nfunction recipeMatches(recipe: Recipe, ctx: RecipeContext): boolean {\n const w = recipe.when\n if (w.agentIds?.length && !w.agentIds.includes(ctx.agentId)) return false\n if (w.intentTags?.length) {\n const tags = ctx.intentTags ?? []\n const hit = w.intentTags.some(t => tags.includes(t))\n if (!hit) return false\n }\n if (w.messageRegex?.length) {\n const hit = w.messageRegex.some(src => {\n try {\n return new RegExp(src, \"i\").test(ctx.message)\n } catch {\n return ctx.message.toLowerCase().includes(src.toLowerCase())\n }\n })\n if (!hit) return false\n }\n return true\n}\n\n/**\n * Expand a reference id pattern. Plain ids return [id]. A trailing `.*` matches\n * any id with that prefix in the index.\n */\nfunction expandReferenceIds(pattern: string, idx: ReferenceIndex): string[] {\n if (!pattern.endsWith(\".*\")) return [pattern]\n const prefix = pattern.slice(0, -2)\n const out: string[] = []\n for (const id of idx.byId.keys()) {\n if (id === prefix || id.startsWith(`${prefix}.`)) out.push(id)\n }\n return out\n}\n"],"mappings":"wCAAA,OAAS,cAAAA,EAAY,YAAYC,MAAU,KAC3C,OAAOC,MAAU,OACjB,OAAOC,MAAU,UACjB,OAAOC,MAAQ,YACf,OAAS,KAAAC,MAAS,MAWlB,IAAMC,EAAeC,EAAE,OAAO,CAC5B,GAAIA,EAAE,OAAO,EAEb,SAAUA,EAAE,OAAO,EAAE,QAAQ,CAAC,EAC9B,KAAMA,EACH,OAAO,CACN,SAAUA,EAA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E,IAAMkB,EAAItB,EAAO,KACjB,GAAIsB,EAAE,UAAU,QAAU,CAACA,EAAE,SAAS,SAASlB,EAAI,OAAO,EAAG,MAAO,GACpE,GAAIkB,EAAE,YAAY,OAAQ,CACxB,IAAMC,EAAOnB,EAAI,YAAc,CAAC,EAEhC,GAAI,CADQkB,EAAE,WAAW,KAAKF,GAAKG,EAAK,SAASH,CAAC,CAAC,EACzC,MAAO,GAEnB,MAAI,EAAAE,EAAE,cAAc,QAQd,CAPQA,EAAE,aAAa,KAAKE,GAAO,CACrC,GAAI,CACF,OAAO,IAAI,OAAOA,EAAK,GAAG,EAAE,KAAKpB,EAAI,OAAO,CAC9C,MAAE,CACA,OAAOA,EAAI,QAAQ,YAAY,EAAE,SAASoB,EAAI,YAAY,CAAC,CAC7D,CACF,CAAC,EAIL,CAMA,SAASP,EAAmBQ,EAAiBC,EAA+B,CAC1E,GAAI,CAACD,EAAQ,SAAS,IAAI,EAAG,MAAO,CAACA,CAAO,EAC5C,IAAME,EAASF,EAAQ,MAAM,EAAG,EAAE,EAC5BG,EAAgB,CAAC,EACvB,QAAWV,KAAMQ,EAAI,KAAK,KAAK,GACzBR,IAAOS,GAAUT,EAAG,WAAW,GAAGS,IAAS,IAAGC,EAAI,KAAKV,CAAE,EAE/D,OAAOU,CACT","names":["existsSync","fs","path","yaml","fg","z","recipeSchema","z","recipeFileSchema","RECIPE_DIRS","loadRecipes","cwd","index","dir","abs","path","existsSync","files","fg","rel","file","raw","fs","parsed","yaml","validated","recipe","e","logger","resolveRecipes","ctx","recipeIndex","referenceIndex","matched","recipeMatches","a","b","seen","cards","skills","unresolvedIds","ref","ids","expandReferenceIds","id","card","t","s","w","tags","src","pattern","idx","prefix","out"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/agents/memory-extract.ts"],"sourcesContent":["import type { MemoryStore } from \"./memory-store\"\n\n// --- Haiku-powered memory extraction ---\n// Fire-and-forget after each agent response.\n// Extracts memorable facts and writes them to the persistent store.\n\nconst EXTRACTION_MODEL = \"claude-haiku-4-20250514\"\n\nconst EXTRACTION_PROMPT = `You are a memory extraction system for an AI agent. Given a conversation exchange, extract facts worth remembering for future conversations across different chat sessions.\n\nExtract ONLY facts that would help the agent in FUTURE, DIFFERENT conversations:\n- Credentials, tokens, API keys shared by the user\n- User preferences and instructions (\"never do X\", \"always use Y\")\n- Commitments the agent made (\"I will deploy by Friday\")\n- Relationships (\"Anis is the admin\", \"Nadia handles content\")\n- Task state (\"GitLab tokens need deploying to clawd-server\")\n- Important facts about infrastructure, config, or processes\n\nSKIP:\n- Routine greetings, acknowledgments, status updates\n- Information derivable from code or config files\n- Transient conversation flow (\"let me check\", \"here's what I found\")\n- Facts already obvious from the agent's system prompt\n\nFor each fact, output a JSON array:\n[{\"category\":\"fact|secret|preference|commitment|task-state\",\"content\":\"concise fact, 1-2 sentences\",\"keywords\":[\"keyword1\",\"keyword2\"]}]\n\nIf nothing worth remembering, output: []`\n\nexport async function extractMemories(\n agentId: string,\n userMessage: string,\n agentResponse: string,\n source: { channel: string; chatId: string; sender: string },\n store: MemoryStore,\n): Promise<void> {\n // Skip very short exchanges (unlikely to contain memorable facts)\n if (userMessage.length < 20 && agentResponse.length < 50) return\n\n const { createProvider } = await import(\"@/agent/providers\")\n const provider = createProvider(\"claude\")\n\n const result = await provider.generate(\n [\n { role: \"system\", content: EXTRACTION_PROMPT },\n {\n role: \"user\",\n content: `${source.sender} (via ${source.channel}): ${userMessage}\\n\\nAgent: ${agentResponse}`,\n },\n ],\n { model: EXTRACTION_MODEL, maxTokens: 512 },\n )\n\n // Parse JSON array from response\n const content = result.content.trim()\n const jsonMatch = content.match(/\\[[\\s\\S]*\\]/)\n if (!jsonMatch) return\n\n const facts = JSON.parse(jsonMatch[0]) as Array<{\n category: string\n content: string\n keywords: string[]\n }>\n\n if (!Array.isArray(facts) || facts.length === 0) return\n\n const date = new Date().toISOString().slice(0, 10)\n\n for (const fact of facts) {\n // Skip duplicates\n if (store.hasSimilar(agentId, fact.content)) continue\n\n store.addMemory(agentId, {\n agentId,\n category: fact.category as any,\n content: fact.content,\n keywords: fact.keywords || [],\n source: { ...source, date },\n expiresAt: fact.category === \"task-state\"\n ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()\n : undefined,\n })\n }\n\n // Prune occasionally (every ~50 calls, probabilistic)\n if (Math.random() < 0.02) {\n store.prune(agentId)\n }\n}\n"],"mappings":"AAMA,IAAMA,EAAmB,0BAEnBC,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0CAqB1B,eAAsBC,EACpBC,EACAC,EACAC,EACAC,EACAC,EACe,CAEf,GAAIH,EAAY,OAAS,IAAMC,EAAc,OAAS,GAAI,OAE1D,GAAM,CAAE,eAAAG,CAAe,EAAI,KAAM,QAAO,yBAAmB,EAgBrDC,GAbS,MAFED,EAAe,QAAQ,EAEV,SAC5B,CACE,CAAE,KAAM,SAAU,QAASP,CAAkB,EAC7C,CACE,KAAM,OACN,QAAS,GAAGK,EAAO,eAAeA,EAAO,aAAaF;AAAA;AAAA,SAAyBC,GACjF,CACF,EACA,CAAE,MAAOL,EAAkB,UAAW,GAAI,CAC5C,GAGuB,QAAQ,KAAK,EACV,MAAM,aAAa,EAC7C,GAAI,CAACS,EAAW,OAEhB,IAAMC,EAAQ,KAAK,MAAMD,EAAU,CAAC,CAAC,EAMrC,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAKA,EAAM,SAAW,EAAG,OAEjD,IAAMC,EAAO,IAAI,KAAK,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,EAEjD,QAAWC,KAAQF,EAEbH,EAAM,WAAWJ,EAASS,EAAK,OAAO,GAE1CL,EAAM,UAAUJ,EAAS,CACvB,QAAAA,EACA,SAAUS,EAAK,SACf,QAASA,EAAK,QACd,SAAUA,EAAK,UAAY,CAAC,EAC5B,OAAQ,CAAE,GAAGN,EAAQ,KAAAK,CAAK,EAC1B,UAAWC,EAAK,WAAa,aACzB,IAAI,KAAK,KAAK,IAAI,EAAI,EAAI,GAAK,GAAK,GAAK,GAAI,EAAE,YAAY,EAC3D,MACN,CAAC,EAIC,KAAK,OAAO,EAAI,KAClBL,EAAM,MAAMJ,CAAO,CAEvB","names":["EXTRACTION_MODEL","EXTRACTION_PROMPT","extractMemories","agentId","userMessage","agentResponse","source","store","createProvider","jsonMatch","facts","date","fact"]}
@@ -1,108 +0,0 @@
1
- import{a as _,b as P,c as T,d as G}from"./chunk-JTJIPNXY.js";import{b as Q}from"./chunk-64P4QHSZ.js";import{m as X}from"./chunk-FDWOECJY.js";import{c as M,d as L}from"./chunk-QOYAX2FT.js";var A={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},F=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as D,writeFileSync as J,appendFileSync as re,existsSync as I,mkdirSync as q,renameSync as ie}from"fs";import{resolve as E,dirname as ee}from"path";import{createHash as ne}from"crypto";var U=class{baseDir;log;constructor(e={}){this.baseDir=e.baseDir??E(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),q(this.baseDir,{recursive:!0})}schemaPath(){return E(this.baseDir,"schema.json")}nodesPath(){return E(this.baseDir,"nodes.json")}indexPath(){return E(this.baseDir,"index.json")}classificationsPath(){return E(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!I(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;let t=D(e,"utf-8"),s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{J(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(o){this.log(`could not back up old schema: ${o?.message??o}`)}this.saveSchema(A);let n=this.nodesPath();if(I(n)){let o=n.replace(/\.json$/,".v1.bak.json");try{J(o,D(n,"utf-8")),this.log(`archived v1 nodes.json -> ${o}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=Z();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!I(e)){let r=Z();return this.saveNodes(r),r}let t=D(e,"utf-8"),s=T.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.nodesPath(),t.data)}validateNode(e,t,s){let r=t.levels.find(i=>i.id===e.level);if(!r)throw new Error(`Unknown level: "${e.level}"`);let n=r.axes.filter(i=>!i.optional).filter(i=>!(i.name in e.axes));if(n.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${n.map(i=>i.name).join(", ")}`);for(let i of r.axes){let a=e.axes[i.name];if(a!=null){if(i.type==="enum"&&i.values&&!i.values.includes(a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" refers to unknown node`);if(i.refLevel){let c=s.find(h=>h.id===a);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let o=t.levels.findIndex(i=>i.id===e.level);if(o===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let i=s.find(c=>c.id===e.parentId);if(!i)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let a=t.levels.findIndex(c=>c.id===i.level);if(a<0||a>=o)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${i.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,s,r){let n=[],o=[],i=new Date().toISOString();for(let a=0;a<e.length;a++){let c=e[a],h=this.loadNodes().nodes;if(h.find(v=>v.id===c)){o.push(c);continue}let d=0;for(let v=a-1;v>=0;v--){let w=e[v],N=h.find(k=>k.id===w)||n.find(k=>k.id===w);if(N){d=s.levels.findIndex(k=>k.id===N.level)+1;break}}let u=t[c]??{},l=null;for(let v=d;v<s.levels.length;v++){let w=s.levels[v];if(w.axes.filter(k=>!k.optional).filter(k=>!(k.name in u)).length===0){l=w.id,d=v+1;break}}if(!l&&d<s.levels.length&&(l=s.levels[d].id,d++),!l)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${d}, levels=${s.levels.length})`);let p=null,m=s.levels.findIndex(v=>v.id===l);for(let v=a-1;v>=0;v--){let w=e[v],N=h.find(C=>C.id===w)||n.find(C=>C.id===w);if(!N)continue;let k=s.levels.findIndex(C=>C.id===N.level);if(k>=0&&k<m){p=w;break}}let f={id:c,level:l,parentId:p,axes:u,createdAt:i,createdBy:r};this.addNode(f),n.push(f)}return{added:n,skipped:o}}addNode(e){let t=this.loadSchema(),s=this.loadNodes();if(s.nodes.some(r=>r.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...s.nodes,e]),s.nodes.push(e),this.saveNodes(s),e}appendClassification(e){let t=P.safeParse(e);if(!t.success){let n=t.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${n} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let s=JSON.stringify(t.data)+`
2
- `,r=this.classificationsPath();return I(r)||q(ee(r),{recursive:!0}),re(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!I(e))return[];let s=D(e,"utf-8").split(`
3
- `).filter(Boolean),r=new Map;for(let n of s)try{let o=P.safeParse(JSON.parse(n));if(!o.success)continue;r.set(o.data.msgHash,o.data)}catch{}return Array.from(r.values()).sort((n,o)=>n.ts<o.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(o=>o.msgHash===e);if(!r)return null;let n={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let o=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;n.preview=((r.preview||"")+o).slice(0,500)}return this.appendClassification(n),n}readRecentClassifications(e=50){let t=this.classificationsPath();if(!I(t))return[];let r=D(t,"utf-8").split(`
4
- `).filter(Boolean),n=[];for(let o=r.length-1;o>=0&&n.length<e;o--)try{let i=P.safeParse(JSON.parse(r[o]));i.success&&n.push(i.data)}catch{}return n}fingerprint(e){let s=[e.text.toLowerCase().replace(/\s+/g," ").trim(),e.channel??"",e.sender??""].join("");return ne("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){let e=this.indexPath();if(!I(e))return{version:1,entries:{}};let t=D(e,"utf-8"),s=G.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.indexPath(),t.data)}getFingerprint(e){return this.loadIndex().entries[e]}setFingerprint(e,t){let s=this.loadIndex();s.entries[e]={...t,fingerprint:e,updatedAt:new Date().toISOString()},this.saveIndex(s)}updateNodeAxes(e,t){let s=this.loadSchema(),r=this.loadNodes(),n=r.nodes.find(i=>i.id===e);if(!n)throw new Error(`Node not found: ${e}`);let o={...n,axes:t};return this.validateNode(o,s,r.nodes.map(i=>i.id===e?o:i)),r.nodes=r.nodes.map(i=>i.id===e?o:i),this.saveNodes(r),o}deleteNode(e){let t=this.loadNodes(),s=t.nodes.find(n=>n.parentId===e);if(s)throw new Error(`Cannot delete "${e}" \u2014 child node "${s.id}" still points to it`);let r=t.nodes.find(n=>Object.values(n.axes).some(o=>o===e));if(r)throw new Error(`Cannot delete "${e}" \u2014 node "${r.id}" references it via an axis`);t.nodes=t.nodes.filter(n=>n.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),s=new Set(this.loadNodes().nodes.map(r=>r.id));for(let r=0;r<e.path.length;r++){let n=e.path[r];if(s.has(n))continue;let o=t.levels[r]?.id;if(!o)break;let i=e.proposedAxes?.[n]??{},a=r===0?null:e.path[r-1];this.addNode({id:n,level:o,parentId:a,axes:i,createdAt:new Date().toISOString(),createdBy:e.agentId}),s.add(n)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function B(g,e){q(ee(g),{recursive:!0});let t=`${g}.tmp-${process.pid}`;J(t,JSON.stringify(e,null,2)),ie(t,g)}function Z(){let g=new Date().toISOString(),e=[],t=new Set;for(let s of F)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:g,createdBy:"starter"}),t.add(s.category));for(let s of F)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:g,createdBy:"starter"});return{version:1,nodes:e}}import{createHash as oe}from"crypto";var H=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=X(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),s=this.store.getFingerprint(t);if(s)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:s.path,proposedAxes:{},leaf:s.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:s.path,pathId:z(s.path),pathLabel:V(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),n=this.store.loadNodes().nodes,o=await this.proposePath(e,r,n).catch(f=>(this.log("LLM proposal failed:",f?.message||f),null));if(!o)return null;let{path:i,proposedAxes:a,confidence:c,leaf:h}=o;if(i.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:a,leaf:h,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},d=new Set(n.map(f=>f.id)),u=i.map((f,v)=>d.has(f)?-1:v).filter(f=>f>=0),l=!1;if(this.autoApproveStructure==="any")l=!0;else if(this.autoApproveStructure==="extend-leaves"){let f=u.length===0,v=u.length===1&&u[0]===i.length-1;l=f||v}let p=c!==void 0&&c>=this.autoApprove,m="pending";if(l||p)try{this.commitNewNodes(i,a,r,n,e.sender),this.store.setFingerprint(t,{path:i,leaf:h}),m="approved"}catch(f){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(f?.message||f).toString().slice(0,200)}`)}return b.status=m,this.store.appendClassification(b),{path:i,pathId:z(i),pathLabel:V(i,this.store.loadNodes().nodes),axes:a,leaf:h,source:"llm",status:m,confidence:c}}async proposePath(e,t,s){let r=s.map(l=>({id:l.id,level:l.level,parentId:l.parentId,axes:l.axes})),n=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(r,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on mtgl/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "noqta", "mtgl-v2", "review-mr-957-system"]','- "Deploy ksi-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "noqta", "ksi-v2", "deploy-ksi-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
- `),o=await this.callProvider(n),i=ae(o);if(!i||!Array.isArray(i.path))return null;let a=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,h=i.path.filter(l=>typeof l=="string"&&l.length>0).map(l=>{let p=l.trim(),m=te(p);return p!==m&&c.set(p,m),m}).filter(l=>a.test(l));if(h.length===0)return null;let b={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[l,p]of Object.entries(i.proposedAxes)){if(!p||typeof p!="object")continue;let m=c.get(l)??te(l);if(!m)continue;let f={};for(let[v,w]of Object.entries(p))typeof w=="string"&&(f[v]=w);!f.name&&l!==m&&(f.name=l.trim()),b[m]=f}let d={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(d.input=i.leaf.input),typeof i.leaf.output=="string"&&(d.output=i.leaf.output));let u=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:h,proposedAxes:b,confidence:u,leaf:d}}commitNewNodes(e,t,s,r,n){this.store.commitNodesAlongPath(e,t,s,n)}async callProvider(e){let t=this.getProvider(),s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800})).content||""}finally{clearTimeout(r)}}};function te(g){let e=g.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function z(g){return oe("sha1").update(g.join("")).digest("hex").slice(0,16)}function V(g,e){return g.map(t=>{let s=e.find(n=>n.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function Y(g,e){if(g.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(g.length,e.length)&&g[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(g.length,e.length);return t/s}function ae(g){if(!g)return null;try{return JSON.parse(g)}catch{}let e=g.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1])}catch{}let t=g.indexOf("{");if(t<0)return null;let s=0;for(let r=t;r<g.length;r++)if(g[r]==="{")s++;else if(g[r]==="}"&&(s--,s===0))try{return JSON.parse(g.slice(t,r+1))}catch{return null}return null}import{readFileSync as W,writeFileSync as S,appendFileSync as ce,existsSync as x,mkdirSync as j,readdirSync as O,statSync as le}from"fs";import{resolve as y,join as de,relative as $,dirname as pe}from"path";var R=class{baseDir;rawDir;log;constructor(e=y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=y(e,"raw/entries"),this.log=t,j(this.rawDir,{recursive:!0}),j(y(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return e.access==="public"?!0:t?!!(e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t)):!1}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=y(this.rawDir,t),r=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&r.push(`context: ${e.sourceContext}`),e.meta)for(let[n,o]of Object.entries(e.meta))r.push(`${n}: ${JSON.stringify(o)}`);return r.push("---","",e.content),S(s,r.join(`
6
- `)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!x(this.rawDir))return[];let t=O(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let n=W(y(this.rawDir,r),"utf-8"),o=this.parseEntry(n,r);o&&(e?.agentId&&o.agentId!==e.agentId||e?.after&&o.date<e.after||e?.before&&o.date>e.before||s.push(o))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),o=i=>r.match(new RegExp(`^${i}:\\s*(.+)$`,"m"))?.[1]?.trim()||"";return{id:o("id")||t.replace(".md",""),date:o("date"),agentId:o("agent"),source:o("source"),sourceContext:o("context")||void 0,content:n}}writeArticle(e,t,s,r){let n=this.readArticle(e);if(n&&!this.canWrite(n.meta,r))return this.log(`Permission denied: "${r}" cannot write "${e}" (owner: ${n.meta.owner})`),!1;t.type&&!Q(t.type)&&(this.log(`Dropping invalid article type "${t.type}" for "${e}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),t={...t,type:void 0});let o=y(this.baseDir,e);n&&this.saveVersion(e,o),j(pe(o),{recursive:!0});let i=["---",`title: "${t.title}"`];t.type&&i.push(`type: ${t.type}`),t.related?.length&&i.push(`related: [${t.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(t.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${t.owner}`,`access: ${t.access}`),t.sharedWith?.length&&i.push(`shared_with: [${t.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`sources: [${t.sources.map(c=>`"${c}"`).join(", ")}]`),t.graphPath?.length&&i.push(`graph_path: [${t.graphPath.map(c=>`"${c}"`).join(", ")}]`),i.push("---","",s),S(o,i.join(`
7
- `));let a=n?"update":"create";return this.appendLog(a,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!x(t))return;let s=W(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),n=y(this.baseDir,"_versions",e.replace(/\.md$/,""));j(n,{recursive:!0}),S(y(n,`${r}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!x(t))return[];try{return O(t).filter(s=>s.endsWith(".md")).sort().reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(r,n)=>n<19?n===10?"T":n===13||n===16?":":"-":r),path:y(t,s)}))}catch{return[]}}restoreVersion(e,t){let r=this.getVersions(e).find(n=>n.timestamp.startsWith(t));if(!r)return!1;try{let n=W(r.path,"utf-8"),o=y(this.baseDir,e);return this.saveVersion(e,o),S(o,n),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!x(t))return null;let s=W(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),o=l=>r.match(new RegExp(`^${l}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=l=>{let p=r.match(new RegExp(`^${l}:\\s*\\[(.*)\\]$`,"m"));return p?p[1].split(",").map(m=>m.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},a=o("type")||o("kind"),h=new Set(["person","project","place","concept","event","decision","pattern"]).has(a)?a:void 0,b=i("tags").filter((l,p,m)=>l&&m.indexOf(l)===p),d=i("related"),u=i("graph_path");return{meta:{title:o("title"),type:h,related:d.length?d:void 0,tags:b,owner:o("owner"),access:o("access")||"public",sharedWith:i("shared_with"),created:o("created"),lastUpdated:o("last_updated"),sources:i("sources"),graphPath:u.length?u:void 0},content:n,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=$(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);n&&this.canRead(n.meta,e)&&t.push(n)}),t}search(e,t,s=10){let r=e.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let u=$(this.baseDir,d);if(u.startsWith("raw/")||u.startsWith("_"))return;let l=this.readArticle(u);!l||!this.canRead(l.meta,t)||n.push(l)}),n.length===0)return[];let o=n.map(d=>d.content),i=y(this.baseDir,"_bm25_cache.json"),a=L(o,i),c=M(e,a),h=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,u)=>{let l=h.get(u)??0;return d.meta.title.toLowerCase().includes(r)&&(l+=10),d.meta.tags?.some(p=>p.toLowerCase().includes(r))&&(l+=5),{article:d,score:l}}).filter(d=>d.score>0).sort((d,u)=>u.score-d.score).slice(0,s).map(d=>d.article)}findRelevant(e,t,s=3,r,n={graph:.6,bm25:.4}){let o=[];if(this.walkDir(this.baseDir,p=>{if(!p.endsWith(".md"))return;let m=$(this.baseDir,p);if(m.startsWith("raw/")||m.startsWith("_"))return;let f=this.readArticle(m);!f||!this.canRead(f.meta,t)||o.push(f)}),o.length===0)return[];let i=o.map(p=>`${p.meta.title} ${(p.meta.tags||[]).join(" ")} ${p.content}`),a=y(this.baseDir,"_bm25_relevance_cache.json"),c=L(i,a),h=M(e,c),b=h.reduce((p,m)=>Math.max(p,m.score),0)||1,d=new Map(h.map(p=>[p.docIndex,p.score/b])),u=!!(r&&r.length>0);return o.map((p,m)=>{let f=d.get(m)??0,v=0;u&&p.meta.graphPath?.length&&(v=Y(r,p.meta.graphPath));let w=u?n.graph*v+n.bm25*f:f;return{article:p,score:w}}).filter(p=>p.score>0).sort((p,m)=>m.score-p.score).slice(0,s).map(p=>p.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let n of e){let o=`
8
- ## ${n.meta.title} [${(n.meta.tags||[]).slice(0,3).join(", ")}]`,i=n.content.length>600?n.content.slice(0,600)+"...":n.content,a=o+`
9
- `+i;if(r+a.length>t)break;s.push(a),r+=a.length}return s.push(`
10
- [End Wiki Knowledge]`),s.join(`
11
- `)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,o=>{if(!o.endsWith(".md"))return;let i=$(this.baseDir,o);if(i.startsWith("raw/")||i.startsWith("_"))return;let a=this.readArticle(i);if(!a)return;let c=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let b of c){let d=b.replace(/\[\[|\]\]/g,"");t.set(d,(t.get(d)||0)+1)}let h=[a.meta.title.toLowerCase()];a.meta.tags&&h.push(...a.meta.tags.map(b=>b.toLowerCase())),e.push({path:i,title:a.meta.title,type:a.meta.type,related:a.meta.related,tags:a.meta.tags||[],owner:a.meta.owner,access:a.meta.access,sharedWith:a.meta.sharedWith,aliases:h,backlinks:t.get(a.meta.title)||0,sources:a.meta.sources,lastUpdated:a.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};S(y(this.baseDir,"_index.json"),JSON.stringify(s,null,2)),this.writeCatalog(e,s.lastRebuilt);let r=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],n=new Map;for(let o of e){let i=o.access||"public",a=n.get(i)||[];a.push(o),n.set(i,a)}for(let[o,i]of Array.from(n.entries()).sort()){r.push(`## ${o}`,"");for(let a of i.sort((c,h)=>c.title.localeCompare(h.title))){let c=a.type?` [${a.type}]`:"";r.push(`- [${a.title}](${a.path})${c} \u2014 owner: ${a.owner}`)}r.push("")}return S(y(this.baseDir,"WIKI.md"),r.join(`
12
- `)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),s}writeCatalog(e,t){let s=["person","project","place","concept","event","decision","pattern","untyped"],r={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},n=new Map;for(let i of e){let a=i.type||"untyped",c=n.get(a)||[];c.push(i),n.set(a,c)}let o=["# Wiki Content Catalog","",`_Last rebuilt: ${t}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of s){let a=n.get(i);if(!(!a||a.length===0)){o.push(r[i]||`## ${i}`,"");for(let c of a.sort((h,b)=>h.title.localeCompare(b.title))){let h=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",b=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";o.push(`- [${c.title}](${c.path})${h}${b}`)}o.push("")}}S(y(this.baseDir,"_index.md"),o.join(`
13
- `))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,o=>{if(!o.endsWith(".md"))return;let i=$(this.baseDir,o);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let a=this.readArticle(i);if(a){e++;for(let c of a.meta.tags||[])t[c]=(t[c]||0)+1;s[a.meta.access]=(s[a.meta.access]||0)+1,r[a.meta.owner]=(r[a.meta.owner]||0)+1}});let n=x(this.rawDir)?O(this.rawDir).filter(o=>o.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:n,articlesByType:t,articlesByAccess:s,articlesByOwner:r}}appendLog(e,t){let s=y(this.baseDir,"log.md"),n=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
14
-
15
- `;x(s)||S(s,`# Wiki Log
16
-
17
- Chronological record of all wiki operations.
18
-
19
- `),ce(s,n)}getLog(e=20){let t=y(this.baseDir,"log.md");return x(t)?W(t,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-e).map(n=>n.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if(x(e))return;S(e,`# Wiki Schema
20
-
21
- A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
22
- structure emerges from data. The wiki is a compounding artifact.
23
-
24
- ## Structure
25
-
26
- \`\`\`
27
- wiki/
28
- _schema.md # This file
29
- worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
30
- raw/entries/ # Immutable raw sources (conversations, imports, anything)
31
- [LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
32
- \`\`\`
33
-
34
- The LLM decides how to organize articles. You describe YOUR world in worldview.md.
35
-
36
- ## Article Format
37
-
38
- \`\`\`yaml
39
- ---
40
- title: "Staging Deployment Process"
41
- tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
42
- owner: devops-agent
43
- access: public
44
- created: 2026-04-06
45
- last_updated: 2026-04-06
46
- sources: ["entry-id-1", "entry-id-2"]
47
- ---
48
-
49
- Article content with [[wikilinks]] and section tags.
50
-
51
- ## Deploy Steps
52
- <!-- tags: process, runbook, staging -->
53
- Content specific to this section...
54
- \`\`\`
55
-
56
- ## Tags
57
-
58
- Tags are the primary context-narrowing mechanism. The more tags, the better.
59
-
60
- Tag aggressively:
61
- - **Who**: people, agents, teams involved
62
- - **What**: project, client, topic, technology
63
- - **When**: dates, periods, milestones
64
- - **Where**: server, environment, channel
65
- - **How**: process, decision, pattern
66
- - **Your terms**: whatever vocabulary makes sense in YOUR world
67
-
68
- Section tags (\`<!-- tags: ... -->\`) let different parts of an article
69
- match different queries. A deploy article might have sections tagged
70
- "runbook" and "incident" separately.
71
-
72
- ## Operations
73
-
74
- ### Absorb
75
- Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
76
- Also identify GAPS: "We mention X but have no article for it."
77
-
78
- ### Query
79
- Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
80
- If agent is working on a specific project, only send content tagged for that project.
81
-
82
- ### Lint
83
- Check for: orphan articles, broken [[wikilinks]], untagged articles,
84
- articles over 100 lines that should split, mentioned-but-missing topics.
85
-
86
- ## Worldview
87
-
88
- Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
89
- mental model. The LLM reads it during absorb to understand where things go.
90
-
91
- Example worldview.md:
92
- \`\`\`
93
- I'm the founder of Acme Corp.
94
- We build software products.
95
- Our agents: Marketing Bot, DevOps Bot, Coordinator.
96
- Clients: ClientA (enterprise), ClientB (startup).
97
- Infrastructure: local dev machine, cloud server.
98
- We use GitLab for version control.
99
- \`\`\`
100
- `),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=$(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=W(t,"utf-8"),n=this.extractWikilinks(r);for(let o of n)e[o]||(e[o]=[]),e[o].push(s)}),S(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!x(t))return[];try{return JSON.parse(W(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(o=>o.toLowerCase()),n=[];return this.walkDir(this.baseDir,o=>{if(!o.endsWith(".md"))return;let i=$(this.baseDir,o);if(i.startsWith("raw/")||i.startsWith("_"))return;let a=this.readArticle(i);if(!a||t&&!this.canRead(a.meta,t))return;let c=(a.meta.tags||[]).map(u=>u.toLowerCase()),h=(a.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(l=>l.trim().toLowerCase())),b=[...c,...h],d=r.filter(u=>b.includes(u)).length;d>0&&n.push({article:a,score:d})}),n.sort((o,i)=>i.score-o.score).slice(0,s).map(o=>o.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=$(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);if(r?.meta.tags)for(let n of r.meta.tags)e.set(n,(e.get(n)||0)+1)}),e}getWorldview(){let e=y(this.baseDir,"worldview.md");return x(e)?W(e,"utf-8"):null}setWorldview(e){S(y(this.baseDir,"worldview.md"),e),this.appendLog("worldview","Updated worldview")}lint(){let e=[],t=new Set,s=new Map,r=new Map;this.walkDir(this.baseDir,o=>{if(!o.endsWith(".md"))return;let i=$(this.baseDir,o);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let a=this.readArticle(i);if(!a)return;t.add(a.meta.title),r.set(a.meta.title,i);let c=this.extractWikilinks(a.content);s.set(i,c);let h=a.content.split(`
101
- `).length;h>100&&e.push({type:"bloated",article:i,message:`${h} lines \u2014 consider splitting`}),a.meta.sources?.length||e.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),h<10&&a.content.trim().length<100&&e.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[o,i]of s)for(let a of i)t.has(a)||e.push({type:"broken-link",article:o,message:`[[${a}]] \u2014 target article not found`});let n=this.buildBacklinks();for(let[o,i]of r)(!n[o]||n[o].length===0)&&e.push({type:"orphan",article:i,message:`No other articles link to "${o}"`});return this.appendLog("lint",`Found ${e.length} issues`),e}getUnabsorbedEntries(){let e=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=$(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);if(n?.meta.sources)for(let o of n.meta.sources)e.add(o)}),this.listEntries().filter(s=>!e.has(s.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let s=t.map(r=>`[${r.date} ${r.agentId} via ${r.source}] ${r.content.slice(0,200)}`).join(`
102
-
103
- `);return`/wiki absorb
104
-
105
- There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
106
-
107
- ${s}`}walkDir(e,t){if(x(e))for(let s of O(e)){let r=de(e,s);le(r).isDirectory()?this.walkDir(r,t):t(r)}}};import{resolve as K}from"path";import{existsSync as he,readdirSync as ge,mkdirSync as ue}from"fs";var se=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=K(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki-hub]"),s="graph"){this.baseDir=e,this.agentsDir=K(e,"agents"),this.mode=s,this.log=t,ue(this.agentsDir,{recursive:!0}),this.sharedStore=new R(e,t)}getMode(){return this.mode}getAgentWiki(e){let t=`${e}:${this.mode}`;if(this.agentStores.has(t))return this.agentStores.get(t);let s=K(this.agentsDir,e,this.mode),r=new R(s,this.log);return this.agentStores.set(t,r),r}getSharedStore(){return this.sharedStore}listAgents(){let e=new Set,t=this.sharedStore.listEntries();for(let s of t)e.add(s.agentId);if(he(this.agentsDir))for(let s of ge(this.agentsDir))!s.startsWith("_")&&!s.startsWith(".")&&e.add(s);return[...e].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){let t=this.getAgentWiki(e),s=this.getAgentEntries(e),r=new Set,n=t.rebuildIndex();for(let o of n.articles)if(o.sources)for(let i of o.sources)r.add(i);return s.filter(o=>!r.has(o.id))}summary(){return this.listAgents().map(t=>{let s=this.getAgentEntries(t),n=this.getAgentWiki(t).rebuildIndex(),o=this.getUnabsorbedEntries(t);return{agentId:t,totalEntries:s.length,totalArticles:n.articles.length,unabsorbed:o.length,articles:n.articles}})}};export{A as a,U as b,H as c,V as d,R as e,se as f};
108
- //# sourceMappingURL=chunk-BFXONUUN.js.map