agentix-cli 0.69.3 → 0.69.4

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 (95) hide show
  1. package/dist/agent-IDAWXA3K.js +2 -0
  2. package/dist/{board-dashboard-U6IZQA4W.js → board-dashboard-MAP6A2N7.js} +2 -2
  3. package/dist/{chunk-NO2HOK4B.js → chunk-23A5K5UW.js} +3 -3
  4. package/dist/chunk-23A5K5UW.js.map +1 -0
  5. package/dist/{chunk-RN5NOIBH.js → chunk-2UYV24UD.js} +2 -2
  6. package/dist/{chunk-EQTSOK7L.js → chunk-535MLOSB.js} +15 -15
  7. package/dist/chunk-535MLOSB.js.map +1 -0
  8. package/dist/{chunk-SZJMS7K4.js → chunk-5MUJZODV.js} +19 -19
  9. package/dist/chunk-5MUJZODV.js.map +1 -0
  10. package/dist/{chunk-SXKOI2IF.js → chunk-5ONI54E6.js} +5 -5
  11. package/dist/{chunk-E7OACKES.js → chunk-BBIWAJRX.js} +2 -2
  12. package/dist/{chunk-Y57CULGE.js → chunk-C245D4BZ.js} +2 -2
  13. package/dist/{chunk-DW5EHX3M.js → chunk-CKBAVCGU.js} +2 -2
  14. package/dist/{chunk-VVMOTM3V.js → chunk-DQQ3BCJW.js} +2 -2
  15. package/dist/{chunk-B7S66EK7.js → chunk-IU6L4V3A.js} +14 -14
  16. package/dist/chunk-IU6L4V3A.js.map +1 -0
  17. package/dist/{chunk-IULWZA3J.js → chunk-J7HA7ZTU.js} +6 -6
  18. package/dist/chunk-J7HA7ZTU.js.map +1 -0
  19. package/dist/chunk-JHCI6XCJ.js +5 -0
  20. package/dist/chunk-JHCI6XCJ.js.map +1 -0
  21. package/dist/chunk-K63IOY6A.js +152 -0
  22. package/dist/chunk-K63IOY6A.js.map +1 -0
  23. package/dist/{chunk-KPPGT5FJ.js → chunk-M6GPRMCQ.js} +2 -2
  24. package/dist/{chunk-USMCN2X3.js → chunk-OHRTBD7U.js} +12 -12
  25. package/dist/{chunk-FGFDPYL4.js → chunk-P2RYUODK.js} +2 -2
  26. package/dist/chunk-P2RYUODK.js.map +1 -0
  27. package/dist/{chunk-JYBSYW7T.js → chunk-V2TLFYKH.js} +2 -2
  28. package/dist/{chunk-3FWJXI7H.js → chunk-YBF2QVZ7.js} +2 -2
  29. package/dist/cli.js +1 -1
  30. package/dist/{compaction-H5U32UU6.js → compaction-MECSN36J.js} +4 -4
  31. package/dist/compaction-MECSN36J.js.map +1 -0
  32. package/dist/{context-planner-LJT5IKH6.js → context-planner-JU7CNXCB.js} +3 -3
  33. package/dist/context-planner-JU7CNXCB.js.map +1 -0
  34. package/dist/heal-CMQL5SG4.js +2 -0
  35. package/dist/index.d.ts +21 -2
  36. package/dist/index.js +2 -2
  37. package/dist/loader-YFVSSYSL.js +2 -0
  38. package/dist/memory-extract-YCNCARZ2.js +2 -0
  39. package/dist/program-T275Y2V6.js +2 -0
  40. package/dist/{promote-7SU6IJDC.js → promote-VZAUTV6E.js} +2 -2
  41. package/dist/{providers-NRPX2FHP.js → providers-ES5KVLI4.js} +2 -2
  42. package/dist/query-7QQZPMXM.js +2 -0
  43. package/dist/{registry-K76DGYLW.js → registry-WQ65MQEY.js} +2 -2
  44. package/dist/{request-planner-YIG5RUN2.js → request-planner-NMOAOZIM.js} +2 -2
  45. package/dist/{review-candidates-2JFQ2M53.js → review-candidates-FLY6HZEN.js} +2 -2
  46. package/dist/{routing-3CIQQZJ4.js → routing-SMIZ77CT.js} +2 -2
  47. package/dist/{seat-HMF3G6BR.js → seat-F3S2HG5G.js} +2 -2
  48. package/dist/{select-2P73MN6O.js → select-5GC7CTPQ.js} +2 -2
  49. package/dist/wiki-J4MMCONT.js +2 -0
  50. package/package.json +1 -1
  51. package/dist/agent-OJQKD5AI.js +0 -2
  52. package/dist/chunk-B7S66EK7.js.map +0 -1
  53. package/dist/chunk-EQTSOK7L.js.map +0 -1
  54. package/dist/chunk-FGFDPYL4.js.map +0 -1
  55. package/dist/chunk-IULWZA3J.js.map +0 -1
  56. package/dist/chunk-JQXG2OO6.js +0 -152
  57. package/dist/chunk-JQXG2OO6.js.map +0 -1
  58. package/dist/chunk-NO2HOK4B.js.map +0 -1
  59. package/dist/chunk-SZJMS7K4.js.map +0 -1
  60. package/dist/chunk-VDMYBPYB.js +0 -5
  61. package/dist/chunk-VDMYBPYB.js.map +0 -1
  62. package/dist/compaction-H5U32UU6.js.map +0 -1
  63. package/dist/context-planner-LJT5IKH6.js.map +0 -1
  64. package/dist/heal-HVYQD3EZ.js +0 -2
  65. package/dist/loader-EVHZ2R73.js +0 -2
  66. package/dist/memory-extract-F76BE6KA.js +0 -2
  67. package/dist/program-O67GMIWX.js +0 -2
  68. package/dist/query-CY7F5ZFR.js +0 -2
  69. package/dist/wiki-VXTUHSRH.js +0 -2
  70. /package/dist/{agent-OJQKD5AI.js.map → agent-IDAWXA3K.js.map} +0 -0
  71. /package/dist/{board-dashboard-U6IZQA4W.js.map → board-dashboard-MAP6A2N7.js.map} +0 -0
  72. /package/dist/{chunk-RN5NOIBH.js.map → chunk-2UYV24UD.js.map} +0 -0
  73. /package/dist/{chunk-SXKOI2IF.js.map → chunk-5ONI54E6.js.map} +0 -0
  74. /package/dist/{chunk-E7OACKES.js.map → chunk-BBIWAJRX.js.map} +0 -0
  75. /package/dist/{chunk-Y57CULGE.js.map → chunk-C245D4BZ.js.map} +0 -0
  76. /package/dist/{chunk-DW5EHX3M.js.map → chunk-CKBAVCGU.js.map} +0 -0
  77. /package/dist/{chunk-VVMOTM3V.js.map → chunk-DQQ3BCJW.js.map} +0 -0
  78. /package/dist/{chunk-KPPGT5FJ.js.map → chunk-M6GPRMCQ.js.map} +0 -0
  79. /package/dist/{chunk-USMCN2X3.js.map → chunk-OHRTBD7U.js.map} +0 -0
  80. /package/dist/{chunk-JYBSYW7T.js.map → chunk-V2TLFYKH.js.map} +0 -0
  81. /package/dist/{chunk-3FWJXI7H.js.map → chunk-YBF2QVZ7.js.map} +0 -0
  82. /package/dist/{heal-HVYQD3EZ.js.map → heal-CMQL5SG4.js.map} +0 -0
  83. /package/dist/{loader-EVHZ2R73.js.map → loader-YFVSSYSL.js.map} +0 -0
  84. /package/dist/{memory-extract-F76BE6KA.js.map → memory-extract-YCNCARZ2.js.map} +0 -0
  85. /package/dist/{program-O67GMIWX.js.map → program-T275Y2V6.js.map} +0 -0
  86. /package/dist/{promote-7SU6IJDC.js.map → promote-VZAUTV6E.js.map} +0 -0
  87. /package/dist/{providers-NRPX2FHP.js.map → providers-ES5KVLI4.js.map} +0 -0
  88. /package/dist/{query-CY7F5ZFR.js.map → query-7QQZPMXM.js.map} +0 -0
  89. /package/dist/{registry-K76DGYLW.js.map → registry-WQ65MQEY.js.map} +0 -0
  90. /package/dist/{request-planner-YIG5RUN2.js.map → request-planner-NMOAOZIM.js.map} +0 -0
  91. /package/dist/{review-candidates-2JFQ2M53.js.map → review-candidates-FLY6HZEN.js.map} +0 -0
  92. /package/dist/{routing-3CIQQZJ4.js.map → routing-SMIZ77CT.js.map} +0 -0
  93. /package/dist/{seat-HMF3G6BR.js.map → seat-F3S2HG5G.js.map} +0 -0
  94. /package/dist/{select-2P73MN6O.js.map → select-5GC7CTPQ.js.map} +0 -0
  95. /package/dist/{wiki-VXTUHSRH.js.map → wiki-J4MMCONT.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{A as a,B as b,C as c}from"./chunk-J7HA7ZTU.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
2
+ //# sourceMappingURL=agent-IDAWXA3K.js.map
@@ -1,4 +1,4 @@
1
- import{a as fn}from"./chunk-62EJKQFX.js";import{a as ln}from"./chunk-2NYP4OQU.js";import{a as ie,b as sn}from"./chunk-JWDJMFU6.js";import{a as A,b as hn,c as gn,d as xn,e as vn,h as bn,i as Me,j as yn,k as wn,l as _n,m as En,n as Sn}from"./chunk-KPPGT5FJ.js";import{a as kn}from"./chunk-Z3IP66SL.js";import{a as cn,b as V,c as dn,d as L,e as j,j as nt,k as rt,l as ae,m as q,n as ot,o as pn,p as un,q as mn}from"./chunk-C4CDVE2E.js";import{A as Ve,B as Ye,Ba as Ie,C as qa,Ca as Qe,D as Ua,Da as Ze,Ea as et,Fa as tt,Ga as tn,Ha as an,Ia as nn,Ja as at,K as B,L as Wa,La as rn,M as Ga,Oa as on,X as Ja,Y as Va,Z as Ya,a as ja,c as Ke,d as Lt,e as Oa,i as Je,k as Na,m as te,n as be,o as Ba,p as $t,sa as Qa,ua as Rt,za as en}from"./chunk-DW5EHX3M.js";import{p as Da,s as Ha}from"./chunk-BYJ3A55Y.js";import{a as Za}from"./chunk-NMFXY3QU.js";import{g as Ra,h as Pa}from"./chunk-3FWJXI7H.js";import{a as Xa,b as Ka}from"./chunk-LQRBGQIR.js";import"./chunk-VVMOTM3V.js";import{b as za,c as Fa}from"./chunk-2D3RYIDU.js";import{a as Aa,f as Ca,g as It,h as Mt,l as Ia,m as Ma,n as La,t as Ge,u as Xe,v as se,w as $a}from"./chunk-B7S66EK7.js";import{a as Ce}from"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-FSYA4GNU.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-AFRHKA7B.js";import"./chunk-OPUPVGYP.js";import"./chunk-YL223TEU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-QD6IICK7.js";import"./chunk-RN5NOIBH.js";import{b as Ta}from"./chunk-EQTSOK7L.js";import"./chunk-4DRNEOOW.js";import"./chunk-64P4QHSZ.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-E7OACKES.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-SZJMS7K4.js";import"./chunk-7I7IEX4S.js";import{a as Ea,b as Sa,c as Cs,w as ee,z as Ct}from"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function Pt(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function Tn(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:Pt(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var ne={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},ye=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",st=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+ye(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function An(t={}){return L({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
1
+ import{a as fn}from"./chunk-62EJKQFX.js";import{a as ln}from"./chunk-2NYP4OQU.js";import{a as ie,b as sn}from"./chunk-JWDJMFU6.js";import{a as A,b as hn,c as gn,d as xn,e as vn,h as bn,i as Me,j as yn,k as wn,l as _n,m as En,n as Sn}from"./chunk-M6GPRMCQ.js";import{a as kn}from"./chunk-Z3IP66SL.js";import{a as cn,b as V,c as dn,d as L,e as j,j as nt,k as rt,l as ae,m as q,n as ot,o as pn,p as un,q as mn}from"./chunk-C4CDVE2E.js";import{A as Ve,B as Ye,Ba as Ie,C as qa,Ca as Qe,D as Ua,Da as Ze,Ea as et,Fa as tt,Ga as tn,Ha as an,Ia as nn,Ja as at,K as B,L as Wa,La as rn,M as Ga,Oa as on,X as Ja,Y as Va,Z as Ya,a as ja,c as Ke,d as Lt,e as Oa,i as Je,k as Na,m as te,n as be,o as Ba,p as $t,sa as Qa,ua as Rt,za as en}from"./chunk-CKBAVCGU.js";import{p as Da,s as Ha}from"./chunk-BYJ3A55Y.js";import{a as Za}from"./chunk-NMFXY3QU.js";import{g as Ra,h as Pa}from"./chunk-YBF2QVZ7.js";import{a as Xa,b as Ka}from"./chunk-LQRBGQIR.js";import"./chunk-DQQ3BCJW.js";import{b as za,c as Fa}from"./chunk-2D3RYIDU.js";import{a as Aa,f as Ca,g as It,h as Mt,l as Ia,m as Ma,n as La,t as Ge,u as Xe,v as se,w as $a}from"./chunk-IU6L4V3A.js";import{a as Ce}from"./chunk-N6EWZGIX.js";import"./chunk-WP6KLXTP.js";import"./chunk-DP7RTNDM.js";import"./chunk-FSYA4GNU.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-AFRHKA7B.js";import"./chunk-OPUPVGYP.js";import"./chunk-YL223TEU.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-QD6IICK7.js";import"./chunk-2UYV24UD.js";import{b as Ta}from"./chunk-535MLOSB.js";import"./chunk-4DRNEOOW.js";import"./chunk-64P4QHSZ.js";import"./chunk-TFVUOC2C.js";import"./chunk-2GIDVZ4H.js";import"./chunk-BBIWAJRX.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import{a as Ea,b as Sa,c as Cs,w as ee,z as Ct}from"./chunk-DTX4I5LQ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function Pt(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function Tn(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:Pt(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var ne={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},ye=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",st=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+ye(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function An(t={}){return L({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
2
2
 
3
3
  <div class="bf-head">
4
4
  <div>
@@ -17907,4 +17907,4 @@ data: ${h.replace(/\n/g," ")}
17907
17907
  `)}catch{}}};s.stdout?.on("data",l),s.stderr?.on("data",l);let c=setInterval(()=>{try{e.write(`: hb
17908
17908
 
17909
17909
  `)}catch{}},15e3),p=()=>{clearInterval(c);try{s.kill()}catch{}try{e.end()}catch{}};t.on("close",p),s.on("exit",p),s.on("error",p)}async function vs(t,e,a,n){let r=a.url+n,o=(t.method||"GET").toUpperCase(),i=o!=="GET"&&o!=="HEAD"?await new Promise((u,f)=>{let h=[];t.on("data",w=>h.push(w)),t.on("end",()=>u(Buffer.concat(h))),t.on("error",f)}):void 0,l={},c=t.headers["content-type"];c&&(l["Content-Type"]=Array.isArray(c)?c[0]:c);let p=t.headers["x-requested-with"];p&&(l["X-Requested-With"]=Array.isArray(p)?p[0]:p),a.token&&(l.Authorization=`Bearer ${a.token}`),l["X-Agentx-Peer"]="primary";try{let u=await fetch(r,{method:o,headers:l,body:i&&i.length>0?i:void 0}),f=Buffer.from(await u.arrayBuffer());e.writeHead(u.status,{"Content-Type":u.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),e.end(f)}catch(u){y(e,502,{error:`proxy to peer failed: ${u?.message||u}`,target:r})}}function We(t,e){let a=t.replace(/\/+$/,""),n=(e.dashboard?.daemons||[]).find(r=>r.url.replace(/\/+$/,"")===a);return n?{url:Es(n),token:n.dashboardToken||n.token}:null}export{Ep as applyAttachSessions,xp as fetchDaemonAgents,pp as handleBoardRequest,nx as resetLiveCaches,ve as resolveNodeTargets,ax as startBoardDashboard,_p as withLastGood};
17910
- //# sourceMappingURL=board-dashboard-U6IZQA4W.js.map
17910
+ //# sourceMappingURL=board-dashboard-MAP6A2N7.js.map
@@ -1,4 +1,4 @@
1
- import{a as u,b as f}from"./chunk-QD6IICK7.js";var d=new Set(["cron","a2a","workflow","selftest"]),g=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function l(e){if(e.responseLength<=50)return{capture:!1,reason:"response too short"};let r=(e.channel??"").toLowerCase().split("@")[0];if(d.has(r))return{capture:!1,reason:`machine channel: ${r}`};let n=e.content.slice(0,400);for(let[o,c]of g)if(o.test(n))return{capture:!1,reason:c};return{capture:!0}}var y="claude-haiku-4-20250514",w=`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.
1
+ import{a as u,b as f}from"./chunk-QD6IICK7.js";var d=new Set(["cron","a2a","workflow","selftest"]),g=[[/^User:\s*You are\s/i,"role brief"],[/^User:\s*(Run|Execute)\s/i,"run instruction"],[/^User:\s*\[MISSED RUN/i,"missed cron run"],[/^User:\s*(\[[^\]]{0,40}\]:?\s*)?\[Recent group conversation\]/i,"group chat dump"]];function l(e){if(e.responseLength<=50)return{capture:!1,reason:"response too short"};let r=(e.channel??"").toLowerCase().split("@")[0];if(d.has(r))return{capture:!1,reason:`machine channel: ${r}`};let n=e.content.slice(0,400);for(let[o,c]of g)if(o.test(n))return{capture:!1,reason:c};return{capture:!0}}var y="claude-haiku-4-5-20251001",w=`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.
2
2
 
3
3
  Extract ONLY facts that would help the agent in FUTURE, DIFFERENT conversations:
4
4
  - User preferences and instructions ("never do X", "always use Y")
@@ -17,7 +17,7 @@ SKIP:
17
17
  For each fact, output a JSON array:
18
18
  [{"category":"fact|preference|commitment|task-state","content":"concise fact, 1-2 sentences","keywords":["keyword1","keyword2"]}]
19
19
 
20
- If nothing worth remembering, output: []`;async function I(e,s,r,n,o){if(s.length<20&&r.length<50||!l({channel:n.channel,content:`User: ${s}`,responseLength:r.length}).capture)return;let{createProvider:h}=await import("./providers-NRPX2FHP.js"),i=(await h("claude").generate([{role:"system",content:w},{role:"user",content:`${n.sender} (via ${n.channel}): ${s}
20
+ If nothing worth remembering, output: []`;async function I(e,s,r,n,o){if(s.length<20&&r.length<50||!l({channel:n.channel,content:`User: ${s}`,responseLength:r.length}).capture)return;let{createProvider:h}=await import("./providers-ES5KVLI4.js"),i=(await h("claude").generate([{role:"system",content:w},{role:"user",content:`${n.sender} (via ${n.channel}): ${s}
21
21
 
22
22
  Agent: ${r}`}],{model:y,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!i)return;let a=JSON.parse(i[0]);if(!Array.isArray(a)||a.length===0)return;let m=new Date().toISOString().slice(0,10),p=u(n.channel);for(let t of a)typeof t?.content=="string"&&(t.category==="secret"||f(t.content)||o.hasSimilar(e,t.content)||o.addMemory(e,{agentId:e,category:t.category,content:t.content,keywords:t.keywords||[],source:{...n,date:m,trust:p},expiresAt:t.category==="task-state"?new Date(Date.now()+7*24*60*60*1e3).toISOString():void 0}));Math.random()<.02&&o.prune(e)}export{l as a,I as b};
23
- //# sourceMappingURL=chunk-NO2HOK4B.js.map
23
+ //# sourceMappingURL=chunk-23A5K5UW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/capture-filter.ts","../src/agents/memory-extract.ts"],"sourcesContent":["// What deserves to become a raw wiki entry.\n//\n// Until now the only gate was `response.content.length > 50`. Every agent\n// task was captured, with the task's own message as the \"User:\" half — so\n// a cron's prompt became an entry, a role brief became an entry, and a\n// \"[MISSED RUN]\" notice became an entry.\n//\n// Measured over the 10,703 entries that produced: 30% arrived on a\n// machine-origin channel, 33% are prompt-shaped, and 47.5% are one or\n// both. That is the bulk of a corpus that has yielded 257 articles and is\n// read about three times a quarter.\n//\n// These rules are deterministic and free. They are deliberately\n// conservative — each one describes a shape that cannot contain knowledge\n// about the world, rather than guessing at value. Judging whether the\n// REMAINDER is worth keeping is a different question, and belongs to the\n// entry-triage seat, which costs money and can be wrong.\n\n/** Channels where both sides of the exchange are machines. A cron's\n * prompt is configuration, and its reply is a status report. */\nconst MACHINE_CHANNELS = new Set([\"cron\", \"a2a\", \"workflow\", \"selftest\"])\n\n/** Shapes that are an instruction to an agent, not a record of anything.\n * Anchored at the start of the captured content, which always begins\n * \"User: \" followed by the task message. */\nconst PROMPT_SHAPES: Array<[RegExp, string]> = [\n [/^User:\\s*You are\\s/i, \"role brief\"],\n [/^User:\\s*(Run|Execute)\\s/i, \"run instruction\"],\n [/^User:\\s*\\[MISSED RUN/i, \"missed cron run\"],\n // The bracketed prefix varies: some arrive as \"[Group, 09:43]: [Recent\n // group conversation]\". Anchoring on the bare marker missed 367 entries\n // in the first purge, so allow one leading bracketed segment.\n [/^User:\\s*(\\[[^\\]]{0,40}\\]:?\\s*)?\\[Recent group conversation\\]/i, \"group chat dump\"],\n]\n\nexport interface CaptureDecision {\n capture: boolean\n /** Why it was rejected, for logging and for counting what the filter\n * actually removes once it is live. */\n reason?: string\n}\n\nexport function shouldCaptureEntry(input: {\n channel: string | undefined\n content: string\n responseLength: number\n}): CaptureDecision {\n if (input.responseLength <= 50) return { capture: false, reason: \"response too short\" }\n\n const channel = (input.channel ?? \"\").toLowerCase()\n // Channels carry a node suffix: \"telegram@peer-server\".\n const base = channel.split(\"@\")[0]\n if (MACHINE_CHANNELS.has(base)) return { capture: false, reason: `machine channel: ${base}` }\n\n const head = input.content.slice(0, 400)\n for (const [shape, reason] of PROMPT_SHAPES) {\n if (shape.test(head)) return { capture: false, reason }\n }\n\n return { capture: true }\n}\n","import type { MemoryStore } from \"./memory-store\"\nimport { shouldCaptureEntry } from \"@/wiki/capture-filter\"\nimport { containsSecret, trustForChannel } from \"./memory-trust\"\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-5-20251001\"\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- User preferences and instructions (\"never do X\", \"always use Y\")\n- Commitments the agent made (\"I will deploy by Friday\")\n- Relationships (\"Alex is the admin\", \"Marketing handles content\")\n- Task state (\"GitLab tokens need deploying to peer-server\")\n- Important facts about infrastructure, config, or processes\n\nSKIP:\n- Credentials of any kind: passwords, tokens, API keys, private keys, connection strings. Never repeat one, not even partly. At most note that a credential exists and where it is kept, without its value.\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|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 // Same gate as wiki capture: machine channels (cron, a2a, workflow) and\n // prompt-shaped messages hold configuration, not facts about the world.\n const gate = shouldCaptureEntry({\n channel: source.channel,\n content: `User: ${userMessage}`,\n responseLength: agentResponse.length,\n })\n if (!gate.capture) 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 const trust = trustForChannel(source.channel)\n\n for (const fact of facts) {\n if (typeof fact?.content !== \"string\") continue\n // The prompt says never to extract credentials; this holds when the\n // model does it anyway. addMemory refuses them too.\n if (fact.category === \"secret\" || containsSecret(fact.content)) continue\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, trust },\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":"+CAoBA,IAAMA,EAAmB,IAAI,IAAI,CAAC,OAAQ,MAAO,WAAY,UAAU,CAAC,EAKlEC,EAAyC,CAC7C,CAAC,sBAAuB,YAAY,EACpC,CAAC,4BAA6B,iBAAiB,EAC/C,CAAC,yBAA0B,iBAAiB,EAI5C,CAAC,iEAAkE,iBAAiB,CACtF,EASO,SAASC,EAAmBC,EAIf,CAClB,GAAIA,EAAM,gBAAkB,GAAI,MAAO,CAAE,QAAS,GAAO,OAAQ,oBAAqB,EAItF,IAAMC,GAFWD,EAAM,SAAW,IAAI,YAAY,EAE7B,MAAM,GAAG,EAAE,CAAC,EACjC,GAAIH,EAAiB,IAAII,CAAI,EAAG,MAAO,CAAE,QAAS,GAAO,OAAQ,oBAAoBA,GAAO,EAE5F,IAAMC,EAAOF,EAAM,QAAQ,MAAM,EAAG,GAAG,EACvC,OAAW,CAACG,EAAOC,CAAM,IAAKN,EAC5B,GAAIK,EAAM,KAAKD,CAAI,EAAG,MAAO,CAAE,QAAS,GAAO,OAAAE,CAAO,EAGxD,MAAO,CAAE,QAAS,EAAK,CACzB,CCpDA,IAAMC,EAAmB,4BAEnBC,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,CAWf,GATIH,EAAY,OAAS,IAAMC,EAAc,OAAS,IASlD,CALSG,EAAmB,CAC9B,QAASF,EAAO,QAChB,QAAS,SAASF,IAClB,eAAgBC,EAAc,MAChC,CAAC,EACS,QAAS,OAEnB,GAAM,CAAE,eAAAI,CAAe,EAAI,KAAM,QAAO,yBAAmB,EAgBrDC,GAbS,MAFED,EAAe,QAAQ,EAEV,SAC5B,CACE,CAAE,KAAM,SAAU,QAASR,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,CAACU,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,EAC3CC,EAAQC,EAAgBR,EAAO,OAAO,EAE5C,QAAWS,KAAQJ,EACb,OAAOI,GAAM,SAAY,WAGzBA,EAAK,WAAa,UAAYC,EAAeD,EAAK,OAAO,GAEzDR,EAAM,WAAWJ,EAASY,EAAK,OAAO,GAE1CR,EAAM,UAAUJ,EAAS,CACvB,QAAAA,EACA,SAAUY,EAAK,SACf,QAASA,EAAK,QACd,SAAUA,EAAK,UAAY,CAAC,EAC5B,OAAQ,CAAE,GAAGT,EAAQ,KAAAM,EAAM,MAAAC,CAAM,EACjC,UAAWE,EAAK,WAAa,aACzB,IAAI,KAAK,KAAK,IAAI,EAAI,EAAI,GAAK,GAAK,GAAK,GAAI,EAAE,YAAY,EAC3D,MACN,CAAC,GAIC,KAAK,OAAO,EAAI,KAClBR,EAAM,MAAMJ,CAAO,CAEvB","names":["MACHINE_CHANNELS","PROMPT_SHAPES","shouldCaptureEntry","input","base","head","shape","reason","EXTRACTION_MODEL","EXTRACTION_PROMPT","extractMemories","agentId","userMessage","agentResponse","source","store","shouldCaptureEntry","createProvider","jsonMatch","facts","date","trust","trustForChannel","fact","containsSecret"]}
@@ -1,2 +1,2 @@
1
- import{e as o}from"./chunk-EQTSOK7L.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
- //# sourceMappingURL=chunk-RN5NOIBH.js.map
1
+ import{e as o}from"./chunk-535MLOSB.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
+ //# sourceMappingURL=chunk-2UYV24UD.js.map
@@ -1,23 +1,23 @@
1
- import{a as M,b as R,c as re,d as L,e as _}from"./chunk-4DRNEOOW.js";import{b as X}from"./chunk-64P4QHSZ.js";import{a as Q,b as Z,c as ee,d as te,e as se}from"./chunk-TFVUOC2C.js";import{v as Y,w as he}from"./chunk-E7OACKES.js";import{a as V,b as pe}from"./chunk-FX3D7YON.js";import{c as O,d as T}from"./chunk-QOYAX2FT.js";import{o as K,p as de}from"./chunk-SZJMS7K4.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)."}},G=[{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 F,appendFileSync as ue,existsSync as I,mkdirSync as B,renameSync as ge,statSync as ie}from"fs";import{resolve as P,dirname as oe}from"path";import{createHash as fe}from"crypto";var J=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),B(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(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=M.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{F(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(a){this.log(`could not back up old schema: ${a?.message??a}`)}this.saveSchema(A);let n=this.nodesPath();if(I(n)){let a=n.replace(/\.json$/,".v1.bak.json");try{F(a,D(n,"utf-8")),this.log(`archived v1 nodes.json -> ${a}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=ae();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=M.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);ne(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!I(e)){let t=ae();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let s=L.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=L.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:s,size:r}=ie(e),n=this.parsed.get(e);if(n&&n.mtimeMs===s&&n.size===r)return n.data;let a=t(D(e,"utf-8"));return this.parsed.set(e,{mtimeMs:s,size:r,data:a}),a}writeParsed(e,t){this.parsed.delete(e),ne(e,t);let{mtimeMs:s,size:r}=ie(e);this.parsed.set(e,{mtimeMs:s,size:r,data:t})}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 o=e.axes[i.name];if(o!=null){if(i.type==="enum"&&i.values&&!i.values.includes(o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===o);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let a=t.levels.findIndex(i=>i.id===e.level);if(a===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 o=t.levels.findIndex(c=>c.id===i.level);if(o<0||o>=a)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=[],a=[],i=new Date().toISOString();for(let o=0;o<e.length;o++){let c=e[o],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){a.push(c);continue}let p=0;for(let m=o-1;m>=0;m--){let b=e[m],W=l.find(k=>k.id===b)||n.find(k=>k.id===b);if(W){p=s.levels.findIndex(k=>k.id===W.level)+1;break}}let u=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let b=s.levels[m];if(b.axes.filter(k=>!k.optional).filter(k=>!(k.name in u)).length===0){d=b.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=o-1;m>=0;m--){let b=e[m],W=l.find(C=>C.id===b)||n.find(C=>C.id===b);if(!W)continue;let k=s.levels.findIndex(C=>C.id===W.level);if(k>=0&&k<f){h=b;break}}let g={id:c,level:d,parentId:h,axes:u,createdAt:i,createdBy:r};this.addNode(g),n.push(g)}return{added:n,skipped:a}}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=R.safeParse(e);if(!t.success){let n=t.error.issues.map(a=>`${a.path.join(".")}: ${a.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)||B(oe(r),{recursive:!0}),ue(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}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 a=R.safeParse(JSON.parse(n));if(!a.success)continue;r.set(a.data.msgHash,a.data)}catch{}return Array.from(r.values()).sort((n,a)=>n.ts<a.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(a=>a.msgHash===e);if(!r)return null;let n={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let a=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;n.preview=((r.preview||"")+a).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 a=r.length-1;a>=0&&n.length<e;a--)try{let i=R.safeParse(JSON.parse(r[a]));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 fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return I(e)?this.readParsed(e,t=>{let s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let s=re.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!s.success)throw new Error(`Refusing to save invalid index entry: ${s.error.issues.map(n=>n.message).join("; ")}`);let r=this.index();this.writeParsed(this.indexPath(),{...r,entries:{...r.entries,[e]:s.data}})}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 a={...n,axes:t};return this.validateNode(a,s,r.nodes.map(i=>i.id===e?a:i)),r.nodes=r.nodes.map(i=>i.id===e?a:i),this.saveNodes(r),a}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(a=>a===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 a=t.levels[r]?.id;if(!a)break;let i=e.proposedAxes?.[n]??{},o=r===0?null:e.path[r-1];this.addNode({id:n,level:a,parentId:o,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 ne(w,e){B(oe(w),{recursive:!0});let t=`${w}.tmp-${process.pid}`;F(t,JSON.stringify(e,null,2)),ge(t,w)}function ae(){let w=new Date().toISOString(),e=[],t=new Set;for(let s of G)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:w,createdBy:"starter"}),t.add(s.category));for(let s of G)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:w,createdBy:"starter"});return{version:1,nodes:e}}pe();de();import{createHash as me}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=K(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:U(s.path),pathLabel:q(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),n=this.store.loadNodes().nodes,a=await this.proposePath(e,r,n).catch(g=>(this.log("LLM proposal failed:",g?.message||g),null));if(!a)return null;let{path:i,proposedAxes:o,confidence:c,leaf:l}=a;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:o,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(n.map(g=>g.id)),u=i.map((g,m)=>p.has(g)?-1:m).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=u.length===0,m=u.length===1&&u[0]===i.length-1;d=g||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,o,r,n,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:U(i),pathLabel:q(i,this.store.loadNodes().nodes),axes:o,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.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 globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-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
- `),a=await this.callProvider(n),i=V(a);if(!i||!Array.isArray(i.path))return null;let o=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,l=i.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let h=d.trim(),f=ce(h);return h!==f&&c.set(h,f),f}).filter(d=>o.test(d));if(l.length===0)return null;let v={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[d,h]of Object.entries(i.proposedAxes)){if(!h||typeof h!="object")continue;let f=c.get(d)??ce(d);if(!f)continue;let g={};for(let[m,b]of Object.entries(h))typeof b=="string"&&(g[m]=b);!g.name&&d!==f&&(g.name=d.trim()),v[f]=g}let p={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(p.input=i.leaf.input),typeof i.leaf.output=="string"&&(p.output=i.leaf.output));let u=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:l,proposedAxes:v,confidence:u,leaf:p}}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 ce(w){let e=w.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function U(w){return me("sha1").update(w.join("")).digest("hex").slice(0,16)}function q(w,e){return w.map(t=>{let s=e.find(n=>n.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function z(w,e){if(w.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(w.length,e.length)&&w[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(w.length,e.length);return t/s}import{readFileSync as N,writeFileSync as x,appendFileSync as ve,existsSync as $,mkdirSync as j,readdirSync as E,statSync as ye}from"fs";import{resolve as y,join as we,relative as S,dirname as be}from"path";he();var le=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,a]of Object.entries(e.meta))r.push(`${n}: ${JSON.stringify(a)}`);return r.push("---","",e.content),x(s,r.join(`
6
- `)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!$(this.rawDir))return[];let t=E(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let n=N(y(this.rawDir,r),"utf-8"),a=this.parseEntry(n,r);a&&(e?.agentId&&a.agentId!==e.agentId||e?.after&&a.date<e.after||e?.before&&a.date>e.before||s.push(a))}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(),a=c=>r.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),o={};for(let c of r.split(`
7
- `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:a("id")||t.replace(".md",""),date:a("date"),agentId:a("agent"),source:a("source"),sourceContext:a("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}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&&!X(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 a=y(this.baseDir,e);n&&this.saveVersion(e,a),j(be(a),{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),x(a,i.join(`
8
- `));let o=n?"update":"create";return this.appendLog(o,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!$(t))return;let s=N(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),n=y(this.baseDir,"_versions",e.replace(/\.md$/,""));j(n,{recursive:!0}),x(y(n,`${r}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!$(t))return[];try{return E(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=N(r.path,"utf-8"),a=y(this.baseDir,e);return this.saveVersion(e,a),x(a,n),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!$(t))return null;let s=N(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(),a=d=>r.match(new RegExp(`^${d}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=d=>{let h=r.match(new RegExp(`^${d}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},o=a("type")||a("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,v=i("tags").filter((d,h,f)=>d&&f.indexOf(d)===h),p=i("related"),u=i("graph_path");return{meta:{title:a("title"),type:l,related:p.length?p:void 0,tags:v,owner:a("owner"),access:a("access")||"public",sharedWith:i("shared_with"),created:a("created"),lastUpdated:a("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=S(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,p=>{if(!p.endsWith(".md"))return;let u=S(this.baseDir,p);if(u.startsWith("raw/")||u.startsWith("_"))return;let d=this.readArticle(u);!d||!this.canRead(d.meta,t)||n.push(d)}),n.length===0)return[];let a=n.map(p=>p.content),i=y(this.baseDir,"_bm25_cache.json"),o=T(a,i),c=O(e,o),l=new Map(c.map(p=>[p.docIndex,p.score]));return n.map((p,u)=>{let d=l.get(u)??0;return p.meta.title.toLowerCase().includes(r)&&(d+=10),p.meta.tags?.some(h=>h.toLowerCase().includes(r))&&(d+=5),{article:p,score:d}}).filter(p=>p.score>0).sort((p,u)=>u.score-p.score).slice(0,s).map(p=>p.article)}async findRelevantReranked(e,t,s=10,r={}){let n=Math.max(s,r.shortlist??Z),a=this.findRelevant(e,t,n);if(a.length<2)return a.slice(0,s);let i=a.map((l,v)=>({id:`c${v}`,title:l.meta.title||`(untitled ${v})`,tags:l.meta.tags,excerpt:l.content})),o=await Y(Q,ee({query:e,candidates:i,excerptChars:r.excerptChars}),te(i),{incumbent:{best:i[0].id},features:{agent:t??"unknown"}});return!o||o.mode!=="active"?a.slice(0,s):se(o.answers,i).ranked.map(l=>a[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(e,t,s=3,r,n={graph:.6,bm25:.4}){let a=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=S(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let g=this.readArticle(f);!g||!this.canRead(g.meta,t)||a.push(g)}),a.length===0)return[];let i=a.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),o=y(this.baseDir,"_bm25_relevance_cache.json"),c=T(i,o),l=O(e,c),v=l.reduce((h,f)=>Math.max(h,f.score),0)||1,p=new Map(l.map(h=>[h.docIndex,h.score/v])),u=!!(r&&r.length>0);return a.map((h,f)=>{let g=p.get(f)??0,m=0;u&&h.meta.graphPath?.length&&(m=z(r,h.meta.graphPath));let b=u?n.graph*m+n.bm25*g:g;return{article:h,score:b}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,s).map(h=>h.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let n of e){let a=`
1
+ import{a as T,b as R,c as re,d as L,e as _}from"./chunk-4DRNEOOW.js";import{b as X}from"./chunk-64P4QHSZ.js";import{a as Q,b as Z,c as ee,d as te,e as se}from"./chunk-TFVUOC2C.js";import{v as Y,w as he}from"./chunk-BBIWAJRX.js";import{a as V,b as pe}from"./chunk-FX3D7YON.js";import{c as O,d as M}from"./chunk-QOYAX2FT.js";import{o as K,p as de}from"./chunk-5MUJZODV.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)."}},G=[{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 F,appendFileSync as ue,existsSync as W,mkdirSync as B,renameSync as ge,statSync as ie}from"fs";import{resolve as P,dirname as oe}from"path";import{createHash as fe}from"crypto";var J=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),B(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!W(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;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("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{F(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(a){this.log(`could not back up old schema: ${a?.message??a}`)}this.saveSchema(A);let n=this.nodesPath();if(W(n)){let a=n.replace(/\.json$/,".v1.bak.json");try{F(a,D(n,"utf-8")),this.log(`archived v1 nodes.json -> ${a}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=ae();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);ne(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!W(e)){let t=ae();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let s=L.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=L.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:s,size:r}=ie(e),n=this.parsed.get(e);if(n&&n.mtimeMs===s&&n.size===r)return n.data;let a=t(D(e,"utf-8"));return this.parsed.set(e,{mtimeMs:s,size:r,data:a}),a}writeParsed(e,t){this.parsed.delete(e),ne(e,t);let{mtimeMs:s,size:r}=ie(e);this.parsed.set(e,{mtimeMs:s,size:r,data:t})}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 o=e.axes[i.name];if(o!=null){if(i.type==="enum"&&i.values&&!i.values.includes(o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===o);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let a=t.levels.findIndex(i=>i.id===e.level);if(a===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 o=t.levels.findIndex(c=>c.id===i.level);if(o<0||o>=a)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=[],a=[],i=new Date().toISOString();for(let o=0;o<e.length;o++){let c=e[o],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){a.push(c);continue}let p=0;for(let m=o-1;m>=0;m--){let b=e[m],C=l.find(k=>k.id===b)||n.find(k=>k.id===b);if(C){p=s.levels.findIndex(k=>k.id===C.level)+1;break}}let u=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let b=s.levels[m];if(b.axes.filter(k=>!k.optional).filter(k=>!(k.name in u)).length===0){d=b.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=o-1;m>=0;m--){let b=e[m],C=l.find(I=>I.id===b)||n.find(I=>I.id===b);if(!C)continue;let k=s.levels.findIndex(I=>I.id===C.level);if(k>=0&&k<f){h=b;break}}let g={id:c,level:d,parentId:h,axes:u,createdAt:i,createdBy:r};this.addNode(g),n.push(g)}return{added:n,skipped:a}}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=R.safeParse(e);if(!t.success){let n=t.error.issues.map(a=>`${a.path.join(".")}: ${a.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 W(r)||B(oe(r),{recursive:!0}),ue(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!W(e))return[];let s=D(e,"utf-8").split(`
3
+ `).filter(Boolean),r=new Map;for(let n of s)try{let a=R.safeParse(JSON.parse(n));if(!a.success)continue;r.set(a.data.msgHash,a.data)}catch{}return Array.from(r.values()).sort((n,a)=>n.ts<a.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(a=>a.msgHash===e);if(!r)return null;let n={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let a=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;n.preview=((r.preview||"")+a).slice(0,500)}return this.appendClassification(n),n}readRecentClassifications(e=50){let t=this.classificationsPath();if(!W(t))return[];let r=D(t,"utf-8").split(`
4
+ `).filter(Boolean),n=[];for(let a=r.length-1;a>=0&&n.length<e;a--)try{let i=R.safeParse(JSON.parse(r[a]));i.success&&n.push(i.data)}catch{}return n}fingerprint(e){let s=[me(e.text),e.channel??""].join("");return fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return W(e)?this.readParsed(e,t=>{let s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let s=re.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!s.success)throw new Error(`Refusing to save invalid index entry: ${s.error.issues.map(n=>n.message).join("; ")}`);let r=this.index();this.writeParsed(this.indexPath(),{...r,entries:{...r.entries,[e]:s.data}})}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 a={...n,axes:t};return this.validateNode(a,s,r.nodes.map(i=>i.id===e?a:i)),r.nodes=r.nodes.map(i=>i.id===e?a:i),this.saveNodes(r),a}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(a=>a===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 a=t.levels[r]?.id;if(!a)break;let i=e.proposedAxes?.[n]??{},o=r===0?null:e.path[r-1];this.addNode({id:n,level:a,parentId:o,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 ne(y,e){B(oe(y),{recursive:!0});let t=`${y}.tmp-${process.pid}`;F(t,JSON.stringify(e,null,2)),ge(t,y)}function ae(){let y=new Date().toISOString(),e=[],t=new Set;for(let s of G)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:y,createdBy:"starter"}),t.add(s.category));for(let s of G)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:y,createdBy:"starter"});return{version:1,nodes:e}}function me(y){return y.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}pe();de();import{createHash as ve}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=K(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:U(s.path),pathLabel:q(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),n=this.store.loadNodes().nodes,a=await this.proposePath(e,r,n).catch(g=>(this.log("LLM proposal failed:",g?.message||g),null));if(!a)return null;let{path:i,proposedAxes:o,confidence:c,leaf:l}=a;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:o,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(n.map(g=>g.id)),u=i.map((g,m)=>p.has(g)?-1:m).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=u.length===0,m=u.length===1&&u[0]===i.length-1;d=g||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,o,r,n,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:U(i),pathLabel:q(i,this.store.loadNodes().nodes),axes:o,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.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 globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-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
+ `),a=await this.callProvider(n),i=V(a);if(!i||!Array.isArray(i.path))return null;let o=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,l=i.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let h=d.trim(),f=ce(h);return h!==f&&c.set(h,f),f}).filter(d=>o.test(d));if(l.length===0)return null;let v={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[d,h]of Object.entries(i.proposedAxes)){if(!h||typeof h!="object")continue;let f=c.get(d)??ce(d);if(!f)continue;let g={};for(let[m,b]of Object.entries(h))typeof b=="string"&&(g[m]=b);!g.name&&d!==f&&(g.name=d.trim()),v[f]=g}let p={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(p.input=i.leaf.input),typeof i.leaf.output=="string"&&(p.output=i.leaf.output));let u=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:l,proposedAxes:v,confidence:u,leaf:p}}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,abortSignal:s.signal,bare:!0})).content||""}finally{clearTimeout(r)}}};function ce(y){let e=y.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function U(y){return ve("sha1").update(y.join("")).digest("hex").slice(0,16)}function q(y,e){return y.map(t=>{let s=e.find(n=>n.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function z(y,e){if(y.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(y.length,e.length)&&y[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(y.length,e.length);return t/s}import{readFileSync as N,writeFileSync as x,appendFileSync as we,existsSync as $,mkdirSync as j,readdirSync as E,statSync as ye}from"fs";import{resolve as w,join as be,relative as S,dirname as ke}from"path";he();var le=class{baseDir;rawDir;log;constructor(e=w(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=w(e,"raw/entries"),this.log=t,j(this.rawDir,{recursive:!0}),j(w(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=w(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,a]of Object.entries(e.meta))r.push(`${n}: ${JSON.stringify(a)}`);return r.push("---","",e.content),x(s,r.join(`
6
+ `)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!$(this.rawDir))return[];let t=E(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let n=N(w(this.rawDir,r),"utf-8"),a=this.parseEntry(n,r);a&&(e?.agentId&&a.agentId!==e.agentId||e?.after&&a.date<e.after||e?.before&&a.date>e.before||s.push(a))}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(),a=c=>r.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),o={};for(let c of r.split(`
7
+ `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:a("id")||t.replace(".md",""),date:a("date"),agentId:a("agent"),source:a("source"),sourceContext:a("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}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&&!X(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 a=w(this.baseDir,e);n&&this.saveVersion(e,a),j(ke(a),{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),x(a,i.join(`
8
+ `));let o=n?"update":"create";return this.appendLog(o,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!$(t))return;let s=N(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),n=w(this.baseDir,"_versions",e.replace(/\.md$/,""));j(n,{recursive:!0}),x(w(n,`${r}.md`),s)}catch{}}getVersions(e){let t=w(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!$(t))return[];try{return E(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:w(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=N(r.path,"utf-8"),a=w(this.baseDir,e);return this.saveVersion(e,a),x(a,n),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=w(this.baseDir,e);if(!$(t))return null;let s=N(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(),a=d=>r.match(new RegExp(`^${d}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=d=>{let h=r.match(new RegExp(`^${d}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},o=a("type")||a("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,v=i("tags").filter((d,h,f)=>d&&f.indexOf(d)===h),p=i("related"),u=i("graph_path");return{meta:{title:a("title"),type:l,related:p.length?p:void 0,tags:v,owner:a("owner"),access:a("access")||"public",sharedWith:i("shared_with"),created:a("created"),lastUpdated:a("last_updated"),sources:i("sources"),graphPath:u.length?u:void 0},content:n,path:t}}listCache=new Map;listArticles(e){let t=[],s=[];this.walkDir(this.baseDir,(i,o)=>{if(!i.endsWith(".md"))return;let c=S(this.baseDir,i);c.startsWith("raw/")||c.startsWith("_")||(t.push(c),s.push(`${c}:${o?.mtimeMs??"?"}:${o?.size??"?"}`))});let r=s.join("|"),n=this.listCache.get(e);if(n&&n.signature===r)return n.articles.slice();let a=[];for(let i of t){let o=this.readArticle(i);o&&this.canRead(o.meta,e)&&a.push(o)}return this.listCache.set(e,{signature:r,articles:a}),a.slice()}search(e,t,s=10){let r=e.toLowerCase(),n=[];if(this.walkDir(this.baseDir,p=>{if(!p.endsWith(".md"))return;let u=S(this.baseDir,p);if(u.startsWith("raw/")||u.startsWith("_"))return;let d=this.readArticle(u);!d||!this.canRead(d.meta,t)||n.push(d)}),n.length===0)return[];let a=n.map(p=>p.content),i=w(this.baseDir,"_bm25_cache.json"),o=M(a,i),c=O(e,o),l=new Map(c.map(p=>[p.docIndex,p.score]));return n.map((p,u)=>{let d=l.get(u)??0;return p.meta.title.toLowerCase().includes(r)&&(d+=10),p.meta.tags?.some(h=>h.toLowerCase().includes(r))&&(d+=5),{article:p,score:d}}).filter(p=>p.score>0).sort((p,u)=>u.score-p.score).slice(0,s).map(p=>p.article)}async findRelevantReranked(e,t,s=10,r={}){let n=Math.max(s,r.shortlist??Z),a=this.findRelevant(e,t,n);if(a.length<2)return a.slice(0,s);let i=a.map((l,v)=>({id:`c${v}`,title:l.meta.title||`(untitled ${v})`,tags:l.meta.tags,excerpt:l.content})),o=await Y(Q,ee({query:e,candidates:i,excerptChars:r.excerptChars}),te(i),{incumbent:{best:i[0].id},features:{agent:t??"unknown"}});return!o||o.mode!=="active"?a.slice(0,s):se(o.answers,i).ranked.map(l=>a[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(e,t,s=3,r,n={graph:.6,bm25:.4}){let a=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=S(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let g=this.readArticle(f);!g||!this.canRead(g.meta,t)||a.push(g)}),a.length===0)return[];let i=a.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),o=w(this.baseDir,"_bm25_relevance_cache.json"),c=M(i,o),l=O(e,c),v=l.reduce((h,f)=>Math.max(h,f.score),0)||1,p=new Map(l.map(h=>[h.docIndex,h.score/v])),u=!!(r&&r.length>0);return a.map((h,f)=>{let g=p.get(f)??0,m=0;u&&h.meta.graphPath?.length&&(m=z(r,h.meta.graphPath));let b=u?n.graph*m+n.bm25*g:g;return{article:h,score:b}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,s).map(h=>h.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let n of e){let a=`
9
9
  ## ${n.meta.title} [${(n.meta.tags||[]).slice(0,3).join(", ")}]`,i=n.content.length>600?n.content.slice(0,600)+"...":n.content,o=a+`
10
10
  `+i;if(r+o.length>t)break;s.push(o),r+=o.length}return s.push(`
11
11
  [End Wiki Knowledge]`),s.join(`
12
- `)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o)return;let c=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let v of c){let p=v.replace(/\[\[|\]\]/g,"");t.set(p,(t.get(p)||0)+1)}let l=[o.meta.title.toLowerCase()];o.meta.tags&&l.push(...o.meta.tags.map(v=>v.toLowerCase())),e.push({path:i,title:o.meta.title,type:o.meta.type,related:o.meta.related,tags:o.meta.tags||[],owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:l,backlinks:t.get(o.meta.title)||0,sources:o.meta.sources,lastUpdated:o.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};x(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 a of e){let i=a.access||"public",o=n.get(i)||[];o.push(a),n.set(i,o)}for(let[a,i]of Array.from(n.entries()).sort()){r.push(`## ${a}`,"");for(let o of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=o.type?` [${o.type}]`:"";r.push(`- [${o.title}](${o.path})${c} \u2014 owner: ${o.owner}`)}r.push("")}return x(y(this.baseDir,"WIKI.md"),r.join(`
13
- `)),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 o=i.type||"untyped",c=n.get(o)||[];c.push(i),n.set(o,c)}let a=["# 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 o=n.get(i);if(!(!o||o.length===0)){a.push(r[i]||`## ${i}`,"");for(let c of o.sort((l,v)=>l.title.localeCompare(v.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",v=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";a.push(`- [${c.title}](${c.path})${l}${v}`)}a.push("")}}x(y(this.baseDir,"_index.md"),a.join(`
14
- `))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let o=this.readArticle(i);if(o){e++;for(let c of o.meta.tags||[])t[c]=(t[c]||0)+1;s[o.meta.access]=(s[o.meta.access]||0)+1,r[o.meta.owner]=(r[o.meta.owner]||0)+1}});let n=$(this.rawDir)?E(this.rawDir).filter(a=>a.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}
12
+ `)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o)return;let c=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let v of c){let p=v.replace(/\[\[|\]\]/g,"");t.set(p,(t.get(p)||0)+1)}let l=[o.meta.title.toLowerCase()];o.meta.tags&&l.push(...o.meta.tags.map(v=>v.toLowerCase())),e.push({path:i,title:o.meta.title,type:o.meta.type,related:o.meta.related,tags:o.meta.tags||[],owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:l,backlinks:t.get(o.meta.title)||0,sources:o.meta.sources,lastUpdated:o.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};x(w(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 a of e){let i=a.access||"public",o=n.get(i)||[];o.push(a),n.set(i,o)}for(let[a,i]of Array.from(n.entries()).sort()){r.push(`## ${a}`,"");for(let o of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=o.type?` [${o.type}]`:"";r.push(`- [${o.title}](${o.path})${c} \u2014 owner: ${o.owner}`)}r.push("")}return x(w(this.baseDir,"WIKI.md"),r.join(`
13
+ `)),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 o=i.type||"untyped",c=n.get(o)||[];c.push(i),n.set(o,c)}let a=["# 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 o=n.get(i);if(!(!o||o.length===0)){a.push(r[i]||`## ${i}`,"");for(let c of o.sort((l,v)=>l.title.localeCompare(v.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",v=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";a.push(`- [${c.title}](${c.path})${l}${v}`)}a.push("")}}x(w(this.baseDir,"_index.md"),a.join(`
14
+ `))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let o=this.readArticle(i);if(o){e++;for(let c of o.meta.tags||[])t[c]=(t[c]||0)+1;s[o.meta.access]=(s[o.meta.access]||0)+1,r[o.meta.owner]=(r[o.meta.owner]||0)+1}});let n=$(this.rawDir)?E(this.rawDir).filter(a=>a.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:n,articlesByType:t,articlesByAccess:s,articlesByOwner:r}}appendLog(e,t){let s=w(this.baseDir,"log.md"),n=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
15
15
 
16
16
  `;$(s)||x(s,`# Wiki Log
17
17
 
18
18
  Chronological record of all wiki operations.
19
19
 
20
- `),ve(s,n)}getLog(e=20){let t=y(this.baseDir,"log.md");return $(t)?N(t,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-e).map(n=>n.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if($(e))return;x(e,`# Wiki Schema
20
+ `),we(s,n)}getLog(e=20){let t=w(this.baseDir,"log.md");return $(t)?N(t,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-e).map(n=>n.trim()):[]}ensureSchema(){let e=w(this.baseDir,"_schema.md");if($(e))return;x(e,`# Wiki Schema
21
21
 
22
22
  A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
23
23
  structure emerges from data. The wiki is a compounding artifact.
@@ -98,12 +98,12 @@ Clients: ClientA (enterprise), ClientB (startup).
98
98
  Infrastructure: local dev machine, cloud server.
99
99
  We use GitLab for version control.
100
100
  \`\`\`
101
- `),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=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=N(t,"utf-8"),n=this.extractWikilinks(r);for(let a of n)e[a]||(e[a]=[]),e[a].push(s)}),x(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!$(t))return[];try{return JSON.parse(N(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(a=>a.toLowerCase()),n=[];return this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o||t&&!this.canRead(o.meta,t))return;let c=(o.meta.tags||[]).map(u=>u.toLowerCase()),l=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(d=>d.trim().toLowerCase())),v=[...c,...l],p=r.filter(u=>v.includes(u)).length;p>0&&n.push({article:o,score:p})}),n.sort((a,i)=>i.score-a.score).slice(0,s).map(a=>a.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=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 $(e)?N(e,"utf-8"):null}setWorldview(e){x(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,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let o=this.readArticle(i);if(!o)return;t.add(o.meta.title),r.set(o.meta.title,i);let c=this.extractWikilinks(o.content);s.set(i,c);let l=o.content.split(`
101
+ `),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=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=N(t,"utf-8"),n=this.extractWikilinks(r);for(let a of n)e[a]||(e[a]=[]),e[a].push(s)}),x(w(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=w(this.baseDir,"_backlinks.json");if(!$(t))return[];try{return JSON.parse(N(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(a=>a.toLowerCase()),n=[];return this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o||t&&!this.canRead(o.meta,t))return;let c=(o.meta.tags||[]).map(u=>u.toLowerCase()),l=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(d=>d.trim().toLowerCase())),v=[...c,...l],p=r.filter(u=>v.includes(u)).length;p>0&&n.push({article:o,score:p})}),n.sort((a,i)=>i.score-a.score).slice(0,s).map(a=>a.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=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=w(this.baseDir,"worldview.md");return $(e)?N(e,"utf-8"):null}setWorldview(e){x(w(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,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let o=this.readArticle(i);if(!o)return;t.add(o.meta.title),r.set(o.meta.title,i);let c=this.extractWikilinks(o.content);s.set(i,c);let l=o.content.split(`
102
102
  `).length;l>100&&e.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),o.meta.sources?.length||e.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&o.content.trim().length<100&&e.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[a,i]of s)for(let o of i)t.has(o)||e.push({type:"broken-link",article:a,message:`[[${o}]] \u2014 target article not found`});let n=this.buildBacklinks();for(let[a,i]of r)(!n[a]||n[a].length===0)&&e.push({type:"orphan",article:i,message:`No other articles link to "${a}"`});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=S(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);if(n?.meta.sources)for(let a of n.meta.sources)e.add(a)}),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(`
103
103
 
104
104
  `);return`/wiki absorb
105
105
 
106
106
  There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
107
107
 
108
- ${s}`}walkDir(e,t){if($(e))for(let s of E(e)){let r=we(e,s);ye(r).isDirectory()?this.walkDir(r,t):t(r)}}};export{A as a,J as b,H as c,q as d,le as e};
109
- //# sourceMappingURL=chunk-EQTSOK7L.js.map
108
+ ${s}`}walkDir(e,t){if($(e))for(let s of E(e)){let r=be(e,s),n=ye(r);n.isDirectory()?this.walkDir(r,t):t(r,n)}}};export{A as a,J as b,H as c,q as d,le as e};
109
+ //# sourceMappingURL=chunk-535MLOSB.js.map