agentix-cli 0.133.0 → 0.135.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/{App-WQPA77VJ.js → App-4UVAI5C5.js} +2 -2
  2. package/dist/{ChatApp-TGW66I4Y.js → ChatApp-COO67WIR.js} +2 -2
  3. package/dist/absorb-eval-WY3YMLS4.js +2 -0
  4. package/dist/{agent-FWHYHXWC.js → agent-3R5NY7I3.js} +2 -2
  5. package/dist/{board-dashboard-GKE4KWJH.js → board-dashboard-U3ZSCO62.js} +24 -8
  6. package/dist/board-dashboard-U3ZSCO62.js.map +1 -0
  7. package/dist/{chunk-ZN5DC6WS.js → chunk-3XVST5XX.js} +2 -2
  8. package/dist/{note-reader-LPPIYYLT.js → chunk-4LWFJ4MZ.js} +3 -3
  9. package/dist/{note-reader-LPPIYYLT.js.map → chunk-4LWFJ4MZ.js.map} +1 -1
  10. package/dist/{chunk-F5PVUB4Y.js → chunk-4XMALK7X.js} +2 -2
  11. package/dist/{chunk-VH2ASPFQ.js → chunk-5NT44FKL.js} +2 -2
  12. package/dist/{chunk-HIUHKOKK.js → chunk-6WF56ME6.js} +2 -2
  13. package/dist/{chunk-MCBTVNPX.js → chunk-BQIWMQNU.js} +2 -2
  14. package/dist/{chunk-2BF6HJJD.js → chunk-DYGQF3MI.js} +4 -4
  15. package/dist/chunk-DYGQF3MI.js.map +1 -0
  16. package/dist/{chunk-4NEO5KB2.js → chunk-EEBK4F6E.js} +15 -15
  17. package/dist/chunk-EEBK4F6E.js.map +1 -0
  18. package/dist/{chunk-JA5Y4LDP.js → chunk-ERULJ2ZL.js} +2 -2
  19. package/dist/{chunk-RJFPCW7T.js → chunk-FWDRBUMS.js} +2 -2
  20. package/dist/{chunk-SJPQQ4OF.js → chunk-GSKJ57XY.js} +234 -234
  21. package/dist/chunk-GSKJ57XY.js.map +1 -0
  22. package/dist/{chunk-4XPVU3N2.js → chunk-H6VWU2HN.js} +2 -2
  23. package/dist/chunk-JRS5QRZG.js +2 -0
  24. package/dist/chunk-JRS5QRZG.js.map +1 -0
  25. package/dist/{chunk-5BI2T3WD.js → chunk-JTDUTCUE.js} +3 -3
  26. package/dist/chunk-JTDUTCUE.js.map +1 -0
  27. package/dist/{chunk-KUOH5MFS.js → chunk-K445URSN.js} +2 -2
  28. package/dist/{chunk-4VVHGR7H.js → chunk-KEXBEUSU.js} +1 -1
  29. package/dist/{chunk-4VVHGR7H.js.map → chunk-KEXBEUSU.js.map} +1 -1
  30. package/dist/chunk-L5UGH4T4.js +160 -0
  31. package/dist/chunk-L5UGH4T4.js.map +1 -0
  32. package/dist/{chunk-V4IFJLQS.js → chunk-LU7GDHGD.js} +2 -2
  33. package/dist/{chunk-D5IHICX3.js → chunk-LUYN6RAC.js} +2 -2
  34. package/dist/chunk-MI7WOGH6.js +4 -0
  35. package/dist/chunk-MI7WOGH6.js.map +1 -0
  36. package/dist/chunk-NY7NHGVT.js +105 -0
  37. package/dist/chunk-NY7NHGVT.js.map +1 -0
  38. package/dist/chunk-NZQBS7GN.js +2 -0
  39. package/dist/{chunk-KBJNJGBP.js.map → chunk-NZQBS7GN.js.map} +1 -1
  40. package/dist/{chunk-3TETB22A.js → chunk-P3I7AATX.js} +2 -2
  41. package/dist/chunk-QAWKN2N4.js +3 -0
  42. package/dist/chunk-QAWKN2N4.js.map +1 -0
  43. package/dist/chunk-QDWEM4DG.js +41 -0
  44. package/dist/chunk-QDWEM4DG.js.map +1 -0
  45. package/dist/{chunk-JP5OAMWQ.js → chunk-RGZARSHV.js} +1 -1
  46. package/dist/{chunk-JP5OAMWQ.js.map → chunk-RGZARSHV.js.map} +1 -1
  47. package/dist/{chunk-GZY5DYXT.js → chunk-RRGITX5B.js} +2 -2
  48. package/dist/{chunk-PHCWYKQW.js → chunk-RVEMX5MJ.js} +2 -2
  49. package/dist/{chunk-PHCWYKQW.js.map → chunk-RVEMX5MJ.js.map} +1 -1
  50. package/dist/{chunk-GUEIF7ZF.js → chunk-SMAI7U6H.js} +2 -2
  51. package/dist/{chunk-S2UXDEGW.js → chunk-SSQMFHSM.js} +2 -2
  52. package/dist/chunk-WWDYDLY2.js +55 -0
  53. package/dist/chunk-WWDYDLY2.js.map +1 -0
  54. package/dist/{chunk-ANC5QXFB.js → chunk-XOUO4XNA.js} +2 -2
  55. package/dist/chunk-YA3P77LV.js +87 -0
  56. package/dist/chunk-YA3P77LV.js.map +1 -0
  57. package/dist/{chunk-OQV3LWJI.js → chunk-ZFRXFUP7.js} +2 -2
  58. package/dist/{chunk-F7GKG5ZO.js → chunk-ZGVVYJIK.js} +3 -3
  59. package/dist/chunk-ZGVVYJIK.js.map +1 -0
  60. package/dist/cli.js +1 -1
  61. package/dist/{client-7UW2ELPP.js → client-NFPBE6L4.js} +2 -2
  62. package/dist/{config-TNYVPT4R.js → config-GHMRBRDL.js} +2 -2
  63. package/dist/{config-mutate-GV7BVG3I.js → config-mutate-2XV27EFV.js} +2 -2
  64. package/dist/config-mutator-6ITNU5DT.js +2 -0
  65. package/dist/{contributions-J57B3KIX.js → contributions-KLRJ4ZXV.js} +2 -2
  66. package/dist/{contributions-J57B3KIX.js.map → contributions-KLRJ4ZXV.js.map} +1 -1
  67. package/dist/{doctor-ROKIYJRT.js → doctor-UBXVMGJG.js} +2 -2
  68. package/dist/{enrich-NH3WHKD6.js → enrich-ZB5I7KHN.js} +2 -2
  69. package/dist/event-levels-CQWHSLMT.js +3 -0
  70. package/dist/event-levels-CQWHSLMT.js.map +1 -0
  71. package/dist/{follow-up-tool-S2U7DFSW.js → follow-up-tool-EARVITTS.js} +2 -2
  72. package/dist/graph-ZVKV3JBD.js +2 -0
  73. package/dist/hub-TILTOOSS.js +2 -0
  74. package/dist/index.d.ts +281 -84
  75. package/dist/index.js +1 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/load-EOZUZK7U.js +2 -0
  78. package/dist/model-call-PKV5UAQ7.js +2 -0
  79. package/dist/note-reader-IDE6RI34.js +2 -0
  80. package/dist/notes-settings-VPXI5IIS.js +2 -0
  81. package/dist/{program-LAOU5DQ3.js → program-U3HJY7E5.js} +262 -264
  82. package/dist/program-U3HJY7E5.js.map +1 -0
  83. package/dist/{promote-FVWRM4BE.js → promote-RHVZB2QZ.js} +2 -2
  84. package/dist/push-bridge-325SXDGN.js +1 -1
  85. package/dist/query-OZXZVLO7.js +2 -0
  86. package/dist/query-runs-7VX3YAC3.js +4 -0
  87. package/dist/query-runs-7VX3YAC3.js.map +1 -0
  88. package/dist/query-settings-2MGUS6AY.js +3 -0
  89. package/dist/query-settings-2MGUS6AY.js.map +1 -0
  90. package/dist/registry-LZLIPP7N.js +2 -0
  91. package/dist/{request-planner-JOXSAAHO.js → request-planner-MFAIVLUQ.js} +2 -2
  92. package/dist/{review-candidates-6N5435V7.js → review-candidates-6WMDVVIZ.js} +2 -2
  93. package/dist/roster-BZGKG2ZA.js +2 -0
  94. package/dist/{routing-6G2QVFIG.js → routing-OPCLHIYW.js} +2 -2
  95. package/dist/schedule-tool-KPVTMYL3.js +2 -0
  96. package/dist/{scheduler-WOH2O3EP.js → scheduler-G3WWYETY.js} +2 -2
  97. package/dist/score-DZGPLHCL.js +3 -0
  98. package/dist/score-DZGPLHCL.js.map +1 -0
  99. package/dist/{seat-I2FBJDTV.js → seat-3HM4J7IX.js} +2 -2
  100. package/dist/{select-5YZQJLLD.js → select-VEFE2ESF.js} +2 -2
  101. package/dist/{set-enabled-CQEUZLHU.js → set-enabled-US5BYKFZ.js} +2 -2
  102. package/dist/{tool-PIJXUBEC.js → tool-HUSCHORN.js} +2 -2
  103. package/dist/{tool-R77KFLZ3.js → tool-XLWLXGB5.js} +2 -2
  104. package/dist/types-ARP27T6T.js +2 -0
  105. package/dist/types-LJZ2YY5W.js +2 -0
  106. package/dist/types-LJZ2YY5W.js.map +1 -0
  107. package/dist/wiki-GCRRINW3.js +2 -0
  108. package/dist/wiki-GCRRINW3.js.map +1 -0
  109. package/dist/wiki-enrich-P5TNWACZ.js +2 -0
  110. package/dist/wiki-enrich-P5TNWACZ.js.map +1 -0
  111. package/package.json +1 -1
  112. package/dist/absorb-eval-37XZJACN.js +0 -2
  113. package/dist/board-dashboard-GKE4KWJH.js.map +0 -1
  114. package/dist/chunk-2BF6HJJD.js.map +0 -1
  115. package/dist/chunk-4NEO5KB2.js.map +0 -1
  116. package/dist/chunk-57Y2WZT2.js +0 -55
  117. package/dist/chunk-57Y2WZT2.js.map +0 -1
  118. package/dist/chunk-5BI2T3WD.js.map +0 -1
  119. package/dist/chunk-7VLLZQ3N.js +0 -2
  120. package/dist/chunk-7VLLZQ3N.js.map +0 -1
  121. package/dist/chunk-BI6VG4DV.js +0 -37
  122. package/dist/chunk-BI6VG4DV.js.map +0 -1
  123. package/dist/chunk-F7GKG5ZO.js.map +0 -1
  124. package/dist/chunk-IDZXAOBC.js +0 -156
  125. package/dist/chunk-IDZXAOBC.js.map +0 -1
  126. package/dist/chunk-IZDKRNXC.js +0 -52
  127. package/dist/chunk-IZDKRNXC.js.map +0 -1
  128. package/dist/chunk-KBJNJGBP.js +0 -2
  129. package/dist/chunk-KFIJDLQ5.js +0 -3
  130. package/dist/chunk-KFIJDLQ5.js.map +0 -1
  131. package/dist/chunk-RTHZQGFC.js +0 -105
  132. package/dist/chunk-RTHZQGFC.js.map +0 -1
  133. package/dist/chunk-SJPQQ4OF.js.map +0 -1
  134. package/dist/config-mutator-AKCR3VKM.js +0 -2
  135. package/dist/graph-EXDH7EPZ.js +0 -2
  136. package/dist/hub-HOVJC4HR.js +0 -2
  137. package/dist/load-5DNMGHFW.js +0 -2
  138. package/dist/model-call-BGTDPWZD.js +0 -2
  139. package/dist/notes-settings-WMOH2V75.js +0 -2
  140. package/dist/program-LAOU5DQ3.js.map +0 -1
  141. package/dist/query-HBCL3FHO.js +0 -2
  142. package/dist/query-settings-RD6GEN2V.js +0 -3
  143. package/dist/query-settings-RD6GEN2V.js.map +0 -1
  144. package/dist/registry-NT4H7HYP.js +0 -2
  145. package/dist/roster-IRXP32XF.js +0 -2
  146. package/dist/schedule-tool-3NYUPKSC.js +0 -2
  147. package/dist/score-KDNIUTNV.js +0 -3
  148. package/dist/score-KDNIUTNV.js.map +0 -1
  149. package/dist/types-ROL44T62.js +0 -2
  150. package/dist/wiki-GCOFERTB.js +0 -2
  151. /package/dist/{App-WQPA77VJ.js.map → App-4UVAI5C5.js.map} +0 -0
  152. /package/dist/{ChatApp-TGW66I4Y.js.map → ChatApp-COO67WIR.js.map} +0 -0
  153. /package/dist/{absorb-eval-37XZJACN.js.map → absorb-eval-WY3YMLS4.js.map} +0 -0
  154. /package/dist/{agent-FWHYHXWC.js.map → agent-3R5NY7I3.js.map} +0 -0
  155. /package/dist/{chunk-ZN5DC6WS.js.map → chunk-3XVST5XX.js.map} +0 -0
  156. /package/dist/{chunk-F5PVUB4Y.js.map → chunk-4XMALK7X.js.map} +0 -0
  157. /package/dist/{chunk-VH2ASPFQ.js.map → chunk-5NT44FKL.js.map} +0 -0
  158. /package/dist/{chunk-HIUHKOKK.js.map → chunk-6WF56ME6.js.map} +0 -0
  159. /package/dist/{chunk-MCBTVNPX.js.map → chunk-BQIWMQNU.js.map} +0 -0
  160. /package/dist/{chunk-JA5Y4LDP.js.map → chunk-ERULJ2ZL.js.map} +0 -0
  161. /package/dist/{chunk-RJFPCW7T.js.map → chunk-FWDRBUMS.js.map} +0 -0
  162. /package/dist/{chunk-4XPVU3N2.js.map → chunk-H6VWU2HN.js.map} +0 -0
  163. /package/dist/{chunk-KUOH5MFS.js.map → chunk-K445URSN.js.map} +0 -0
  164. /package/dist/{chunk-V4IFJLQS.js.map → chunk-LU7GDHGD.js.map} +0 -0
  165. /package/dist/{chunk-D5IHICX3.js.map → chunk-LUYN6RAC.js.map} +0 -0
  166. /package/dist/{chunk-3TETB22A.js.map → chunk-P3I7AATX.js.map} +0 -0
  167. /package/dist/{chunk-GZY5DYXT.js.map → chunk-RRGITX5B.js.map} +0 -0
  168. /package/dist/{chunk-GUEIF7ZF.js.map → chunk-SMAI7U6H.js.map} +0 -0
  169. /package/dist/{chunk-S2UXDEGW.js.map → chunk-SSQMFHSM.js.map} +0 -0
  170. /package/dist/{chunk-ANC5QXFB.js.map → chunk-XOUO4XNA.js.map} +0 -0
  171. /package/dist/{chunk-OQV3LWJI.js.map → chunk-ZFRXFUP7.js.map} +0 -0
  172. /package/dist/{client-7UW2ELPP.js.map → client-NFPBE6L4.js.map} +0 -0
  173. /package/dist/{config-TNYVPT4R.js.map → config-GHMRBRDL.js.map} +0 -0
  174. /package/dist/{config-mutate-GV7BVG3I.js.map → config-mutate-2XV27EFV.js.map} +0 -0
  175. /package/dist/{config-mutator-AKCR3VKM.js.map → config-mutator-6ITNU5DT.js.map} +0 -0
  176. /package/dist/{doctor-ROKIYJRT.js.map → doctor-UBXVMGJG.js.map} +0 -0
  177. /package/dist/{enrich-NH3WHKD6.js.map → enrich-ZB5I7KHN.js.map} +0 -0
  178. /package/dist/{follow-up-tool-S2U7DFSW.js.map → follow-up-tool-EARVITTS.js.map} +0 -0
  179. /package/dist/{graph-EXDH7EPZ.js.map → graph-ZVKV3JBD.js.map} +0 -0
  180. /package/dist/{hub-HOVJC4HR.js.map → hub-TILTOOSS.js.map} +0 -0
  181. /package/dist/{load-5DNMGHFW.js.map → load-EOZUZK7U.js.map} +0 -0
  182. /package/dist/{model-call-BGTDPWZD.js.map → model-call-PKV5UAQ7.js.map} +0 -0
  183. /package/dist/{notes-settings-WMOH2V75.js.map → note-reader-IDE6RI34.js.map} +0 -0
  184. /package/dist/{promote-FVWRM4BE.js.map → notes-settings-VPXI5IIS.js.map} +0 -0
  185. /package/dist/{query-HBCL3FHO.js.map → promote-RHVZB2QZ.js.map} +0 -0
  186. /package/dist/{registry-NT4H7HYP.js.map → query-OZXZVLO7.js.map} +0 -0
  187. /package/dist/{roster-IRXP32XF.js.map → registry-LZLIPP7N.js.map} +0 -0
  188. /package/dist/{request-planner-JOXSAAHO.js.map → request-planner-MFAIVLUQ.js.map} +0 -0
  189. /package/dist/{review-candidates-6N5435V7.js.map → review-candidates-6WMDVVIZ.js.map} +0 -0
  190. /package/dist/{routing-6G2QVFIG.js.map → roster-BZGKG2ZA.js.map} +0 -0
  191. /package/dist/{schedule-tool-3NYUPKSC.js.map → routing-OPCLHIYW.js.map} +0 -0
  192. /package/dist/{scheduler-WOH2O3EP.js.map → schedule-tool-KPVTMYL3.js.map} +0 -0
  193. /package/dist/{seat-I2FBJDTV.js.map → scheduler-G3WWYETY.js.map} +0 -0
  194. /package/dist/{types-ROL44T62.js.map → seat-3HM4J7IX.js.map} +0 -0
  195. /package/dist/{select-5YZQJLLD.js.map → select-VEFE2ESF.js.map} +0 -0
  196. /package/dist/{set-enabled-CQEUZLHU.js.map → set-enabled-US5BYKFZ.js.map} +0 -0
  197. /package/dist/{tool-PIJXUBEC.js.map → tool-HUSCHORN.js.map} +0 -0
  198. /package/dist/{tool-R77KFLZ3.js.map → tool-XLWLXGB5.js.map} +0 -0
  199. /package/dist/{wiki-GCOFERTB.js.map → types-ARP27T6T.js.map} +0 -0
@@ -1,6 +1,6 @@
1
- import{d as h}from"./chunk-OQV3LWJI.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
1
+ import{d as h}from"./chunk-ZFRXFUP7.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
2
2
  `),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
3
3
  `).filter(o=>o.trim()).length,a=c.split(`
4
4
  `).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
5
5
  `))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
6
- //# sourceMappingURL=chunk-V4IFJLQS.js.map
6
+ //# sourceMappingURL=chunk-LU7GDHGD.js.map
@@ -1,5 +1,5 @@
1
- import{na as m,oa as $,xa as x}from"./chunk-2BF6HJJD.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{na as m,oa as $,xa as x}from"./chunk-DYGQF3MI.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-D5IHICX3.js.map
5
+ //# sourceMappingURL=chunk-LUYN6RAC.js.map
@@ -0,0 +1,4 @@
1
+ import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-TILTOOSS.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-EOZUZK7U.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-ZB5I7KHN.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-ZB5I7KHN.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
2
+ `).slice(0,12).map(n=>` | ${n}`).join(`
3
+ `)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
4
+ //# sourceMappingURL=chunk-MI7WOGH6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/wiki-enrich.ts"],"sourcesContent":["import type { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { spawn } from \"child_process\"\nimport { resolve } from \"path\"\n\n// --- agentx wiki enrich: full overview, typed facts and linked history per entity (#820) ---\n//\n// Runs on demand or from a scheduled job with `command`. Each entity\n// costs one model call; `--max-cost` stops the run before the next call\n// once the spend reaches it.\n\nconst wikiDir = (dir?: string) => dir || resolve(process.cwd(), \".agentx/wiki\")\n\n/** One `claude -p` call with no tools; cost from the JSON envelope.\n * The prompt carries raw message text, so no built-in tool, MCP server,\n * hook or settings file is loaded: an injected instruction has nothing\n * to write or send with. */\nexport function claudeCall(model: string): (prompt: string) => Promise<{ text: string; costUsd: number }> {\n return async (prompt) => {\n const { claudeCliEnv } = await import(\"@/utils/workspace-env\")\n const args = [\"-p\", \"-\", \"--output-format\", \"json\", \"--max-turns\", \"1\", \"--model\", model,\n \"--tools\", \"\", \"--strict-mcp-config\", \"--mcp-config\", '{\"mcpServers\":{}}',\n \"--settings\", '{\"disableAllHooks\":true}', \"--setting-sources\", \"\", \"--no-session-persistence\"]\n const out = await new Promise<string>((ok, fail) => {\n const child = spawn(\"claude\", args, { env: claudeCliEnv(), stdio: [\"pipe\", \"pipe\", \"pipe\"] })\n let stdout = \"\"\n let stderr = \"\"\n const timer = setTimeout(() => child.kill(\"SIGTERM\"), 240_000)\n child.stdout.on(\"data\", d => { stdout += d })\n child.stderr.on(\"data\", d => { stderr += d })\n child.on(\"error\", err => { clearTimeout(timer); fail(err) })\n child.on(\"close\", code => {\n clearTimeout(timer)\n if (code === 0) ok(stdout)\n else fail(new Error(`claude exited ${code}: ${stderr.trim().slice(0, 200)}`))\n })\n child.stdin.end(prompt)\n })\n const envelope = JSON.parse(out) as { result?: string; total_cost_usd?: number; is_error?: boolean }\n if (envelope.is_error) throw new Error(`model error: ${String(envelope.result).slice(0, 200)}`)\n return { text: String(envelope.result ?? \"\"), costUsd: Number(envelope.total_cost_usd) || 0 }\n }\n}\n\nexport function registerWikiEnrich(wiki: Command): void {\n wiki\n .command(\"enrich [entities...]\")\n .description(\"write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)\")\n .option(\"--dir <path>\", \"wiki directory (default .agentx/wiki)\")\n .option(\"--types <list>\", \"comma-separated entity types\", \"person,organization,project,place,device,server,app,domain,account\")\n .option(\"--max <n>\", \"most entities per run\", \"10\")\n .option(\"--max-cost <usd>\", \"stop before the next call once the run spent this much\", \"1\")\n .option(\"--model <m>\", \"model\", \"sonnet\")\n .option(\"--force\", \"redo entities whose sources did not change\")\n .option(\"--dry-run\", \"show what would be written, write nothing\")\n .option(\"--create <title>\", \"first create a page for a thing other pages only name, then enrich it (needs --as and --owner)\")\n .option(\"--as <type>\", \"type of the page --create makes, e.g. organization\")\n .option(\"--owner <agent>\", \"agent whose wiki gets the page --create makes\")\n .option(\"--json\", \"print the run as JSON\")\n .action(async (entities: string[], opts: { dir?: string; types: string; max: string; maxCost: string; model: string; force?: boolean; dryRun?: boolean; json?: boolean; create?: string; as?: string; owner?: string }) => {\n const { WikiHub } = await import(\"@/wiki/hub\")\n const { GraphCache } = await import(\"@/wiki/ontology/graph\")\n const { loadOntology } = await import(\"@/wiki/ontology/load\")\n const { loadRoster } = await import(\"@/wiki/ontology/roster\")\n const { ENRICH_TYPES, loadEnrichState, runEnrich, saveEnrichState } = await import(\"@/wiki/enrich\")\n const dir = wikiDir(opts.dir)\n const types = opts.types.split(\",\").map(s => s.trim()).filter(Boolean)\n const unknown = types.filter(t => !ENRICH_TYPES.includes(t))\n if (unknown.length) {\n console.error(chalk.red(` not an entity type this job handles: ${unknown.join(\", \")} (use ${ENRICH_TYPES.join(\", \")})`))\n process.exitCode = 1\n return\n }\n const max = Number(opts.max)\n if (!Number.isInteger(max) || max < 1) {\n console.error(chalk.red(\" --max must be a whole number of entities, 1 or more\"))\n process.exitCode = 1\n return\n }\n const maxCostUsd = Number(opts.maxCost)\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n console.error(chalk.red(\" --max-cost must be a positive number of dollars\"))\n process.exitCode = 1\n return\n }\n const hub = new WikiHub(dir, () => {})\n if (opts.create) {\n const { createEntityPage } = await import(\"@/wiki/enrich\")\n if (!opts.as || !ENRICH_TYPES.includes(opts.as) || !opts.owner) {\n console.error(chalk.red(` --create needs --as <${ENRICH_TYPES.join(\"|\")}> and --owner <agent>`))\n process.exitCode = 1\n return\n }\n if (hub.syncedFrom(opts.owner)) {\n console.error(chalk.red(` ${opts.owner}'s pages are copied from another node; pick an agent that runs here`))\n process.exitCode = 1\n return\n }\n if (opts.dryRun) {\n console.log(chalk.dim(` --dry-run: would create \"${opts.create}\" (${opts.as}) in ${opts.owner}'s wiki`))\n } else {\n const path = createEntityPage(hub, opts.create, opts.as, opts.owner, new Date().toISOString().slice(0, 10))\n console.log(path ? chalk.green(` created ${opts.owner}/${path}`) : chalk.dim(` ${opts.owner} already has a page titled \"${opts.create}\"`))\n }\n entities = [...entities, opts.create]\n if (!types.includes(opts.as)) types.push(opts.as)\n }\n const { ontology } = loadOntology(dir)\n const g = new GraphCache().get(hub, ontology, loadRoster(dir, hub.listAgents([]), ontology.agent_names))\n const state = loadEnrichState(dir)\n const run = await runEnrich(hub, g, claudeCall(opts.model), {\n types, only: entities, max, maxCostUsd, dryRun: !!opts.dryRun, force: !!opts.force, today: new Date().toISOString().slice(0, 10),\n save: s => saveEnrichState(dir, s),\n }, state)\n\n if (opts.json) {\n console.log(JSON.stringify(run, null, 2))\n return\n }\n for (const o of run.outcomes) {\n const mark = o.status === \"written\" ? chalk.green(\"✓\") : o.status === \"dry-run\" ? chalk.cyan(\"~\") : chalk.yellow(\"·\")\n console.log(` ${mark} ${o.title} ${chalk.dim(`${o.status} · ${o.page ?? \"no page\"} · overview ${o.overview ? \"yes\" : \"no\"} · ${o.statements} facts · ${o.links} links · $${o.costUsd.toFixed(3)}`)}`)\n for (const f of o.facts ?? []) console.log(chalk.dim(` fact: ${f.property} → ${f.value}${f.role ? ` (${f.role})` : \"\"} · source ${f.source}`))\n for (const d of o.dropped.slice(0, 6)) console.log(chalk.dim(` dropped: ${d}`))\n if (o.preview) console.log(chalk.dim(o.preview.split(\"\\n\").slice(0, 12).map(l => ` | ${l}`).join(\"\\n\")))\n }\n if (run.outcomes.length === 0) console.log(chalk.dim(\" nothing to do: no entity of these types changed since the last run (--force redoes them)\"))\n console.log(chalk.dim(` spent $${run.costUsd.toFixed(3)} of $${maxCostUsd}${run.capped ? \" · stopped at the cap\" : \"\"}`))\n })\n}\n"],"mappings":"AACA,OAAOA,MAAW,QAClB,OAAS,SAAAC,MAAa,gBACtB,OAAS,WAAAC,MAAe,OAQxB,IAAMC,EAAWC,GAAiBA,GAAOF,EAAQ,QAAQ,IAAI,EAAG,cAAc,EAMvE,SAASG,EAAWC,EAA+E,CACxG,MAAO,OAAOC,GAAW,CACvB,GAAM,CAAE,aAAAC,CAAa,EAAI,KAAM,QAAO,6BAAuB,EACvDC,EAAO,CAAC,KAAM,IAAK,kBAAmB,OAAQ,cAAe,IAAK,UAAWH,EACjF,UAAW,GAAI,sBAAuB,eAAgB,oBACtD,aAAc,2BAA4B,oBAAqB,GAAI,0BAA0B,EACzFI,EAAM,MAAM,IAAI,QAAgB,CAACC,EAAIC,IAAS,CAClD,IAAMC,EAAQZ,EAAM,SAAUQ,EAAM,CAAE,IAAKD,EAAa,EAAG,MAAO,CAAC,OAAQ,OAAQ,MAAM,CAAE,CAAC,EACxFM,EAAS,GACTC,EAAS,GACPC,EAAQ,WAAW,IAAMH,EAAM,KAAK,SAAS,EAAG,IAAO,EAC7DA,EAAM,OAAO,GAAG,OAAQI,GAAK,CAAEH,GAAUG,CAAE,CAAC,EAC5CJ,EAAM,OAAO,GAAG,OAAQI,GAAK,CAAEF,GAAUE,CAAE,CAAC,EAC5CJ,EAAM,GAAG,QAASK,GAAO,CAAE,aAAaF,CAAK,EAAGJ,EAAKM,CAAG,CAAE,CAAC,EAC3DL,EAAM,GAAG,QAASM,GAAQ,CACxB,aAAaH,CAAK,EACdG,IAAS,EAAGR,EAAGG,CAAM,EACpBF,EAAK,IAAI,MAAM,iBAAiBO,MAASJ,EAAO,KAAK,EAAE,MAAM,EAAG,GAAG,GAAG,CAAC,CAC9E,CAAC,EACDF,EAA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C,EAAM,IAAI,eAAe+C,EAAE,mBAAcA,EAAE,QAAQA,EAAE,KAAO,KAAKA,EAAE,QAAU,kBAAeA,EAAE,QAAQ,CAAC,EAClJ,QAAW9B,KAAK,EAAE,QAAQ,MAAM,EAAG,CAAC,EAAG,QAAQ,IAAIjB,EAAM,IAAI,kBAAkBiB,GAAG,CAAC,EAC/E,EAAE,SAAS,QAAQ,IAAIjB,EAAM,IAAI,EAAE,QAAQ,MAAM;AAAA,CAAI,EAAE,MAAM,EAAG,EAAE,EAAE,IAAIgD,GAAK,WAAWA,GAAG,EAAE,KAAK;AAAA,CAAI,CAAC,CAAC,EAE1GH,EAAI,SAAS,SAAW,GAAG,QAAQ,IAAI7C,EAAM,IAAI,4FAA4F,CAAC,EAClJ,QAAQ,IAAIA,EAAM,IAAI,YAAY6C,EAAI,QAAQ,QAAQ,CAAC,SAASP,IAAaO,EAAI,OAAS,2BAA0B,IAAI,CAAC,CAC3H,CAAC,CACL","names":["chalk","spawn","resolve","wikiDir","dir","claudeCall","model","prompt","claudeCliEnv","args","out","ok","fail","child","stdout","stderr","timer","d","err","code","envelope","registerWikiEnrich","wiki","entities","opts","WikiHub","GraphCache","loadOntology","loadRoster","ENRICH_TYPES","loadEnrichState","runEnrich","saveEnrichState","types","s","unknown","t","max","maxCostUsd","hub","createEntityPage","path","ontology","g","state","run","mark","f","l"]}
@@ -0,0 +1,105 @@
1
+ import{b as I}from"./chunk-KEXBEUSU.js";import{a as P}from"./chunk-RGZARSHV.js";import{a as E,b as R,c as j,d as M,e as T,j as O}from"./chunk-ERULJ2ZL.js";import{y as L,z as U}from"./chunk-4XMALK7X.js";import{c as _,d as C}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as w,appendFileSync as J,existsSync as b,mkdirSync as x,readdirSync as D,statSync as K}from"fs";import{resolve as u,join as V,relative as k,dirname as F}from"path";U();function N(v){return P.includes(v)}function Y(v){if(!v)return;let t;try{t=JSON.parse(v)}catch{return}if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="object"&&r!==null&&typeof r.property=="string"&&r.property!==""&&typeof r.value=="string"&&r.value!=="");return e.length?e:void 0}function z(v,t){let e=i=>{let n=/^(.*Z)(?:-(\d+))?\.md$/.exec(i);return n?[n[1],n[2]?Number(n[2]):0]:[i,0]},[r,a]=e(v),[o,s]=e(t);return r<o?-1:r>o?1:a-s}var B=class{baseDir;rawDir;log;constructor(t=u(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=u(t,"raw/entries"),this.log=e,x(this.rawDir,{recursive:!0}),x(u(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=u(this.rawDir,e),a=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&a.push(`context: ${t.sourceContext}`),t.meta)for(let[o,s]of Object.entries(t.meta))a.push(`${o}: ${JSON.stringify(s)}`);return a.push("---","",t.content),w(r,a.join(`
2
+ `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!b(this.rawDir))return[];let e=new Set(t),r=[];for(let a of D(this.rawDir)){let o=a.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(o))continue;let s=this.parseEntry($(u(this.rawDir,a),"utf-8"),a);s&&r.push(s)}return r}listEntries(t){if(!b(this.rawDir))return[];let e=D(this.rawDir).filter(a=>a.endsWith(".md")).sort(),r=[];for(let a of e){let o=$(u(this.rawDir,a),"utf-8"),s=this.parseEntry(o,a);s&&(t?.agentId&&s.agentId!==t.agentId||t?.after&&s.date<t.after||t?.before&&s.date>t.before||r.push(s))}return r}parseEntry(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let a=r[1],o=r[2].trim(),s=c=>a.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),n={};for(let c of a.split(`
3
+ `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{n[l[1]]=JSON.parse(l[2])}catch{n[l[1]]=l[2].trim()}}return{id:s("id")||e.replace(".md",""),date:s("date"),agentId:s("agent"),source:s("source"),sourceContext:s("context")||void 0,content:o,meta:Object.keys(n).length>0?n:void 0}}writeArticle(t,e,r,a){let o=this.readArticle(t);if(o&&!this.canWrite(o.meta,a))return this.log(`Permission denied: "${a}" cannot write "${t}" (owner: ${o.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=u(this.baseDir,t);o&&this.saveVersion(t,s),x(F(s),{recursive:!0});let i=["---",`title: "${e.title}"`];e.type&&i.push(`type: ${e.type}`),e.related?.length&&i.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&i.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&i.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&i.push(`class: ${e.class}`),e.importance&&i.push(`importance: ${e.importance}`),e.importanceProposed&&i.push(`importance_proposed: ${e.importanceProposed}`),e.date&&i.push(`date: ${e.date}`),e.rolledUpInto&&i.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&i.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&i.push(`statements: ${JSON.stringify(e.statements)}`),i.push("---","",r),w(s,i.join(`
4
+ `));let n=o?"update":"create";return this.appendLog(n,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${a} at ${t}`),!0}saveVersion(t,e){try{if(!b(e))return;let r=$(e,"utf-8"),a=new Date().toISOString().replace(/[:.]/g,"-"),o=u(this.baseDir,"_versions",t.replace(/\.md$/,""));x(o,{recursive:!0});for(let s=0;;s++)try{w(u(o,`${s?`${a}-${s}`:a}.md`),r,{flag:"wx"});return}catch(i){if(i.code!=="EEXIST")throw i}}catch{}}getVersions(t){let e=u(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!b(e))return[];try{return D(e).filter(r=>r.endsWith(".md")).sort(z).reverse().map(r=>({timestamp:r.replace(/\.md$/,"").replace(/-/g,(a,o)=>o<19?o===10?"T":o===13||o===16?":":"-":a),path:u(e,r)}))}catch{return[]}}restoreVersion(t,e){let r=this.getVersions(t),a=r.find(o=>o.timestamp===e)??r.find(o=>o.timestamp.startsWith(e));if(!a)return!1;try{let o=$(a.path,"utf-8"),s=u(this.baseDir,t);return this.saveVersion(t,s),w(s,o),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=u(this.baseDir,t);if(!b(e))return null;let r=$(e,"utf-8");return this.parseArticle(r,t)}readArticleAs(t,e){let r=this.readArticle(t);return!r||!this.canRead(r.meta,e)?null:r}parseArticle(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let a=r[1],o=r[2].trim(),s=W=>a.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=W=>{let A=a.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return A?[...A[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},n=s("type")||s("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(n)?n:void 0,g=i("tags").filter((W,A,S)=>W&&S.indexOf(W)===A),d=i("related"),p=i("graph_path"),m=i("aliases"),h=s("importance"),f=s("importance_proposed"),y=s("date");return{meta:{title:s("title"),type:l,related:d.length?d:void 0,tags:g,owner:s("owner"),access:s("access")||"public",sharedWith:i("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:i("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(s("class"))?s("class"):void 0,importance:N(h)?h:void 0,importanceProposed:N(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:s("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:Y(s("statements"))},content:o,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],r=[];this.walkDir(this.baseDir,(n,c)=>{if(!n.endsWith(".md"))return;let l=k(this.baseDir,n);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),r.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let a=r.join("|"),o=t??"\0all",s=this.listCache.get(o);if(s&&s.signature===a)return s.articles.slice();let i=[];for(let n of e){let c=this.readArticle(n);c&&(t===null||this.canRead(c.meta,t))&&i.push(c)}return this.listCache.set(o,{signature:a,articles:i}),i.slice()}search(t,e,r=10){let a=t.toLowerCase(),o=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||o.push(m)}),o.length===0)return[];let s=o.map(d=>d.content),i=u(this.baseDir,"_bm25_cache.json"),n=C(s,i),c=_(t,n),l=new Map(c.map(d=>[d.docIndex,d.score]));return o.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(a)&&(m+=10),d.meta.tags?.some(h=>h.toLowerCase().includes(a))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,r).map(d=>d.article)}async findRelevantReranked(t,e,r=10,a={}){let o=Math.max(r,a.shortlist??R),s=this.findRelevant(t,e,o);if(s.length<2)return s.slice(0,r);let i=s.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),n=await L(E,j({query:t,candidates:i,excerptChars:a.excerptChars}),M(i),{incumbent:{best:i[0].id},features:{agent:e??"unknown"}});return!n||n.mode!=="active"?s.slice(0,r):T(n.answers,i).ranked.map(l=>s[Number(l.slice(1))]).filter(l=>!!l).slice(0,r)}findRelevant(t,e,r=3,a,o={graph:.6,bm25:.4}){let s=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=k(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||s.push(y)}),s.length===0)return[];let i=s.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),n=u(this.baseDir,"_bm25_relevance_cache.json"),c=C(i,n),l=_(t,c),g=l.reduce((h,f)=>Math.max(h,f.score),0)||1,d=new Map(l.map(h=>[h.docIndex,h.score/g])),p=!!(a&&a.length>0);return s.map((h,f)=>{let y=d.get(f)??0,W=0;p&&h.meta.graphPath?.length&&(W=O(a,h.meta.graphPath));let A=p?o.graph*W+o.bm25*y:y;return{article:h,score:A}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,r).map(h=>h.article)}buildContext(t,e=4e3){if(t.length===0)return"";let r=["[Wiki Knowledge]"],a=0;for(let o of t){let s=`
5
+ ## ${o.meta.title} [${(o.meta.tags||[]).slice(0,3).join(", ")}]`,i=o.content.length>600?o.content.slice(0,600)+"...":o.content,n=s+`
6
+ `+i;if(a+n.length>e)break;r.push(n),a+=n.length}return r.push(`
7
+ [End Wiki Knowledge]`),r.join(`
8
+ `)}rebuildIndex(){let t=[],e=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);if(!n)return;let c=n.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let g of c){let d=g.replace(/\[\[|\]\]/g,"");e.set(d,(e.get(d)||0)+1)}let l=[n.meta.title.toLowerCase()];n.meta.tags&&l.push(...n.meta.tags.map(g=>g.toLowerCase())),t.push({path:i,title:n.meta.title,type:n.meta.type,related:n.meta.related,tags:n.meta.tags||[],owner:n.meta.owner,access:n.meta.access,sharedWith:n.meta.sharedWith,aliases:l,backlinks:e.get(n.meta.title)||0,sources:n.meta.sources,lastUpdated:n.meta.lastUpdated,graphPath:n.meta.graphPath})});let r={articles:t,lastRebuilt:new Date().toISOString()};w(u(this.baseDir,"_index.json"),JSON.stringify(r,null,2)),this.writeCatalog(t,r.lastRebuilt);let a=["# Wiki Index","",`Last rebuilt: ${r.lastRebuilt}`,""],o=new Map;for(let s of t){let i=s.access||"public",n=o.get(i)||[];n.push(s),o.set(i,n)}for(let[s,i]of Array.from(o.entries()).sort()){a.push(`## ${s}`,"");for(let n of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=n.type?` [${n.type}]`:"";a.push(`- [${n.title}](${n.path})${c} \u2014 owner: ${n.owner}`)}a.push("")}return w(u(this.baseDir,"WIKI.md"),a.join(`
9
+ `)),this.log(`Index rebuilt: ${t.length} articles`),this.appendLog("rebuild-index",`${t.length} articles indexed`),r}writeCatalog(t,e){let r=["person","project","place","concept","event","decision","pattern","untyped"],a={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},o=new Map;for(let i of t){let n=i.type||"untyped",c=o.get(n)||[];c.push(i),o.set(n,c)}let s=["# Wiki Content Catalog","",`_Last rebuilt: ${e}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of r){let n=o.get(i);if(!(!n||n.length===0)){s.push(a[i]||`## ${i}`,"");for(let c of n.sort((l,g)=>l.title.localeCompare(g.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",g=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";s.push(`- [${c.title}](${c.path})${l}${g}`)}s.push("")}}w(u(this.baseDir,"_index.md"),s.join(`
10
+ `))}stats(){let t=0,e={},r={},a={};this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let n=this.readArticle(i);if(n){t++;for(let c of n.meta.tags||[])e[c]=(e[c]||0)+1;r[n.meta.access]=(r[n.meta.access]||0)+1,a[n.meta.owner]=(a[n.meta.owner]||0)+1}});let o=b(this.rawDir)?D(this.rawDir).filter(s=>s.endsWith(".md")).length:0;return{totalArticles:t,totalEntries:o,articlesByType:e,articlesByAccess:r,articlesByOwner:a}}appendLog(t,e){let r=u(this.baseDir,"log.md"),o=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${t} | ${e}
11
+
12
+ `;b(r)||w(r,`# Wiki Log
13
+
14
+ Chronological record of all wiki operations.
15
+
16
+ `),J(r,o)}getLog(t=20){let e=u(this.baseDir,"log.md");return b(e)?$(e,"utf-8").split(/^## /m).filter(o=>o.startsWith("[")).slice(-t).map(o=>o.trim()):[]}ensureSchema(){let t=u(this.baseDir,"_schema.md");if(b(t))return;w(t,`# Wiki Schema
17
+
18
+ A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
19
+ structure emerges from data. The wiki is a compounding artifact.
20
+
21
+ ## Structure
22
+
23
+ \`\`\`
24
+ wiki/
25
+ _schema.md # This file
26
+ worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
27
+ raw/entries/ # Immutable raw sources (conversations, imports, anything)
28
+ [LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
29
+ \`\`\`
30
+
31
+ The LLM decides how to organize articles. You describe YOUR world in worldview.md.
32
+
33
+ ## Article Format
34
+
35
+ \`\`\`yaml
36
+ ---
37
+ title: "Staging Deployment Process"
38
+ tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
39
+ owner: devops-agent
40
+ access: public
41
+ created: 2026-04-06
42
+ last_updated: 2026-04-06
43
+ sources: ["entry-id-1", "entry-id-2"]
44
+ ---
45
+
46
+ Article content with [[wikilinks]] and section tags.
47
+
48
+ ## Deploy Steps
49
+ <!-- tags: process, runbook, staging -->
50
+ Content specific to this section...
51
+ \`\`\`
52
+
53
+ ## Tags
54
+
55
+ Tags are the primary context-narrowing mechanism. The more tags, the better.
56
+
57
+ Tag aggressively:
58
+ - **Who**: people, agents, teams involved
59
+ - **What**: project, client, topic, technology
60
+ - **When**: dates, periods, milestones
61
+ - **Where**: server, environment, channel
62
+ - **How**: process, decision, pattern
63
+ - **Your terms**: whatever vocabulary makes sense in YOUR world
64
+
65
+ Section tags (\`<!-- tags: ... -->\`) let different parts of an article
66
+ match different queries. A deploy article might have sections tagged
67
+ "runbook" and "incident" separately.
68
+
69
+ ## Operations
70
+
71
+ ### Absorb
72
+ Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
73
+ Also identify GAPS: "We mention X but have no article for it."
74
+
75
+ ### Query
76
+ Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
77
+ If agent is working on a specific project, only send content tagged for that project.
78
+
79
+ ### Lint
80
+ Check for: orphan articles, broken [[wikilinks]], untagged articles,
81
+ articles over 100 lines that should split, mentioned-but-missing topics.
82
+
83
+ ## Worldview
84
+
85
+ Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
86
+ mental model. The LLM reads it during absorb to understand where things go.
87
+
88
+ Example worldview.md:
89
+ \`\`\`
90
+ I'm the founder of Acme Corp.
91
+ We build software products.
92
+ Our agents: Marketing Bot, DevOps Bot, Coordinator.
93
+ Clients: ClientA (enterprise), ClientB (startup).
94
+ Infrastructure: local dev machine, cloud server.
95
+ We use GitLab for version control.
96
+ \`\`\`
97
+ `),this.log("Created _schema.md")}extractWikilinks(t){return(t.match(/\[\[([^\]]+)\]\]/g)||[]).map(r=>r.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let t={};return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=k(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_")||r==="WIKI.md"||r==="log.md")return;let a=$(e,"utf-8"),o=this.extractWikilinks(a);for(let s of o)t[s]||(t[s]=[]),t[s].push(r)}),w(u(this.baseDir,"_backlinks.json"),JSON.stringify(t,null,2)),t}getBacklinks(t){let e=u(this.baseDir,"_backlinks.json");if(!b(e))return[];try{return JSON.parse($(e,"utf-8"))[t]||[]}catch{return[]}}findByTags(t,e,r=10){let a=t.map(s=>s.toLowerCase()),o=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);if(!n||e&&!this.canRead(n.meta,e))return;let c=(n.meta.tags||[]).map(p=>p.toLowerCase()),l=(n.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(p=>p.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(m=>m.trim().toLowerCase())),g=[...c,...l],d=a.filter(p=>g.includes(p)).length;d>0&&o.push({article:n,score:d})}),o.sort((s,i)=>i.score-s.score).slice(0,r).map(s=>s.article)}getAllTags(){let t=new Map;return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=k(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_"))return;let a=this.readArticle(r);if(a?.meta.tags)for(let o of a.meta.tags)t.set(o,(t.get(o)||0)+1)}),t}getWorldview(){let t=u(this.baseDir,"worldview.md");return b(t)?$(t,"utf-8"):null}setWorldview(t){w(u(this.baseDir,"worldview.md"),t),this.appendLog("worldview","Updated worldview")}lint(){let t=[],e=new Set,r=new Map,a=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let n=this.readArticle(i);if(!n)return;e.add(n.meta.title),a.set(n.meta.title,i);let c=this.extractWikilinks(n.content);r.set(i,c);let l=n.content.split(`
98
+ `).length;l>100&&t.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),n.meta.sources?.length||t.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&n.content.trim().length<100&&t.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[s,i]of r)for(let n of i)e.has(n)||t.push({type:"broken-link",article:s,message:`[[${n}]] \u2014 target article not found`});let o=this.buildBacklinks();for(let[s,i]of a)(!o[s]||o[s].length===0)&&t.push({type:"orphan",article:i,message:`No other articles link to "${s}"`});return this.appendLog("lint",`Found ${t.length} issues`),t}getUnabsorbedEntries(){let t=new Set;return this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let a=k(this.baseDir,r);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(o?.meta.sources)for(let s of o.meta.sources)t.add(s)}),this.listEntries().filter(r=>!t.has(r.id))}buildAbsorbPrompt(t=20){let e=this.getUnabsorbedEntries().slice(0,t);if(e.length===0)return null;let r=e.map(a=>`[${a.date} ${a.agentId} via ${a.source}] ${a.content.slice(0,200)}`).join(`
99
+
100
+ `);return`/wiki absorb
101
+
102
+ There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
+
104
+ ${r}`}walkDir(t,e){if(b(t))for(let r of D(t)){let a=V(t,r),o=K(a);o.isDirectory()?this.walkDir(a,e):e(a,o)}}};export{B as a};
105
+ //# sourceMappingURL=chunk-NY7NHGVT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/store.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync, type Stats } from \"fs\"\nimport { resolve, join, relative, dirname } from \"path\"\nimport { isWikiArticleType } from \"./types\"\nimport type { WikiArticle, WikiArticleMeta, WikiEntry, WikiIndex, WikiAccess } from \"./types\"\nimport { buildIndex, buildIndexCached, scoreAll } from \"../memory/bm25\"\nimport { askSeat } from \"../decisions/seat\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"../decisions/seats/wiki-rerank\"\nimport { ancestryScore as ancestryOf } from \"@/graph\"\nimport { IMPORTANCE_LEVELS, type Importance, type WikiStatement } from \"./ontology/types\"\n\nfunction isImportance(s: string): s is Importance {\n return (IMPORTANCE_LEVELS as readonly string[]).includes(s)\n}\n\n/** Read the one-line JSON `statements:` value. A statement without a\n * property or value is dropped; a line that is not JSON drops them all,\n * since a half-read list would show wrong facts as complete. */\nexport function parseStatements(line: string): WikiStatement[] | undefined {\n if (!line) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n return undefined // not JSON: treat the page as having no statements\n }\n if (!Array.isArray(parsed)) return undefined\n const out = parsed.filter((s): s is WikiStatement =>\n typeof s === \"object\" && s !== null\n && typeof (s as WikiStatement).property === \"string\" && (s as WikiStatement).property !== \"\"\n && typeof (s as WikiStatement).value === \"string\" && (s as WikiStatement).value !== \"\")\n return out.length ? out : undefined\n}\n\n// --- Wiki Store: filesystem-based knowledge base with permissions ---\n//\n// Structure:\n// .agentx/wiki/\n// _index.md # Master index with aliases\n// _backlinks.json # Reverse link index\n// raw/entries/ # One .md per ingested entry\n// {directories}/ # Articles organized by type\n//\n// Permission model:\n// - private: only owner agent reads/writes\n// - shared: owner writes, listed agents read\n// - public: owner writes, all agents read\n\n/**\n * Order version file names oldest first: by timestamp, then by the counter\n * suffix that saveVersion adds when two writes share a millisecond\n * (`<ts>.md` < `<ts>-1.md` < `<ts>-2.md` < ... < `<ts>-10.md`).\n */\nfunction compareVersionNames(a: string, b: string): number {\n const split = (f: string): [string, number] => {\n const m = /^(.*Z)(?:-(\\d+))?\\.md$/.exec(f)\n return m ? [m[1], m[2] ? Number(m[2]) : 0] : [f, 0]\n }\n const [ta, na] = split(a)\n const [tb, nb] = split(b)\n return ta < tb ? -1 : ta > tb ? 1 : na - nb\n}\n\nexport class WikiStore {\n readonly baseDir: string\n private rawDir: string\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki]\"),\n ) {\n this.baseDir = baseDir\n this.rawDir = resolve(baseDir, \"raw/entries\")\n this.log = log\n\n mkdirSync(this.rawDir, { recursive: true })\n mkdirSync(resolve(baseDir, \"raw\"), { recursive: true })\n\n // Initialize schema if missing\n this.ensureSchema()\n }\n\n // --- Permission checks ---\n\n /**\n * Check if an agent can read an article.\n */\n canRead(article: WikiArticleMeta, agentId?: string): boolean {\n if (article.access === \"public\") return true\n if (!agentId) return false\n if (article.owner === agentId) return true\n if (article.access === \"shared\" && article.sharedWith?.includes(agentId)) return true\n return false\n }\n\n /**\n * Check if an agent can write an article.\n */\n canWrite(article: WikiArticleMeta, agentId: string): boolean {\n return article.owner === agentId\n }\n\n // --- Raw entries (ingestion) ---\n\n /**\n * Add a raw entry (from a conversation, cron result, etc.)\n */\n addEntry(entry: WikiEntry): string {\n const filename = `${entry.date}_${entry.id}.md`\n const filepath = resolve(this.rawDir, filename)\n\n const frontmatter = [\n \"---\",\n `id: ${entry.id}`,\n `date: ${entry.date}`,\n `agent: ${entry.agentId}`,\n `source: ${entry.source}`,\n ]\n if (entry.sourceContext) frontmatter.push(`context: ${entry.sourceContext}`)\n if (entry.meta) {\n for (const [k, v] of Object.entries(entry.meta)) {\n frontmatter.push(`${k}: ${JSON.stringify(v)}`)\n }\n }\n frontmatter.push(\"---\", \"\", entry.content)\n\n writeFileSync(filepath, frontmatter.join(\"\\n\"))\n this.appendLog(\"ingest\", `${entry.id} from ${entry.agentId} via ${entry.source}`)\n return filename\n }\n\n /** Read only the named entries. Files are `<date>_<id>.md`, so one\n * directory listing finds them without parsing the rest. */\n readEntries(ids: string[]): WikiEntry[] {\n if (ids.length === 0 || !existsSync(this.rawDir)) return []\n const wanted = new Set(ids)\n const out: WikiEntry[] = []\n for (const file of readdirSync(this.rawDir)) {\n const id = file.replace(/\\.md$/, \"\").replace(/^\\d{4}-\\d{2}-\\d{2}_/, \"\")\n if (!wanted.has(id)) continue\n const entry = this.parseEntry(readFileSync(resolve(this.rawDir, file), \"utf-8\"), file)\n if (entry) out.push(entry)\n }\n return out\n }\n\n /**\n * List raw entries, optionally filtered by agent or date range.\n */\n listEntries(filter?: { agentId?: string; after?: string; before?: string }): WikiEntry[] {\n if (!existsSync(this.rawDir)) return []\n\n const files = readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).sort()\n const entries: WikiEntry[] = []\n\n for (const file of files) {\n const content = readFileSync(resolve(this.rawDir, file), \"utf-8\")\n const entry = this.parseEntry(content, file)\n if (!entry) continue\n\n if (filter?.agentId && entry.agentId !== filter.agentId) continue\n if (filter?.after && entry.date < filter.after) continue\n if (filter?.before && entry.date > filter.before) continue\n\n entries.push(entry)\n }\n\n return entries\n }\n\n private parseEntry(content: string, filename: string): WikiEntry | null {\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const body = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim() || \"\"\n }\n\n // Everything addEntry wrote that is not one of the five named keys is\n // `meta`, JSON-encoded one key per line. Dropping it here is what made\n // graphPath 0%: the capture path stamps intentPath onto every entry,\n // `wiki absorb` reads entry.meta.intentPath to propagate it onto the\n // article, and this parser never returned a meta at all — so absorb\n // always fell through to a fingerprint lookup its own comment calls\n // unreliable, and the retrieval scorer multiplied the graph weight\n // (0.6 of the hybrid score) by zero for every article ever compiled.\n const KNOWN = new Set([\"id\", \"date\", \"agent\", \"source\", \"context\"])\n const meta: Record<string, unknown> = {}\n for (const line of fm.split(\"\\n\")) {\n const m = line.match(/^(\\w+):\\s*(.+)$/)\n if (!m || KNOWN.has(m[1])) continue\n try {\n meta[m[1]] = JSON.parse(m[2])\n } catch {\n meta[m[1]] = m[2].trim()\n }\n }\n\n return {\n id: get(\"id\") || filename.replace(\".md\", \"\"),\n date: get(\"date\"),\n agentId: get(\"agent\"),\n source: get(\"source\"),\n sourceContext: get(\"context\") || undefined,\n content: body,\n meta: Object.keys(meta).length > 0 ? meta : undefined,\n }\n }\n\n // --- Articles (compiled knowledge) ---\n\n /**\n * Write or update a wiki article.\n */\n writeArticle(\n path: string,\n meta: WikiArticleMeta,\n content: string,\n agentId: string,\n ): boolean {\n // LLM picks the path. We just write the file.\n const existing = this.readArticle(path)\n if (existing && !this.canWrite(existing.meta, agentId)) {\n this.log(`Permission denied: \"${agentId}\" cannot write \"${path}\" (owner: ${existing.meta.owner})`)\n return false\n }\n\n // Drop invalid `type` at write time. The parser already rejects invalid\n // values on read (returns type=undefined), so silently serialising a\n // stray value would cause the round-trip to look fine but the article\n // to render as \"untyped\" in the catalog. Log + drop beats surprise.\n if (meta.type && !isWikiArticleType(meta.type)) {\n this.log(`Dropping invalid article type \"${meta.type}\" for \"${path}\" — enum is [person, project, place, concept, event, decision, pattern]`)\n meta = { ...meta, type: undefined }\n }\n\n const fullPath = resolve(this.baseDir, path)\n\n // Version the previous content before overwriting (immutable history)\n if (existing) {\n this.saveVersion(path, fullPath)\n }\n\n mkdirSync(dirname(fullPath), { recursive: true })\n\n const frontmatter = [\n \"---\",\n `title: \"${meta.title}\"`,\n ]\n if (meta.type) frontmatter.push(`type: ${meta.type}`)\n if (meta.related?.length) {\n frontmatter.push(`related: [${meta.related.map(t => `\"${t}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `tags: [${(meta.tags || []).map(t => `\"${t}\"`).join(\", \")}]`,\n `owner: ${meta.owner}`,\n `access: ${meta.access}`,\n )\n if (meta.sharedWith?.length) {\n frontmatter.push(`shared_with: [${meta.sharedWith.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `created: ${meta.created}`,\n `last_updated: ${meta.lastUpdated}`,\n `sources: [${meta.sources.map(s => `\"${s}\"`).join(\", \")}]`,\n )\n if (meta.graphPath?.length) {\n frontmatter.push(`graph_path: [${meta.graphPath.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n // Ontology fields (#811). Statements go on one line as JSON, which\n // is also valid YAML, so the line-based reader below stays simple.\n if (meta.class) frontmatter.push(`class: ${meta.class}`)\n if (meta.importance) frontmatter.push(`importance: ${meta.importance}`)\n if (meta.importanceProposed) frontmatter.push(`importance_proposed: ${meta.importanceProposed}`)\n if (meta.date) frontmatter.push(`date: ${meta.date}`)\n if (meta.rolledUpInto) frontmatter.push(`rolled_up_into: ${JSON.stringify(meta.rolledUpInto)}`)\n if (meta.aliases?.length) frontmatter.push(`aliases: ${JSON.stringify(meta.aliases)}`)\n if (meta.statements?.length) frontmatter.push(`statements: ${JSON.stringify(meta.statements)}`)\n frontmatter.push(\"---\", \"\", content)\n\n writeFileSync(fullPath, frontmatter.join(\"\\n\"))\n const action = existing ? \"update\" : \"create\"\n this.appendLog(action, `${meta.title} [${(meta.tags || []).slice(0, 5).join(\", \")}] by ${agentId} at ${path}`)\n return true\n }\n\n // --- Article Versioning ---\n\n /**\n * Save current article content as an immutable version before overwriting.\n * Versions stored in _versions/{article-path}/{timestamp}.md\n */\n private saveVersion(articlePath: string, fullPath: string): void {\n try {\n if (!existsSync(fullPath)) return\n const content = readFileSync(fullPath, \"utf-8\")\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\")\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n mkdirSync(versionDir, { recursive: true })\n // Two writes inside one millisecond share a timestamp: the later one\n // gets a counter suffix (`<ts>-1.md`, ...) instead of overwriting.\n for (let n = 0; ; n++) {\n try {\n writeFileSync(resolve(versionDir, `${n ? `${ts}-${n}` : ts}.md`), content, { flag: \"wx\" })\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err\n }\n }\n } catch {\n // Version save is best-effort\n }\n }\n\n /**\n * List all versions of an article (newest first).\n */\n getVersions(articlePath: string): Array<{ timestamp: string; path: string }> {\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n if (!existsSync(versionDir)) return []\n\n try {\n return readdirSync(versionDir)\n .filter(f => f.endsWith(\".md\"))\n .sort(compareVersionNames)\n .reverse()\n .map(f => ({\n timestamp: f.replace(/\\.md$/, \"\").replace(/-/g, (m, i) => i < 19 ? (i === 10 ? \"T\" : i === 13 || i === 16 ? \":\" : \"-\") : m),\n path: resolve(versionDir, f),\n }))\n } catch {\n return []\n }\n }\n\n /**\n * Restore a specific version of an article.\n */\n restoreVersion(articlePath: string, versionTimestamp: string): boolean {\n const versions = this.getVersions(articlePath)\n const version = versions.find(v => v.timestamp === versionTimestamp)\n ?? versions.find(v => v.timestamp.startsWith(versionTimestamp))\n if (!version) return false\n\n try {\n const content = readFileSync(version.path, \"utf-8\")\n const fullPath = resolve(this.baseDir, articlePath)\n // Save current as a version too before restoring\n this.saveVersion(articlePath, fullPath)\n writeFileSync(fullPath, content)\n this.appendLog(\"restore\", `${articlePath} restored to ${versionTimestamp}`)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Read an article. Returns null if not found.\n */\n readArticle(path: string): WikiArticle | null {\n const fullPath = resolve(this.baseDir, path)\n if (!existsSync(fullPath)) return null\n\n const raw = readFileSync(fullPath, \"utf-8\")\n return this.parseArticle(raw, path)\n }\n\n /**\n * Read an article with permission check.\n */\n readArticleAs(path: string, agentId: string): WikiArticle | null {\n const article = this.readArticle(path)\n if (!article) return null\n if (!this.canRead(article.meta, agentId)) return null\n return article\n }\n\n private parseArticle(raw: string, path: string): WikiArticle | null {\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const content = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim().replace(/^\"(.*)\"$/, \"$1\") || \"\"\n }\n\n const getArray = (key: string): string[] => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*\\\\[(.*)\\\\]$`, \"m\"))\n if (!m) return []\n // Quoted items may hold commas — related titles often do, e.g.\n // \"Reviewed: NOT READY, Then READY\". Unquoted legacy items may not.\n // Items are written unescaped, so a quoted item may also hold quotes\n // (\"Carbon \"12 M\" Fix\"): it ends only at a quote before a comma or the end.\n return [...m[1].matchAll(/\\s*(?:\"(.*?)\"(?=\\s*(?:,|$))|([^,]+))/g)]\n .map(x => (x[1] ?? x[2]).trim())\n .filter(Boolean)\n }\n\n // `type` and `kind` are the new structural spine; no longer stuffed into tags.\n // Legacy articles may have a `kind:` field; we promote it to `type` on read so\n // the migration (Phase 2) can patch it in place.\n const rawType = get(\"type\") || get(\"kind\")\n const validTypes = new Set([\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\",\n ])\n const type = validTypes.has(rawType) ? (rawType as WikiArticleMeta[\"type\"]) : undefined\n\n const tags = getArray(\"tags\").filter((v, i, a) => v && a.indexOf(v) === i)\n const related = getArray(\"related\")\n const graphPath = getArray(\"graph_path\")\n const aliases = getArray(\"aliases\")\n const importance = get(\"importance\")\n const importanceProposed = get(\"importance_proposed\")\n const date = get(\"date\")\n return {\n meta: {\n title: get(\"title\"),\n type,\n related: related.length ? related : undefined,\n tags,\n owner: get(\"owner\"),\n access: (get(\"access\") as WikiAccess) || \"public\",\n sharedWith: getArray(\"shared_with\"),\n created: get(\"created\"),\n lastUpdated: get(\"last_updated\"),\n sources: getArray(\"sources\"),\n graphPath: graphPath.length ? graphPath : undefined,\n class: /^[a-z][a-z0-9_]*$/.test(get(\"class\")) ? get(\"class\") : undefined,\n importance: isImportance(importance) ? importance : undefined,\n importanceProposed: isImportance(importanceProposed) ? importanceProposed : undefined,\n date: /^\\d{4}-\\d{2}-\\d{2}/.test(date) ? date.slice(0, 10) : undefined,\n rolledUpInto: get(\"rolled_up_into\") || undefined,\n aliases: aliases.length ? aliases : undefined,\n statements: parseStatements(get(\"statements\")),\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n /** Catalog per agent, valid while no article file changed. The walk is\n * repeated (names, mtimes, sizes) but the frontmatter parse of every\n * article is not; on a wiki of ten thousand files that parse was the\n * cost of every fresh session. */\n private listCache = new Map<string, { signature: string; articles: WikiArticle[] }>()\n\n listArticles(agentId: string): WikiArticle[] {\n return this.listCached(agentId)\n }\n\n /** Every article whatever its access, for the owner's own views. */\n listAllArticles(): WikiArticle[] {\n return this.listCached(null)\n }\n\n private listCached(agentId: string | null): WikiArticle[] {\n const relPaths: string[] = []\n const sig: string[] = []\n this.walkDir(this.baseDir, (filePath, stat) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n relPaths.push(relPath)\n sig.push(`${relPath}:${stat?.mtimeMs ?? \"?\"}:${stat?.size ?? \"?\"}`)\n })\n const signature = sig.join(\"|\")\n const key = agentId ?? \"\\u0000all\"\n const hit = this.listCache.get(key)\n if (hit && hit.signature === signature) return hit.articles.slice()\n\n const articles: WikiArticle[] = []\n for (const relPath of relPaths) {\n const article = this.readArticle(relPath)\n if (article && (agentId === null || this.canRead(article.meta, agentId))) {\n articles.push(article)\n }\n }\n this.listCache.set(key, { signature, articles })\n return articles.slice()\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * findRelevant, then re-ranked by the wiki-rerank seat.\n *\n * Recall comes from findRelevant rather than search() because\n * findRelevant is the function everything actually calls — search()\n * turned out to have no callers at all. Additive on purpose: the\n * synchronous findRelevant is untouched and its existing callers stay\n * as they are. Measured on the 12-query eval against this\n * wiki, re-ranking moves R@1 from 33.3% to 50.0% and R@3 from 41.7% to\n * 66.7%, for about $0.0005 and 550ms a query.\n *\n * Fail-open in every direction. Seat off, backend down, no key, fewer\n * than two candidates — all return BM25's own order, which is what the\n * caller would have got anyway.\n *\n * Note what this cannot do: it only reorders what BM25 shortlisted. In\n * the eval R@3 sat exactly on that ceiling, so every remaining miss was\n * an article BM25 never returned. Widening the shortlist does not fix\n * that — past 30 the extra candidates measurably diluted the ranking.\n */\n async findRelevantReranked(\n query: string,\n agentId?: string,\n maxResults = 10,\n opts: { shortlist?: number; excerptChars?: number } = {},\n ): Promise<WikiArticle[]> {\n const shortlist = Math.max(maxResults, opts.shortlist ?? DEFAULT_SHORTLIST)\n const pool = this.findRelevant(query, agentId, shortlist)\n if (pool.length < 2) return pool.slice(0, maxResults)\n\n const candidates: RerankCandidate[] = pool.map((article, i) => ({\n // Index, not title: titles are not unique across a wiki and a\n // Choice needs distinct keys.\n id: `c${i}`,\n title: article.meta.title || `(untitled ${i})`,\n tags: article.meta.tags,\n excerpt: article.content,\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query, candidates, excerptChars: opts.excerptChars }),\n rerankQuestions(candidates),\n { incumbent: { best: candidates[0].id }, features: { agent: agentId ?? \"unknown\" } },\n )\n if (!result || result.mode !== \"active\") return pool.slice(0, maxResults)\n\n const ranking = toRanking(result.answers as never, candidates)\n return ranking.ranked\n .map((id) => pool[Number(id.slice(1))])\n .filter((a): a is WikiArticle => Boolean(a))\n .slice(0, maxResults)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n graphPath: article.meta.graphPath,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string, stat?: Stats) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full, stat)\n }\n }\n }\n}\n"],"mappings":"yPAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,EAAW,eAAAC,EAAa,YAAAC,MAA4B,KACtH,OAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,WAAAC,MAAe,OAIjDC,IAYA,SAASC,EAAaC,EAA4B,CAChD,OAAQC,EAAwC,SAASD,CAAC,CAC5D,CAKO,SAASE,EAAgBC,EAA2C,CACzE,GAAI,CAACA,EAAM,OACX,IAAIC,EACJ,GAAI,CACF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pC,IAAMC,EAAiBD,EAAW,IAAIf,GACpC,IAAIA,EAAE,QAAQA,EAAE,eAAeA,EAAE,WAAWA,EAAE,QAAQ,MAAM,EAAG,GAAG,GACpE,EAAE,KAAK;AAAA;AAAA,CAAM,EAEb,MAAO;AAAA;AAAA,YAA6Be,EAAW;AAAA;AAAA,EAA2GC,GAC5J,CAEQ,QAAQC,EAAaC,EAA0D,CACrF,GAAKrI,EAAWoI,CAAG,EACnB,QAAW5I,KAASW,EAAYiI,CAAG,EAAG,CACpC,IAAME,EAAOC,EAAKH,EAAK5I,CAAK,EACtBwD,EAAOwF,EAASF,CAAI,EACtBtF,EAAK,YAAY,EACnB,KAAK,QAAQsF,EAAMD,CAAQ,EAE3BA,EAASC,EAAMtF,CAAI,EAGzB,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","readdirSync","statSync","resolve","join","relative","dirname","init_seat","isImportance","s","IMPORTANCE_LEVELS","parseStatements","line","parsed","out","compareVersionNames","a","b","split","f","m","ta","na","tb","nb","WikiStore","baseDir","resolve","log","mkdirSync","article","agentId","entry","filename","filepath","frontmatter","k","v","writeFileSync","ids","existsSync","wanted","file","readdirSync","id","readFileSync","filter","files","entries","content","fmMatch","fm","body","get","key","KNOWN","meta","path","existing","isWikiArticleType","fullPath","dirname","t","action","articlePath","ts","versionDir","n","err","i","versionTimestamp","versions","version","raw","getArray","x","rawType","type","tags","related","graphPath","aliases","importance","importanceProposed","date","relPaths","sig","filePath","stat","relPath","relative","signature","hit","articles","query","maxResults","queryLower","docs","cachePath","index","buildIndexCached","bm25Scores","scoreAll","scoreMap","r","score","opts","shortlist","DEFAULT_SHORTLIST","pool","candidates","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","toRanking","message","maxArticles","messagePath","weights","maxBm25","bm25Map","hasGraph","bm25","ancestry","ancestryScore","combined","maxChars","lines","totalChars","header","chunk","backlinks","links","link","target","md","byAccess","bucket","list","y","lastRebuilt","typeOrder","typeHeaders","byType","access","totalArticles","byOwner","tag","entryFiles","details","logPath","appendFileSync","limit","e","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync"]}
@@ -0,0 +1,2 @@
1
+ var i=/^[A-Za-z0-9][A-Za-z0-9._:@-]*$/;function b(o){let r=o&&typeof o=="object"?o:{};return{enabled:r.enabled===!0,inbox:typeof r.inbox=="string"?r.inbox:"",crons:Array.isArray(r.crons)?r.crons.filter(n=>typeof n=="string"):[],absorbAgent:typeof r.absorbAgent=="string"?r.absorbAgent:"",maxNotesPerRun:Number.isInteger(r.maxNotesPerRun)?r.maxNotesPerRun:20,maxDeferrals:Number.isInteger(r.maxDeferrals)?r.maxDeferrals:3}}function a(o,r){let n={...o.wikiNotes&&typeof o.wikiNotes=="object"?o.wikiNotes:{}},t=[];if(r.inbox!==void 0){let e=String(r.inbox).trim();if(e&&!i.test(e))throw new Error(`"${e}" is not an agent id`);e?n.inbox=e:delete n.inbox,t.push(e?`inbox=${e}`:"inbox cleared")}if(r.crons!==void 0){let e=[...new Set(r.crons.map(s=>String(s).trim()).filter(Boolean))];n.crons=e,t.push(`crons=${e.length?e.join(","):"none"}`)}if(r.absorbAgent!==void 0){let e=String(r.absorbAgent).trim();if(e&&!i.test(e))throw new Error(`"${e}" is not an agent id`);e?n.absorbAgent=e:delete n.absorbAgent,t.push(e?`absorbAgent=${e}`:"absorb agent cleared")}if(r.maxNotesPerRun!==void 0){let e=Number(r.maxNotesPerRun);if(!Number.isInteger(e)||e<1||e>100)throw new Error("max notes per run must be a whole number from 1 to 100");n.maxNotesPerRun=e,t.push(`maxNotesPerRun=${e}`)}if(r.maxDeferrals!==void 0){let e=Number(r.maxDeferrals);if(!Number.isInteger(e)||e<1||e>20)throw new Error("deferrals before a note expires must be a whole number from 1 to 20");n.maxDeferrals=e,t.push(`maxDeferrals=${e}`)}if(r.enabled!==void 0&&(n.enabled=!!r.enabled,t.push(n.enabled?"on":"off")),t.length===0)throw new Error("nothing to update");if(n.enabled&&!n.inbox)throw new Error("set the inbox agent first: the agent that runs the wiki observe/sweep schedule");for(let e of n.crons??[]){let s=o.crons?.[e];if(!s)throw new Error(`no schedule "${e}" on this node`);if(n.inbox&&s.agent!==n.inbox)throw new Error(`schedule "${e}" runs as "${s.agent}", not the inbox agent "${n.inbox}"`)}if(n.absorbAgent){if(!o.agents?.[n.absorbAgent])throw new Error(`no agent "${n.absorbAgent}" on this node to run the absorb that reads the notes`);if(n.inbox&&!o.agents?.[n.inbox])throw new Error(`the inbox agent "${n.inbox}" is not on this node; set the absorb agent on the node that keeps its notes`);if(r.absorbAgent!==void 0&&o.agents[n.absorbAgent]?.wiki?.absorb?.enabled===!1)throw new Error(`wiki absorb is off for "${n.absorbAgent}" (agents.${n.absorbAgent}.wiki.absorb.enabled is false), so a bulk wiki absorb skips it and never reads the notes; turn its wiki absorb back on first`)}return o.wikiNotes=n,`wiki notes updated (${t.join(", ")})`}export{b as a,a as b};
2
+ //# sourceMappingURL=chunk-NZQBS7GN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wiki/notes-settings.ts"],"sourcesContent":["// Settings for the wiki notes inbox (#825), shared by\n// `agentx wiki notes config` and the dashboard's Schedules tab so both\n// apply the same checks to agentx.json.\n\nexport interface WikiNotesPatch {\n enabled?: boolean\n /** Agent that runs the wiki observe/sweep schedule. \"\" clears it. */\n inbox?: string\n /** Replace the list of schedules that read the inbox. */\n crons?: string[]\n /** Agent whose `wiki absorb` pass reads the inbox. \"\" clears it. */\n absorbAgent?: string\n maxNotesPerRun?: number\n maxDeferrals?: number\n}\n\nexport interface WikiNotesView {\n enabled: boolean\n inbox: string\n crons: string[]\n absorbAgent: string\n maxNotesPerRun: number\n maxDeferrals: number\n}\n\nconst ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:@-]*$/\n\n/** The current settings, with defaults filled in. */\nexport function wikiNotesSettings(raw: any): WikiNotesView {\n const n = raw && typeof raw === \"object\" ? raw : {}\n return {\n enabled: n.enabled === true,\n inbox: typeof n.inbox === \"string\" ? n.inbox : \"\",\n crons: Array.isArray(n.crons) ? n.crons.filter((c: unknown) => typeof c === \"string\") : [],\n absorbAgent: typeof n.absorbAgent === \"string\" ? n.absorbAgent : \"\",\n maxNotesPerRun: Number.isInteger(n.maxNotesPerRun) ? n.maxNotesPerRun : 20,\n maxDeferrals: Number.isInteger(n.maxDeferrals) ? n.maxDeferrals : 3,\n }\n}\n\n/**\n * Apply `patch` to `cfg.wikiNotes` in place and say what changed. Throws a\n * message meant for a person when the result would not work.\n *\n * The inbox agent may live on another node (a node that only posts notes),\n * so it is not required to be in `cfg.agents`. A schedule listed in\n * `crons` must exist here and run as the inbox agent: that is the run\n * that reads the notes. So must `absorbAgent`: absorb reads the inbox\n * file on its own node, which is the inbox agent's node.\n */\nexport function patchWikiNotes(cfg: any, patch: WikiNotesPatch): string {\n const cur = { ...(cfg.wikiNotes && typeof cfg.wikiNotes === \"object\" ? cfg.wikiNotes : {}) }\n const changes: string[] = []\n\n if (patch.inbox !== undefined) {\n const inbox = String(patch.inbox).trim()\n if (inbox && !ID_RE.test(inbox)) throw new Error(`\"${inbox}\" is not an agent id`)\n if (inbox) cur.inbox = inbox\n else delete cur.inbox\n changes.push(inbox ? `inbox=${inbox}` : \"inbox cleared\")\n }\n if (patch.crons !== undefined) {\n const ids = [...new Set(patch.crons.map((c) => String(c).trim()).filter(Boolean))]\n cur.crons = ids\n changes.push(`crons=${ids.length ? ids.join(\",\") : \"none\"}`)\n }\n if (patch.absorbAgent !== undefined) {\n const id = String(patch.absorbAgent).trim()\n if (id && !ID_RE.test(id)) throw new Error(`\"${id}\" is not an agent id`)\n if (id) cur.absorbAgent = id\n else delete cur.absorbAgent\n changes.push(id ? `absorbAgent=${id}` : \"absorb agent cleared\")\n }\n if (patch.maxNotesPerRun !== undefined) {\n const n = Number(patch.maxNotesPerRun)\n if (!Number.isInteger(n) || n < 1 || n > 100) throw new Error(\"max notes per run must be a whole number from 1 to 100\")\n cur.maxNotesPerRun = n\n changes.push(`maxNotesPerRun=${n}`)\n }\n if (patch.maxDeferrals !== undefined) {\n const n = Number(patch.maxDeferrals)\n if (!Number.isInteger(n) || n < 1 || n > 20) throw new Error(\"deferrals before a note expires must be a whole number from 1 to 20\")\n cur.maxDeferrals = n\n changes.push(`maxDeferrals=${n}`)\n }\n if (patch.enabled !== undefined) {\n cur.enabled = Boolean(patch.enabled)\n changes.push(cur.enabled ? \"on\" : \"off\")\n }\n if (changes.length === 0) throw new Error(\"nothing to update\")\n\n if (cur.enabled && !cur.inbox) {\n throw new Error(\"set the inbox agent first: the agent that runs the wiki observe/sweep schedule\")\n }\n for (const id of cur.crons ?? []) {\n const job = cfg.crons?.[id]\n if (!job) throw new Error(`no schedule \"${id}\" on this node`)\n if (cur.inbox && job.agent !== cur.inbox) {\n throw new Error(`schedule \"${id}\" runs as \"${job.agent}\", not the inbox agent \"${cur.inbox}\"`)\n }\n }\n\n if (cur.absorbAgent) {\n if (!cfg.agents?.[cur.absorbAgent]) throw new Error(`no agent \"${cur.absorbAgent}\" on this node to run the absorb that reads the notes`)\n if (cur.inbox && !cfg.agents?.[cur.inbox]) {\n throw new Error(`the inbox agent \"${cur.inbox}\" is not on this node; set the absorb agent on the node that keeps its notes`)\n }\n }\n\n cfg.wikiNotes = cur\n return `wiki notes updated (${changes.join(\", \")})`\n}\n"],"mappings":"AAyBA,IAAMA,EAAQ,iCAGP,SAASC,EAAkBC,EAAyB,CACzD,IAAM,EAAIA,GAAO,OAAOA,GAAQ,SAAWA,EAAM,CAAC,EAClD,MAAO,CACL,QAAS,EAAE,UAAY,GACvB,MAAO,OAAO,EAAE,OAAU,SAAW,EAAE,MAAQ,GAC/C,MAAO,MAAM,QAAQ,EAAE,KAAK,EAAI,EAAE,MAAM,OAAQC,GAAe,OAAOA,GAAM,QAAQ,EAAI,CAAC,EACzF,YAAa,OAAO,EAAE,aAAgB,SAAW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,wDAAwD,EACtHL,EAAI,eAAiBK,EACrBJ,EAAQ,KAAK,kBAAkBI,GAAG,EAEpC,GAAIN,EAAM,eAAiB,OAAW,CACpC,IAAMM,EAAI,OAAON,EAAM,YAAY,EACnC,GAAI,CAAC,OAAO,UAAUM,CAAC,GAAKA,EAAI,GAAKA,EAAI,GAAI,MAAM,IAAI,MAAM,qEAAqE,EAClIL,EAAI,aAAeK,EACnBJ,EAAQ,KAAK,gBAAgBI,GAAG,EAMlC,GAJIN,EAAM,UAAY,SACpBC,EAAI,QAAU,EAAQD,EAAM,QAC5BE,EAAQ,KAAKD,EAAI,QAAU,KAAO,KAAK,GAErCC,EAAQ,SAAW,EAAG,MAAM,IAAI,MAAM,mBAAmB,EAE7D,GAAID,EAAI,SAAW,CAACA,EAAI,MACtB,MAAM,IAAI,MAAM,gFAAgF,EAElG,QAAWI,KAAMJ,EAAI,OAAS,CAAC,EAAG,CAChC,IAAMM,EAAMR,EAAI,QAAQM,CAAE,EAC1B,GAAI,CAACE,EAAK,MAAM,IAAI,MAAM,gBAAgBF,iBAAkB,EAC5D,GAAIJ,EAAI,OAASM,EAAI,QAAUN,EAAI,MACjC,MAAM,IAAI,MAAM,aAAaI,eAAgBE,EAAI,gCAAgCN,EAAI,QAAQ,EAIjG,GAAIA,EAAI,YAAa,CACnB,GAAI,CAACF,EAAI,SAASE,EAAI,WAAW,EAAG,MAAM,IAAI,MAAM,aAAaA,EAAI,kEAAkE,EACvI,GAAIA,EAAI,OAAS,CAACF,EAAI,SAASE,EAAI,KAAK,EACtC,MAAM,IAAI,MAAM,oBAAoBA,EAAI,mFAAmF,EAI/H,OAAAF,EAAI,UAAYE,EACT,uBAAuBC,EAAQ,KAAK,IAAI,IACjD","names":["ID_RE","wikiNotesSettings","raw","c","patchWikiNotes","cfg","patch","cur","changes","inbox","ids","id","n","job"]}
1
+ {"version":3,"sources":["../src/wiki/notes-settings.ts"],"sourcesContent":["// Settings for the wiki notes inbox (#825), shared by\n// `agentx wiki notes config` and the dashboard's Schedules tab so both\n// apply the same checks to agentx.json.\n\nexport interface WikiNotesPatch {\n enabled?: boolean\n /** Agent that runs the wiki observe/sweep schedule. \"\" clears it. */\n inbox?: string\n /** Replace the list of schedules that read the inbox. */\n crons?: string[]\n /** Agent whose `wiki absorb` pass reads the inbox. \"\" clears it. */\n absorbAgent?: string\n maxNotesPerRun?: number\n maxDeferrals?: number\n}\n\nexport interface WikiNotesView {\n enabled: boolean\n inbox: string\n crons: string[]\n absorbAgent: string\n maxNotesPerRun: number\n maxDeferrals: number\n}\n\nconst ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:@-]*$/\n\n/** The current settings, with defaults filled in. */\nexport function wikiNotesSettings(raw: any): WikiNotesView {\n const n = raw && typeof raw === \"object\" ? raw : {}\n return {\n enabled: n.enabled === true,\n inbox: typeof n.inbox === \"string\" ? n.inbox : \"\",\n crons: Array.isArray(n.crons) ? n.crons.filter((c: unknown) => typeof c === \"string\") : [],\n absorbAgent: typeof n.absorbAgent === \"string\" ? n.absorbAgent : \"\",\n maxNotesPerRun: Number.isInteger(n.maxNotesPerRun) ? n.maxNotesPerRun : 20,\n maxDeferrals: Number.isInteger(n.maxDeferrals) ? n.maxDeferrals : 3,\n }\n}\n\n/**\n * Apply `patch` to `cfg.wikiNotes` in place and say what changed. Throws a\n * message meant for a person when the result would not work.\n *\n * The inbox agent may live on another node (a node that only posts notes),\n * so it is not required to be in `cfg.agents`. A schedule listed in\n * `crons` must exist here and run as the inbox agent: that is the run\n * that reads the notes. So must `absorbAgent`: absorb reads the inbox\n * file on its own node, which is the inbox agent's node.\n */\nexport function patchWikiNotes(cfg: any, patch: WikiNotesPatch): string {\n const cur = { ...(cfg.wikiNotes && typeof cfg.wikiNotes === \"object\" ? cfg.wikiNotes : {}) }\n const changes: string[] = []\n\n if (patch.inbox !== undefined) {\n const inbox = String(patch.inbox).trim()\n if (inbox && !ID_RE.test(inbox)) throw new Error(`\"${inbox}\" is not an agent id`)\n if (inbox) cur.inbox = inbox\n else delete cur.inbox\n changes.push(inbox ? `inbox=${inbox}` : \"inbox cleared\")\n }\n if (patch.crons !== undefined) {\n const ids = [...new Set(patch.crons.map((c) => String(c).trim()).filter(Boolean))]\n cur.crons = ids\n changes.push(`crons=${ids.length ? ids.join(\",\") : \"none\"}`)\n }\n if (patch.absorbAgent !== undefined) {\n const id = String(patch.absorbAgent).trim()\n if (id && !ID_RE.test(id)) throw new Error(`\"${id}\" is not an agent id`)\n if (id) cur.absorbAgent = id\n else delete cur.absorbAgent\n changes.push(id ? `absorbAgent=${id}` : \"absorb agent cleared\")\n }\n if (patch.maxNotesPerRun !== undefined) {\n const n = Number(patch.maxNotesPerRun)\n if (!Number.isInteger(n) || n < 1 || n > 100) throw new Error(\"max notes per run must be a whole number from 1 to 100\")\n cur.maxNotesPerRun = n\n changes.push(`maxNotesPerRun=${n}`)\n }\n if (patch.maxDeferrals !== undefined) {\n const n = Number(patch.maxDeferrals)\n if (!Number.isInteger(n) || n < 1 || n > 20) throw new Error(\"deferrals before a note expires must be a whole number from 1 to 20\")\n cur.maxDeferrals = n\n changes.push(`maxDeferrals=${n}`)\n }\n if (patch.enabled !== undefined) {\n cur.enabled = Boolean(patch.enabled)\n changes.push(cur.enabled ? \"on\" : \"off\")\n }\n if (changes.length === 0) throw new Error(\"nothing to update\")\n\n if (cur.enabled && !cur.inbox) {\n throw new Error(\"set the inbox agent first: the agent that runs the wiki observe/sweep schedule\")\n }\n for (const id of cur.crons ?? []) {\n const job = cfg.crons?.[id]\n if (!job) throw new Error(`no schedule \"${id}\" on this node`)\n if (cur.inbox && job.agent !== cur.inbox) {\n throw new Error(`schedule \"${id}\" runs as \"${job.agent}\", not the inbox agent \"${cur.inbox}\"`)\n }\n }\n\n if (cur.absorbAgent) {\n if (!cfg.agents?.[cur.absorbAgent]) throw new Error(`no agent \"${cur.absorbAgent}\" on this node to run the absorb that reads the notes`)\n if (cur.inbox && !cfg.agents?.[cur.inbox]) {\n throw new Error(`the inbox agent \"${cur.inbox}\" is not on this node; set the absorb agent on the node that keeps its notes`)\n }\n // A bulk `wiki absorb` skips an agent with absorb off (#850), so its\n // notes would wait for a step that never runs (#885). Checked only when\n // this patch names the agent, so other edits are not blocked.\n if (patch.absorbAgent !== undefined && cfg.agents[cur.absorbAgent]?.wiki?.absorb?.enabled === false) {\n throw new Error(`wiki absorb is off for \"${cur.absorbAgent}\" (agents.${cur.absorbAgent}.wiki.absorb.enabled is false), so a bulk wiki absorb skips it and never reads the notes; turn its wiki absorb back on first`)\n }\n }\n\n cfg.wikiNotes = cur\n return `wiki notes updated (${changes.join(\", \")})`\n}\n"],"mappings":"AAyBA,IAAMA,EAAQ,iCAGP,SAASC,EAAkBC,EAAyB,CACzD,IAAMC,EAAID,GAAO,OAAOA,GAAQ,SAAWA,EAAM,CAAC,EAClD,MAAO,CACL,QAASC,EAAE,UAAY,GACvB,MAAO,OAAOA,EAAE,OAAU,SAAWA,EAAE,MAAQ,GAC/C,MAAO,MAAM,QAAQA,EAAE,KAAK,EAAIA,EAAE,MAAM,OAAQC,GAAe,OAAOA,GAAM,QAAQ,EAAI,CAAC,EACzF,YAAa,OAAOD,EAAE,aAAgB,SAAWA,EAAE,YAAc,GACjE,eAAgB,OAAO,UAAUA,EAAE,cAAc,EAAIA,EAAE,eAAiB,GACxE,aAAc,OAAO,UAAUA,EAAE,YAAY,EAAIA,EAAE,aAAe,CACpE,CACF,CAYO,SAASE,EAAeC,EAAUC,EAA+B,CACtE,IAAMC,EAAM,CAAE,GAAIF,EAAI,WAAa,OAAOA,EAAI,WAAc,SAAWA,EAAI,UAAY,CAAC,CAAG,EACrFG,EAAoB,CAAC,EAE3B,GAAIF,EAAM,QAAU,OAAW,CAC7B,IAAMG,EAAQ,OAAOH,EAAM,KAAK,EAAE,KAAK,EACvC,GAAIG,GAAS,CAACV,EAAM,KAAKU,CAAK,EAAG,MAAM,IAAI,MAAM,IAAIA,uBAA2B,EAC5EA,EAAOF,EAAI,MAAQE,EAClB,OAAO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MACtB,MAAM,IAAI,MAAM,gFAAgF,EAElG,QAAWI,KAAMJ,EAAI,OAAS,CAAC,EAAG,CAChC,IAAMK,EAAMP,EAAI,QAAQM,CAAE,EAC1B,GAAI,CAACC,EAAK,MAAM,IAAI,MAAM,gBAAgBD,iBAAkB,EAC5D,GAAIJ,EAAI,OAASK,EAAI,QAAUL,EAAI,MACjC,MAAM,IAAI,MAAM,aAAaI,eAAgBC,EAAI,gCAAgCL,EAAI,QAAQ,EAIjG,GAAIA,EAAI,YAAa,CACnB,GAAI,CAACF,EAAI,SAASE,EAAI,WAAW,EAAG,MAAM,IAAI,MAAM,aAAaA,EAAI,kEAAkE,EACvI,GAAIA,EAAI,OAAS,CAACF,EAAI,SAASE,EAAI,KAAK,EACtC,MAAM,IAAI,MAAM,oBAAoBA,EAAI,mFAAmF,EAK7H,GAAID,EAAM,cAAgB,QAAaD,EAAI,OAAOE,EAAI,WAAW,GAAG,MAAM,QAAQ,UAAY,GAC5F,MAAM,IAAI,MAAM,2BAA2BA,EAAI,wBAAwBA,EAAI,yIAAyI,EAIxN,OAAAF,EAAI,UAAYE,EACT,uBAAuBC,EAAQ,KAAK,IAAI,IACjD","names":["ID_RE","wikiNotesSettings","raw","n","c","patchWikiNotes","cfg","patch","cur","changes","inbox","ids","id","job"]}
@@ -1,7 +1,7 @@
1
- import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{pa as S,xa as L}from"./chunk-2BF6HJJD.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{pa as S,xa as L}from"./chunk-DYGQF3MI.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
3
  `)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
6
6
  `))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,J as b,ke as c,G as d,V as e,ne as f};
7
- //# sourceMappingURL=chunk-3TETB22A.js.map
7
+ //# sourceMappingURL=chunk-P3I7AATX.js.map
@@ -0,0 +1,3 @@
1
+ import{existsSync as U,readFileSync as v,statSync as B}from"fs";import{resolve as I}from"path";var A=new Map;function N(t){if(!A.has(t))try{A.set(t,new RegExp(t,"i"))}catch{A.set(t,null)}return A.get(t)??null}function R(t,a,o){let i=new Set(o.types.map(r=>r.id));if(t.class&&i.has(t.class))return t.class;let n=a.split("/").slice(0,-1).map(r=>r.toLowerCase()),e=new Set((t.tags??[]).map(r=>r.toLowerCase()));for(let r of o.classify){if(!i.has(r.type))continue;let c=0;if(!(r.legacy&&(c++,!t.type||!r.legacy.includes(t.type)))&&!(r.path&&(c++,!r.path.some(m=>n.includes(m.toLowerCase()))))&&!(r.tags&&(c++,!r.tags.some(m=>e.has(m.toLowerCase()))))){if(r.title){c++;let m=N(r.title);if(!m||!m.test(t.title))continue}if(c>0)return r.type}}return i.has(o.fallback_type)?o.fallback_type:o.types[0].id}function u(t){return t.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/\.md$/,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function E(t){return u(t).replace(/ /g,"-").slice(0,80)||"page"}var O=/\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;function G(t){if(t.meta.date)return t.meta.date;let o=(t.path.split("/").pop()??"").match(/^(\d{4}-\d{2}-\d{2})/);if(o)return o[1];let i=t.meta.title.match(/(\d{4}-\d{2}-\d{2})/);return i?i[1]:(t.meta.created||t.meta.lastUpdated||"").slice(0,10)}function $(t,a,o){if(a.size===0||!o.types.some(e=>e.id==="agent"))return;let i=o.types.find(e=>e.id==="agent").pillar,n=new Set;for(let e of t.values()){let r=u(e.title).split(" ");e.type==="person"&&r.length>1&&n.add(r[0])}for(let e of t.values()){if(e.type!=="person"&&e.type!==o.fallback_type||e.pages.some(c=>c.article.meta.class))continue;let r=M(a,[e.title]);if(!r){let c=M(a,e.pages.flatMap(m=>m.article.meta.aliases??[]));c&&(e.review??=`an alias matches agent ${c}; set class on the page to decide`);continue}if(e.type==="person"&&n.has(u(e.title))){e.review=`shares a name with agent ${r} and with a person; set class on the page to decide`;continue}e.type="agent",e.pillar=i}}function L(t,a,o=new Map){let i=new Map(a.types.map(s=>[s.id,s])),n=new Map,e=new Map,r=new Set;for(let s of t){let p=[s.article.meta.title,...s.article.meta.aliases??[]].map(u).filter(Boolean);if(p.length===0)continue;let l=p.map(d=>n.get(d)).find(Boolean);if(!l){l=E(s.article.meta.title);for(let d=2;r.has(l);d++)l=`${E(s.article.meta.title)}-${d}`;r.add(l),e.set(l,[])}e.get(l).push(s);for(let d of p)n.has(d)||n.set(d,l);let f=u(s.article.path);n.has(f)||n.set(f,l)}let c=new Map;for(let[s,p]of e){let l=new Map;for(let g of p){let w=R(g.article.meta,g.article.path,a),W=g.article.meta.class===w?1e3:w===a.fallback_type?.5:1;l.set(w,(l.get(w)??0)+W)}let f=[...l.entries()].sort((g,w)=>w[1]-g[1])[0][0],d=p[0].article,b=p.map(g=>G(g.article)).filter(Boolean).sort(),P=p.map(g=>g.article.meta.importance).find(Boolean)??a.importance.default;c.set(s,{id:s,type:f,pillar:i.get(f)?.pillar??"topics",title:d.meta.title,pages:p,statements:[],date:b[0]??"",updated:p.map(g=>g.article.meta.lastUpdated||"").sort().pop()??"",importance:p.some(g=>g.article.meta.importance==="major")?"major":P,importanceProposed:p.map(g=>g.article.meta.importanceProposed).find(Boolean),rolledUpInto:p.map(g=>g.article.meta.rolledUpInto).find(Boolean),sources:[...new Set(p.flatMap(g=>g.article.meta.sources??[]))]})}$(c,o,a);let m=s=>n.get(u(s)),y=new Map,h=new Map,x=s=>{if(s.from===s.to)return;let p=y.get(s.from)??[];if(s.property==="related"&&p.some(f=>f.to===s.to))return;p.push(s),y.set(s.from,p);let l=h.get(s.to)??[];l.push(s),h.set(s.to,l)};for(let s of c.values())for(let p of s.pages)for(let l of p.article.meta.statements??[]){let f={...l,page:p,target:m(l.value)};s.statements.push(f),f.target&&x({from:s.id,to:f.target,property:l.property,statement:f})}for(let s of c.values())for(let p of s.pages){let l=new Set(p.article.meta.related??[]);for(let f of p.article.content.matchAll(O))l.add(f[1].trim());for(let f of l){let d=m(f);d&&x({from:s.id,to:d,property:"related"})}}for(let s of c.values())s.rolledUpInto&&(s.rolledUpInto=m(s.rolledUpInto));return{ontology:a,entities:c,outgoing:y,incoming:h,names:n}}var S=class{last=null;get(a,o,i=new Map){let n=[];for(let y of a.listAgents([]))for(let h of a.getAgentWiki(y).listAllArticles())n.push({agentId:y,article:h});let e=n.map(y=>y.article),r=[...i].join(`
2
+ `),c=this.last;if(c&&c.ontology===o&&c.roster===r&&c.refs.length===e.length&&c.refs.every((y,h)=>y===e[h]))return c.graph;let m=L(n,o,i);return this.last={refs:e,ontology:o,roster:r,graph:m},m}};function _(t,a=[]){let o=new Map,i=(n,e)=>{let r=n?u(n):"";r&&!o.has(r)&&o.set(r,e)};for(let n of t)(!n.name||u(n.name)!==`${u(n.id)} agent`)&&i(n.id,n.id),i(n.name,n.id),i(n.persona,n.id);for(let n of a)i(n,n);return o}function M(t,a){for(let o of a){let i=u(o),n=t.get(i)??t.get(i.replace(/ (agent|bot)$/,""));if(n)return n;if(/ (agent|bot)( |$)/.test(i)){for(let[e,r]of t)if(i.startsWith(`${e} `))return r}}}var j=["IDENTITY.md","persona.md","PERSONA.md"];function C(t){let o=t.match(/\*\*Name:\*\*[ \t]*([^\n(.,;—–]+)/)?.[1]?.replace(/[*_`]/g,"").trim();return o&&o.length<=40?o:void 0}function K(t){if(t)for(let a of j){let o=I(t,a);try{if(U(o)){let i=C(v(o,"utf-8"));if(i)return i}}catch{}}}var k=null;function D(t){let a=I(t,"..","..","agentx.json"),o;try{o=B(a).mtimeMs}catch{return[]}if(k&&k.file===a&&k.mtimeMs===o)return k.agents;let i=[];try{let n=JSON.parse(v(a,"utf-8"));i=Object.entries(n.agents??{}).map(([e,r])=>({id:e,name:typeof r?.name=="string"?r.name:void 0,persona:K(typeof r?.workspace=="string"?r.workspace:void 0)}))}catch{i=[]}return k={file:a,mtimeMs:o,agents:i},i}function Q(t,a,o=[]){let i=D(t),n=new Set(i.map(e=>e.id));return _([...i,...a.filter(e=>!n.has(e)).map(e=>({id:e}))],o)}export{_ as a,M as b,C as c,D as d,Q as e,u as f,E as g,L as h,S as i};
3
+ //# sourceMappingURL=chunk-QAWKN2N4.js.map