agentix-cli 0.18.0 → 0.19.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 (171) hide show
  1. package/README.md +75 -27
  2. package/dist/{agent-RDVGL2TW.js → agent-57MG4LBM.js} +2 -2
  3. package/dist/{audit-Z47AQFFD.js → audit-JU3HWISB.js} +2 -2
  4. package/dist/{board-dashboard-KX2CNOSY.js → board-dashboard-HXDOYGIG.js} +2237 -69
  5. package/dist/board-dashboard-HXDOYGIG.js.map +1 -0
  6. package/dist/chunk-23AUU4S2.js +102 -0
  7. package/dist/chunk-23AUU4S2.js.map +1 -0
  8. package/dist/chunk-4MREHZP5.js +111 -0
  9. package/dist/chunk-4MREHZP5.js.map +1 -0
  10. package/dist/chunk-4YCH6IZV.js +2 -0
  11. package/dist/chunk-6B74TO2J.js +743 -0
  12. package/dist/chunk-6B74TO2J.js.map +1 -0
  13. package/dist/chunk-7P5QRX5W.js +108 -0
  14. package/dist/chunk-7P5QRX5W.js.map +1 -0
  15. package/dist/chunk-A6BKSZQA.js +3 -0
  16. package/dist/chunk-A6BKSZQA.js.map +1 -0
  17. package/dist/{chunk-6PPIFDOQ.js → chunk-CNNLREHD.js} +67 -22
  18. package/dist/{chunk-6PPIFDOQ.js.map → chunk-CNNLREHD.js.map} +1 -1
  19. package/dist/{chunk-J4WKMKTP.js → chunk-DLVOHCTA.js} +2 -2
  20. package/dist/chunk-E4ZZILAK.js +15 -0
  21. package/dist/chunk-E4ZZILAK.js.map +1 -0
  22. package/dist/{chunk-TRQSP67X.js → chunk-IKBHHTIT.js} +2 -2
  23. package/dist/chunk-JTJIPNXY.js +2 -0
  24. package/dist/chunk-JTJIPNXY.js.map +1 -0
  25. package/dist/chunk-MBOLXKA2.js +6 -0
  26. package/dist/chunk-MBOLXKA2.js.map +1 -0
  27. package/dist/{inbox-O5UB3YQN.js → chunk-MTRWXRFF.js} +69 -4
  28. package/dist/chunk-MTRWXRFF.js.map +1 -0
  29. package/dist/{processes-7W27G3J3.js → chunk-NOF4HSGK.js} +3 -3
  30. package/dist/{processes-7W27G3J3.js.map → chunk-NOF4HSGK.js.map} +1 -1
  31. package/dist/chunk-QW2OYR3N.js +7 -0
  32. package/dist/chunk-QW2OYR3N.js.map +1 -0
  33. package/dist/chunk-SV3I4CI7.js +440 -0
  34. package/dist/chunk-SV3I4CI7.js.map +1 -0
  35. package/dist/{chunk-JXEPJ3YD.js → chunk-TC3BSUP7.js} +5 -5
  36. package/dist/chunk-VWTBHLMX.js +1 -0
  37. package/dist/chunk-WFHIIVLL.js +719 -0
  38. package/dist/chunk-WFHIIVLL.js.map +1 -0
  39. package/dist/chunk-WPPUOTY6.js +6 -0
  40. package/dist/chunk-WPPUOTY6.js.map +1 -0
  41. package/dist/cli.js +1 -1
  42. package/dist/cli.js.map +1 -1
  43. package/dist/{compaction-S5H6DTOR.js → compaction-BTUJJ3LJ.js} +4 -4
  44. package/dist/config-QXWKEQON.js +2 -0
  45. package/dist/config-mutator-53XGR2NT.js +2 -0
  46. package/dist/conflict-detector-D7VIYPDI.js +2 -0
  47. package/dist/conflict-detector-D7VIYPDI.js.map +1 -0
  48. package/dist/{context-planner-2RGHJHSO.js → context-planner-I7ID7XF3.js} +3 -3
  49. package/dist/debug-N3B5NVJU.js +2 -0
  50. package/dist/{discover-OATU7SHI.js → discover-XJXQXXIO.js} +2 -2
  51. package/dist/doctor-SEOUFHSL.js +2 -0
  52. package/dist/{editor-chat-FUBQLMAQ.js → editor-chat-RVLCKKB7.js} +2 -2
  53. package/dist/{heal-YP7QI7D3.js → heal-YEQYWX2L.js} +2 -2
  54. package/dist/inbox-BIN2S5XN.js +2 -0
  55. package/dist/index.d.ts +830 -100
  56. package/dist/index.js +2 -2
  57. package/dist/index.js.map +1 -1
  58. package/dist/{ingest-whatsapp-C3O5UPBX.js → ingest-whatsapp-LZE62INA.js} +2 -2
  59. package/dist/loader-5CA3O5GM.js +2 -0
  60. package/dist/loader-6IHUCPVO.js +2 -0
  61. package/dist/memory-extract-KRCHD3OP.js +2 -0
  62. package/dist/migrate-v2-QO7SLKIM.js +4 -0
  63. package/dist/migrate-v2-QO7SLKIM.js.map +1 -0
  64. package/dist/processes-RJ6RDP32.js +2 -0
  65. package/dist/program-SASDC2GV.js +2 -0
  66. package/dist/{providers-WCQSKTNP.js → providers-WVCMIW67.js} +2 -2
  67. package/dist/query-HZYYRCLU.js +2 -0
  68. package/dist/recipes-EPLE2SNT.js +2 -0
  69. package/dist/registry-HM4ELSXS.js +2 -0
  70. package/dist/rotation-memo-GMTZPMNE.js +13 -0
  71. package/dist/rotation-memo-GMTZPMNE.js.map +1 -0
  72. package/dist/scheduler-XVFIK4XH.js +2 -0
  73. package/dist/{slack-D27BE37Q.js → slack-6P7ZJ32Y.js} +2 -2
  74. package/dist/store-BAPDZHXE.js +2 -0
  75. package/dist/{subagent-EPOT3QDM.js → subagent-WV7QKQ3L.js} +2 -2
  76. package/dist/{task-store-3NUWLYRY.js → task-store-RHISEU6V.js} +2 -2
  77. package/dist/{telegram-UWV67KWG.js → telegram-PIYDRM46.js} +2 -2
  78. package/dist/timers-5LPZN55J.js +2 -0
  79. package/dist/types-VECTMYTO.js +2 -0
  80. package/dist/types-VECTMYTO.js.map +1 -0
  81. package/dist/types-ZRLHHCGB.js +2 -0
  82. package/dist/types-ZRLHHCGB.js.map +1 -0
  83. package/dist/web/activity-graph.global.js +654 -0
  84. package/dist/web/activity-graph.global.js.map +1 -0
  85. package/dist/web/workflow-editor.global.js +1 -1
  86. package/dist/web/workflow-editor.global.js.map +1 -1
  87. package/dist/{whatsapp-KJ2NRKKQ.js → whatsapp-PFRDMUMT.js} +2 -2
  88. package/dist/{whatsapp-state-3ZVQ6MQD.js → whatsapp-state-XMTCSRXU.js} +2 -2
  89. package/dist/wiki-53W5NLZV.js +2 -0
  90. package/dist/wiki-53W5NLZV.js.map +1 -0
  91. package/dist/workspace-setup-FPGN5VNY.js +2 -0
  92. package/dist/workspace-setup-FPGN5VNY.js.map +1 -0
  93. package/package.json +3 -2
  94. package/dist/board-dashboard-KX2CNOSY.js.map +0 -1
  95. package/dist/chunk-34NG7UDX.js +0 -11
  96. package/dist/chunk-34NG7UDX.js.map +0 -1
  97. package/dist/chunk-ASSJ4Z6Z.js +0 -164
  98. package/dist/chunk-ASSJ4Z6Z.js.map +0 -1
  99. package/dist/chunk-BLUXL6HR.js +0 -854
  100. package/dist/chunk-BLUXL6HR.js.map +0 -1
  101. package/dist/chunk-BTAEYL3P.js +0 -72
  102. package/dist/chunk-BTAEYL3P.js.map +0 -1
  103. package/dist/chunk-DSCMCVTV.js +0 -7
  104. package/dist/chunk-DSCMCVTV.js.map +0 -1
  105. package/dist/chunk-HPDHNIA3.js +0 -2
  106. package/dist/chunk-IM376SD6.js +0 -13
  107. package/dist/chunk-IM376SD6.js.map +0 -1
  108. package/dist/chunk-LEIYC3BF.js +0 -104
  109. package/dist/chunk-LEIYC3BF.js.map +0 -1
  110. package/dist/chunk-LY7JGDV7.js +0 -6
  111. package/dist/chunk-LY7JGDV7.js.map +0 -1
  112. package/dist/chunk-U364GNQX.js +0 -719
  113. package/dist/chunk-U364GNQX.js.map +0 -1
  114. package/dist/chunk-WZEYII2S.js +0 -6
  115. package/dist/chunk-WZEYII2S.js.map +0 -1
  116. package/dist/config-UOHEG4BW.js +0 -2
  117. package/dist/config-mutator-KSEBWKJH.js +0 -2
  118. package/dist/debug-TGAP7E7W.js +0 -2
  119. package/dist/inbox-O5UB3YQN.js.map +0 -1
  120. package/dist/loader-BGWA7IRY.js +0 -2
  121. package/dist/loader-LBHKSXBK.js +0 -2
  122. package/dist/memory-extract-KKPKAOPH.js +0 -2
  123. package/dist/program-2MDELQLX.js +0 -2
  124. package/dist/query-FZAL7AQD.js +0 -2
  125. package/dist/recipes-LZ56TA3X.js +0 -2
  126. package/dist/registry-ONJSILH4.js +0 -2
  127. package/dist/scheduler-XRM2RJIV.js +0 -2
  128. package/dist/store-4UCO56K2.js +0 -2
  129. package/dist/timers-QB4KYNAE.js +0 -2
  130. package/dist/types-ECMEC5BZ.js +0 -2
  131. package/dist/types-TTB6DJUE.js +0 -2
  132. package/dist/usage-dashboard-FQGPPABD.js +0 -803
  133. package/dist/usage-dashboard-FQGPPABD.js.map +0 -1
  134. package/dist/wiki-OUYKM7MB.js +0 -2
  135. package/dist/workspace-setup-6GDBEORT.js +0 -2
  136. /package/dist/{agent-RDVGL2TW.js.map → agent-57MG4LBM.js.map} +0 -0
  137. /package/dist/{audit-Z47AQFFD.js.map → audit-JU3HWISB.js.map} +0 -0
  138. /package/dist/{chunk-HPDHNIA3.js.map → chunk-4YCH6IZV.js.map} +0 -0
  139. /package/dist/{chunk-J4WKMKTP.js.map → chunk-DLVOHCTA.js.map} +0 -0
  140. /package/dist/{chunk-TRQSP67X.js.map → chunk-IKBHHTIT.js.map} +0 -0
  141. /package/dist/{chunk-JXEPJ3YD.js.map → chunk-TC3BSUP7.js.map} +0 -0
  142. /package/dist/{config-UOHEG4BW.js.map → chunk-VWTBHLMX.js.map} +0 -0
  143. /package/dist/{compaction-S5H6DTOR.js.map → compaction-BTUJJ3LJ.js.map} +0 -0
  144. /package/dist/{config-mutator-KSEBWKJH.js.map → config-QXWKEQON.js.map} +0 -0
  145. /package/dist/{debug-TGAP7E7W.js.map → config-mutator-53XGR2NT.js.map} +0 -0
  146. /package/dist/{context-planner-2RGHJHSO.js.map → context-planner-I7ID7XF3.js.map} +0 -0
  147. /package/dist/{heal-YP7QI7D3.js.map → debug-N3B5NVJU.js.map} +0 -0
  148. /package/dist/{discover-OATU7SHI.js.map → discover-XJXQXXIO.js.map} +0 -0
  149. /package/dist/{loader-BGWA7IRY.js.map → doctor-SEOUFHSL.js.map} +0 -0
  150. /package/dist/{editor-chat-FUBQLMAQ.js.map → editor-chat-RVLCKKB7.js.map} +0 -0
  151. /package/dist/{loader-LBHKSXBK.js.map → heal-YEQYWX2L.js.map} +0 -0
  152. /package/dist/{memory-extract-KKPKAOPH.js.map → inbox-BIN2S5XN.js.map} +0 -0
  153. /package/dist/{ingest-whatsapp-C3O5UPBX.js.map → ingest-whatsapp-LZE62INA.js.map} +0 -0
  154. /package/dist/{program-2MDELQLX.js.map → loader-5CA3O5GM.js.map} +0 -0
  155. /package/dist/{providers-WCQSKTNP.js.map → loader-6IHUCPVO.js.map} +0 -0
  156. /package/dist/{query-FZAL7AQD.js.map → memory-extract-KRCHD3OP.js.map} +0 -0
  157. /package/dist/{recipes-LZ56TA3X.js.map → processes-RJ6RDP32.js.map} +0 -0
  158. /package/dist/{registry-ONJSILH4.js.map → program-SASDC2GV.js.map} +0 -0
  159. /package/dist/{scheduler-XRM2RJIV.js.map → providers-WVCMIW67.js.map} +0 -0
  160. /package/dist/{store-4UCO56K2.js.map → query-HZYYRCLU.js.map} +0 -0
  161. /package/dist/{task-store-3NUWLYRY.js.map → recipes-EPLE2SNT.js.map} +0 -0
  162. /package/dist/{timers-QB4KYNAE.js.map → registry-HM4ELSXS.js.map} +0 -0
  163. /package/dist/{types-ECMEC5BZ.js.map → scheduler-XVFIK4XH.js.map} +0 -0
  164. /package/dist/{slack-D27BE37Q.js.map → slack-6P7ZJ32Y.js.map} +0 -0
  165. /package/dist/{types-TTB6DJUE.js.map → store-BAPDZHXE.js.map} +0 -0
  166. /package/dist/{subagent-EPOT3QDM.js.map → subagent-WV7QKQ3L.js.map} +0 -0
  167. /package/dist/{wiki-OUYKM7MB.js.map → task-store-RHISEU6V.js.map} +0 -0
  168. /package/dist/{telegram-UWV67KWG.js.map → telegram-PIYDRM46.js.map} +0 -0
  169. /package/dist/{workspace-setup-6GDBEORT.js.map → timers-5LPZN55J.js.map} +0 -0
  170. /package/dist/{whatsapp-KJ2NRKKQ.js.map → whatsapp-PFRDMUMT.js.map} +0 -0
  171. /package/dist/{whatsapp-state-3ZVQ6MQD.js.map → whatsapp-state-XMTCSRXU.js.map} +0 -0
@@ -0,0 +1,440 @@
1
+ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as at,b as mn,e as Jt,i as un}from"./chunk-WFHIIVLL.js";import{a as Vo,g as en,h as tn,i as uo,j as dn,k as gn}from"./chunk-6B74TO2J.js";import{a as on,b as nn,c as sn,d as rn,e as an,f as qt,g as Ct,l as cn,m as mo,n as ln,o as po}from"./chunk-E4ZZILAK.js";import{b as xe}from"./chunk-EW27SCCC.js";import{c as Xo}from"./chunk-QW2OYR3N.js";import{a as re,b as Q,c as Ye,d as Zo}from"./chunk-DLVOHCTA.js";import{d as Qo,e as P,f as Ut}from"./chunk-MBOLXKA2.js";import{e as rt}from"./chunk-23AUU4S2.js";import{b as Ko}from"./chunk-4MREHZP5.js";import{b as Ge,d as Ho,f as go}from"./chunk-7P5QRX5W.js";import{a as Ie}from"./chunk-VJUTQAPJ.js";import{a as ws}from"./chunk-4YCH6IZV.js";import{Command as Gr}from"commander";import{Command as $s}from"commander";import S from"chalk";import{existsSync as bs,readFileSync as ks}from"fs";var Se=new $s().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Se.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:l}=await import("child_process"),p=["dist/cli.js","daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let d=l("node",p,{detached:!0,stdio:["ignore","ignore","ignore"],cwd:process.cwd()});d.unref();let{writeFileSync:m}=await import("fs");m("/tmp/agentx-daemon.pid",String(d.pid)),console.log(S.green(`Daemon started in background (PID: ${d.pid})`)),console.log(S.dim(" Logs: tail -f /tmp/agentx-daemon.log")),console.log(S.dim(" Stop: agentx daemon stop"));return}let{readFileSync:t,writeFileSync:o,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let l=parseInt(t(a,"utf-8").trim(),10);if(l&&l!==process.pid)try{process.kill(l,0),console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0)}catch{}}o(a,String(process.pid));try{vs(i(process.cwd(),".env"))}catch{}await new uo(e.config).start()});function vs(e){if(!bs(e))return;let t=ks(e,"utf-8");for(let o of t.split(`
2
+ `)){let n=o.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}Se.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:o}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(t(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{o(r)}catch{}console.log(S.green(`Daemon stopped (PID: ${a})`));return}catch{try{o(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(S.green("Daemon stopped"))}catch{console.log(S.yellow("No daemon process found"))}});Se.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let t=P(e.config),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(S.bold(` ${r.node.name}`)+S.dim(` (${r.node.id})`)),console.log(S.green(" Status: running")+S.dim(` \u2014 uptime ${xs(r.uptime)}`)),console.log(),console.log(S.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?S.yellow(` [${c.active} active]`):"",p=c.errors>0?S.red(` (${c.errors} errors)`):"";console.log(` ${S.cyan(c.name)} ${S.dim(`(${c.tier})`)}${l}${p}`),console.log(S.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(S.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?S.green("\u25CF"):S.dim("\u25CB"),p=c.nextRun?S.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${p}`)}}if(r.mesh?.length){console.log(),console.log(S.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?S.green("\u25CF"):S.red("\u25CF"),p=c.skills?.length?S.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${S.dim(c.peerUrl)}${p}`)}}console.log()}catch(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(S.red(" Daemon is not running")),console.log(S.dim(" Start with: agentx daemon start"));else try{let o=P(e.config),n=Ut(o);if(console.log(),console.log(S.bold(` ${o.node.name}`)+S.dim(` (${o.node.id})`)),console.log(S.yellow(" Status: stopped")),console.log(S.dim(` ${Object.keys(o.agents).length} agents, ${Object.keys(o.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(S.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(S.red(` ${o.message}`))}}});Se.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:t,spawn:o}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(S.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=o("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Se.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(P(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(S.dim(` Connecting to ${n}...`)),console.log(S.dim(` Press Ctrl+C to stop
3
+ `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(S.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let p=a.split(`
4
+ `);a=p.pop()||"";for(let d of p)if(d.startsWith("data: "))try{let m=JSON.parse(d.slice(6)),h=new Date(m.time).toLocaleTimeString(),f=m.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${S.dim(h)} ${S.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${S.dim(h)} ${S.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${S.dim(h)} ${S.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${S.dim(h)} ${S.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${S.dim(h)} ${S.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${S.dim(h)} ${S.dim("\u2298")} ${S.dim(f)}`):console.log(`${S.dim(h)} ${f}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(S.red(` Connection failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});Se.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,t,o)=>{let n=t.join(" ");try{let s=P(o.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;o.peer?(c=`${a}/mesh/task`,l={peer:o.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(S.dim(` Sending to ${o.peer?`${o.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();o.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(S.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(S.dim(`
5
+ (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(S.red(` Failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});Se.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,t)=>{let{execSync:o}=await import("child_process"),n=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(S.dim(" Running tests...")),o("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Tests passed"))}catch{console.log(S.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(S.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(S.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(S.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Build complete")))}console.log(S.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(S.green(" \u2713 Deploy complete")),t.restart){console.log(S.dim(" Restarting remote daemon..."));let i=t.identity?`ssh -i ${t.identity}`:"ssh";o(`${i} ${t.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${t.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(S.green(" Remote daemon restarted"))}}catch(i){console.log(S.red(` Deploy failed: ${i.message}`))}});Se.action(async e=>{await new uo(e.config).start()});function xs(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as Ss}from"commander";import ke from"chalk";import{existsSync as Et,readFileSync as js,writeFileSync as hn,mkdirSync as fn}from"fs";import{hostname as yn}from"os";import{resolve as ct}from"path";var wn=new Ss().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=ct(t,"agentx.json"),n=ct(t,".env"),s=ct(t,".agentx/sessions");if(console.log(),console.log(ke.bold(" agentx init")),console.log(),Et(o)&&!e.force){console.log(ke.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ct(t,"agentx.example.json"),ct(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Et(c)){r=js(c,"utf-8");break}r||(r=JSON.stringify({node:{id:yn().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:yn(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),hn(o,r),console.log(ke.green(" \u2713 Created agentx.json")),Et(n)||(hn(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
6
+ `)),console.log(ke.green(" \u2713 Created .env template"))),Et(s)||(fn(s,{recursive:!0}),console.log(ke.green(" \u2713 Created .agentx/sessions/")));let a=ct(t,".claude");Et(a)||(fn(a,{recursive:!0}),console.log(ke.green(" \u2713 Created .claude/"))),console.log(),console.log(ke.bold(" Next steps:")),console.log(` 1. Edit ${ke.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${ke.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${ke.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${ke.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Cs}from"commander";import At from"chalk";import{spawn as bn}from"child_process";import{existsSync as Es}from"fs";import{resolve as As}from"path";var kn=new Cs().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let t=mn(),o=e.port?parseInt(e.port,10):Is(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(At.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(At.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(At.bold(` Opening ${n}`)),console.log(),await Rs(n).catch(()=>!1))console.log(At.dim(" Dashboard is already running.")),e.open!==!1&&$n(n);else{console.log(At.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=Os(),r=bn(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&$n(n),await new Promise(a=>r.on("exit",()=>a()))}});function Is(){try{return P().dashboard.port||4202}catch{return 4202}}function Os(){let e=As(import.meta.dirname,"cli.js");return Es(e)?e:process.argv[1]||e}async function Rs(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function $n(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{bn(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}import{Command as Ds}from"commander";import ee from"chalk";var It=new Ds().name("token").description("scoped API tokens for external access (mesh peers, integrations)");It.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let t=new Jt,o=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=t.create({name:e.name,scopes:o,expiresInDays:n});console.log(),console.log(ee.bold(" Token created.")),console.log(),console.log(` id: ${ee.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||ee.dim("never")}`),console.log(),console.log(ee.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${ee.green.bold(s)}`),console.log(),console.log(ee.dim(" Use it via the Authorization header:")),console.log(ee.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(ee.red(` ${t.message}`)),process.exit(1)}});It.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Jt().list();if(e.length===0){console.log(ee.dim(`
7
+ No tokens issued.
8
+ `));return}console.log();for(let t of e){let o=t.revokedAt?ee.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?ee.red("expired"):ee.green("active");console.log(` ${ee.cyan(t.id)} ${o} ${t.name}`),console.log(ee.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(ee.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ee.red(` ${e.message}`)),process.exit(1)}});It.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Jt().revoke(e);t||(console.log(ee.red(` Token ${e} not found.`)),process.exit(1)),console.log(ee.green(`
9
+ \u2713 Revoked ${e} (${t.name})
10
+ `))}catch(t){console.log(ee.red(` ${t.message}`)),process.exit(1)}});import{Command as Oe}from"commander";import u from"chalk";import $e from"prompts";import{readFileSync as Ne,writeFileSync as lt,existsSync as G,mkdirSync as je,cpSync as ho,readdirSync as yo}from"fs";import{resolve as R,join as Pe}from"path";function X(){let e=R(process.cwd(),"agentx.json");if(!G(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ne(e,"utf-8"))}function me(e){return re(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(u.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(u.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(u.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var dt=new Oe().name("agent").description("manage agents \u2014 add, list, remove");dt.command("list").alias("ls").description("list configured agents").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${u.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(u.dim(` workspace: ${o.workspace}`)),n&&console.log(u.dim(` mentions: ${n}`))}console.log()});dt.command("add").description("add a new agent interactively").action(async()=>{let e=X(),t=await $e([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:R(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Pe(t.workspace,t.id);je(R(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-FPGN5VNY.js"),i=s(t.id,n,"19900",(...l)=>{console.log(u.dim(` ${l.join(" ")}`))}),r=R(process.cwd(),"src/wiki/SKILL.md"),a=R(import.meta.dirname,"../wiki/SKILL.md"),c=G(r)?r:a;G(c)&&(je(R(o,".claude/skills/wiki"),{recursive:!0}),ho(c,R(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await me(e),console.log(u.green(`
11
+ Agent "${t.id}" added`)),console.log(u.dim(` Workspace: ${o}`)),console.log(u.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});dt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=X();if(!t.agents?.[e]){console.log(u.red(` Agent "${e}" not found`));return}delete t.agents[e],await me(t),console.log(u.green(` Agent "${e}" removed from config (workspace preserved)`))});dt.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,t)=>{let o=X(),n=o.agents?.[e];if(n||(console.log(u.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(u.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):u.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":u.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||u.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let i=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(u.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(t.contextReferences!==void 0){let i=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(u.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(u.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let i=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(u.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(u.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await me(o),console.log(u.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(u.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var zt=new Oe().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");zt.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=X();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(u.bold(" Telegram:"));for(let[i,r]of Object.entries(t.accounts||{}))console.log(` ${u.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(u.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(u.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of o.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(u.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(u.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(u.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(u.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let i of s.routes||[])console.log(` ${i.project} -> agent: ${i.agent}`)}else console.log(u.dim(" GitLab: disabled"));console.log()});zt.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=X(),t=Object.keys(e.agents||{});if(!t.length){console.log(u.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await $e({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"Discord \u2014 bot via Discord developer portal",value:"discord"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await $e([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(u.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(u.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await me(e),console.log(u.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await $e([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await $e([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await me(e),je(R(process.cwd(),s.sessionDir),{recursive:!0}),console.log(u.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(u.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await $e([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.token)return;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await me(e),console.log(u.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await $e([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await $e([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await me(e),console.log(u.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(u.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(u.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(u.dim(` Secret token: ${s.webhookSecret}`)),console.log(u.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(u.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var gt=new Oe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");gt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?u.green("\u25CF"):u.dim("\u25CB");console.log(` ${n} ${u.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(u.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(u.dim(" No cron jobs configured")),console.log()});gt.command("add").description("add a cron job").action(async()=>{let e=X(),t=Object.keys(e.agents||{}),o=await $e([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await me(e),console.log(u.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});gt.command("enable <id>").description("enable a cron job").action(async e=>{let t=X();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,await me(t),console.log(u.green(` Cron "${e}" enabled`))});gt.command("disable <id>").description("disable a cron job").action(async e=>{let t=X();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await me(t),console.log(u.green(` Cron "${e}" disabled`))});var mt=new Oe().name("mesh").description("manage mesh peers \u2014 add, list, remove");mt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=X();if(console.log(),!e.mesh?.enabled)console.log(u.dim(" Mesh: disabled"));else{console.log(u.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=u.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=u.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${u.cyan(t.name)} ${u.dim(t.url)} ${o}`)}}console.log()});mt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=X(),t=await $e([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.67.108.119:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(u.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(u.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await me(e),console.log(u.green(` Peer "${t.name}" added`)),console.log()}});mt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=X();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await me(t),console.log(u.green(` Peer "${e}" removed`)))});mt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=X();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(u.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(u.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(u.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await me(t),console.log(u.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(u.dim(" Restart the daemon for the new cadence to take effect."))});var pt=new Oe().name("skill").description("manage skills \u2014 add to agent(s), list");pt.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,t)=>{let o=X(),n=R(e);if(!G(n)){console.log(u.red(` Skill not found: ${n}`));return}let s=G(Pe(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await $e({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(u.yellow(` Agent "${r}" not found, skipping`));continue}let c=R(a.workspace,".claude/skills",s);je(c,{recursive:!0}),G(Pe(n,"SKILL.md"))?ho(n,c,{recursive:!0}):n.endsWith(".md")&&ho(n,Pe(c,"SKILL.md")),console.log(u.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});pt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=R(o.workspace,".claude/skills"),s=G(n)?yo(n).filter(i=>!i.startsWith(".")):[];console.log(` ${u.cyan(t)}: ${s.length?s.join(", "):u.dim("(none)")}`)}console.log()});pt.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[R(n,"src",e,"SKILL.md"),R(n,"skills",e,"SKILL.md")],i=s.find(k=>G(k));if(!i){console.log(u.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(u.dim(` ${k}`));return}let r=Ne(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=P()}catch(k){console.log(u.red(` Can't load agentx.json: ${k.message}`));return}let p=Object.entries(l.agents||{}),d=t.agent?p.filter(([k])=>k===t.agent):p;if(d.length===0){console.log(u.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(u.bold(` Skill sync \u2014 ${e}`)),console.log(u.dim(` Source: ${i}`)),console.log(u.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(u.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let m=0,h=0,f=0,w=0;for(let[k,$]of d){let x=$.workspace;if(!x||!G(x)){console.log(` ${u.yellow("\u2717")} ${k.padEnd(22)} ${u.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let v=R(x,".claude/skills",e),b=R(v,"SKILL.md");if(!G(b)){if(!t.allWorkspaces){console.log(` ${u.dim("\xB7")} ${k.padEnd(22)} ${u.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(je(v,{recursive:!0}),lt(b,r)),console.log(` ${u.green("+")} ${k.padEnd(22)} ${u.dim("\u2192 seeded v"+c)}`),m++;continue}let C=Ne(b,"utf-8");if(o("sha256").update(C).digest("hex").slice(0,12)===a){console.log(` ${u.dim("=")} ${k.padEnd(22)} ${u.dim("up to date (v"+c+")")}`),f++;continue}let M=(C.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||lt(b,r),console.log(` ${u.yellow("\u21BB")} ${k.padEnd(22)} ${u.dim(`v${M} \u2192 v${c}`)}`),h++}console.log();let y=t.dryRun?"would":"did";console.log(u.dim(` Summary: ${y} seed ${m}, ${y} update ${h}, ${f} already current, ${w} skipped.`)),t.dryRun&&(m>0||h>0)&&console.log(u.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});pt.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:t}=await import("./loader-5CA3O5GM.js"),{auditAll:o}=await import("./audit-JU3HWISB.js"),{loadReferences:n}=await import("./loader-6IHUCPVO.js"),{loadRecipes:s}=await import("./recipes-EPLE2SNT.js"),i=[];if(e.workspace){let h=X().agents?.[e.workspace];h||(console.log(u.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(R(h.workspace))}else if(e.allWorkspaces){let m=X();for(let h of Object.values(m.agents||{}))h?.workspace&&i.push(R(h.workspace))}else i.push(R(e.cwd));let r=R(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(m=>t(m)))).flat(),[l,p]=await Promise.all([n(r),s(r)]),d=o({skills:c,references:l,recipes:p});if(e.json)console.log(JSON.stringify(d.map(m=>({name:m.name,verdict:m.verdict,reasons:m.reasons,path:m.skill?.path})),null,2));else{let m={PASS:0,REVIEW:0,FAILING:0};for(let h of d)m[h.verdict]++;console.log();for(let h of d){let f=h.verdict==="PASS"?u.green("PASS "):h.verdict==="REVIEW"?u.yellow("REVIEW "):u.red("FAILING");console.log(` ${f} ${u.bold(h.name)}${h.skill?.path?u.dim(` (${h.skill.path})`):""}`);for(let w of h.reasons)console.log(` ${u.dim("\xB7")} ${w}`)}console.log(),console.log(` ${u.green(`${m.PASS} PASS`)} ${u.yellow(`${m.REVIEW} REVIEW`)} ${u.red(`${m.FAILING} FAILING`)}`),console.log()}process.exit(d.some(m=>m.verdict==="FAILING")?1:0)});var Ot=new Oe().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Ot.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(u.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=R(t.cwd),n=R(o,"references/example"),s=R(o,"references/recipes/example.yaml");G(n)||(console.log(u.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=R(o,".agentx/references",e),r=R(o,".agentx/references/recipes");je(i,{recursive:!0}),je(r,{recursive:!0});let a=yo(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let m=Pe(i,d);if(G(m)&&!t.force){console.log(u.dim(` skip ${m} (exists; --force to overwrite)`)),l++;continue}let f=Ne(Pe(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);lt(m,f),console.log(u.green(` + ${m}`)),c++}let p=Pe(r,`${e}.yaml`);if(G(p)&&!t.force)console.log(u.dim(` skip ${p} (exists; --force to overwrite)`)),l++;else if(G(s)){let d=Ne(s,"utf-8").replaceAll("example.",`${e}.`);lt(p,d),console.log(u.green(` + ${p}`)),c++}console.log(),console.log(u.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(u.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(u.dim(" 2. agentx skill audit # verify references resolve")),console.log(u.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Ot.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.noqta.tn)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(u.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-5CA3O5GM.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-XJXQXXIO.js"),i=R(t.cwd),r=t.from?String(t.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await o(i),c=n(a,{namespace:e,filter:r,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(u.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(u.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(u.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let p=s(c,e),d=R(t.referencesCwd||t.cwd),m=R(d,".agentx/references",e);if(!t.write){console.log(),console.log(u.dim(` Dry-run \u2014 would write to ${m}/`));for(let[w,y]of Object.entries(p))console.log(u.cyan(`
12
+ --- ${w} ---`)),console.log(y.split(`
13
+ `).slice(0,30).map(k=>` ${k}`).join(`
14
+ `)),y.split(`
15
+ `).length>30&&console.log(u.dim(` \u2026 (${y.split(`
16
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(u.dim(` Re-run with --write to commit these to ${m}/`)),console.log();return}je(m,{recursive:!0});let h=0,f=0;for(let[w,y]of Object.entries(p)){let k=Pe(m,w);if(G(k)&&!t.force){console.log(u.dim(` skip ${k} (exists; --force to overwrite)`)),f++;continue}lt(k,y),console.log(u.green(` + ${k}`)),h++}console.log(),console.log(u.dim(` ${h} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(u.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Ot.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-6IHUCPVO.js"),o=await t(R(e.cwd)),n=[...o.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(u.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=o.sourceById.get(s.id);console.log(` ${u.cyan(s.id)} ${u.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(u.dim(` ${i}`))}console.log(),console.log(u.dim(` ${n.length} reference(s) loaded.`)),console.log()});var wo=new Oe().name("hook").description("manage hooks \u2014 add to agent workspace");wo.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=X().agents?.[e];if(!o){console.log(u.red(` Agent "${e}" not found`));return}let n=R(o.workspace,".claude/settings.json"),s=G(n)?JSON.parse(Ne(n,"utf-8")):{},i=await $e([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),je(R(o.workspace,".claude"),{recursive:!0}),lt(n,JSON.stringify(s,null,2)),console.log(u.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var $o=new Oe().name("migrate").description("import configuration from OpenClaw or other tools");$o.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let o=[e,R(process.env.HOME||"",".openclaw/openclaw.json"),R(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),n;for(let h of o)if(h&&G(h)){n=h;break}if(!n){console.log(u.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(u.dim(` Reading: ${n}`));let s=JSON.parse(Ne(n,"utf-8")),i=G(R(process.cwd(),"agentx.json"))?X():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let h of a)h.match?.channel==="telegram"&&(c[h.match.accountId]=h.agentId);r.find(h=>h.id==="main"||h.default)&&(c.default="main");let l=0;for(let h of r){if(h.workspace?.startsWith("/data"))continue;let f=h.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=h.groupChat?.mentionPatterns||[];if(w.some(y=>y===f)||w.push(f),i.agents[f]={name:h.name,workspace:h.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:h.id==="main"?2:1,systemPrompt:`You are ${h.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){je(R(h.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-FPGN5VNY.js");y(f,i.agents[f])}}console.log(` ${u.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let p=s.channels?.telegram?.accounts||{},d=0;for(let[h,f]of Object.entries(p)){if(!f.botToken)continue;let y=c[h]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[h]={token:f.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${u.green(d)} Telegram accounts imported`);let m=R(n,"../cron/jobs.json");if(G(m)){let h=JSON.parse(Ne(m,"utf-8")),f=0;for(let w of h.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},f++}console.log(` ${u.green(f)} cron jobs imported`)}t.dryRun?(console.log(u.yellow(`
17
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await me(i),console.log(u.green(`
18
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Me=new Oe().name("config").description("validate and inspect configuration");Me.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let t=P(e.config);console.log(u.green(" \u2713 Config valid")),console.log(u.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(u.dim(` Bind: ${t.node.bind}`)),console.log(u.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(u.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(u.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(u.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(u.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(u.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let n=Ut(t);if(n.length){console.log(),console.log(u.yellow(" Warnings:"));for(let s of n)console.log(u.yellow(` \u26A0 ${s}`))}else console.log(u.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.agents)){let r=i.workspace,a=G(R(r,".claude")),c=G(R(r,"CLAUDE.md")),l=G(R(r,".claude/settings.json")),p=G(R(r,".claude/skills"))?yo(R(r,".claude/skills")).filter(m=>!m.startsWith(".")).length:0,d=[a?u.green("\u2713"):u.red("\u2717"),".claude",c?u.green("\u2713"):u.yellow("\u25CB"),"CLAUDE.md",l?u.green("\u2713"):u.yellow("\u25CB"),"settings",`${p} skills`];console.log(` ${u.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(u.red(` \u2717 ${t.message}`))}console.log()});Me.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=P(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(u.red(t.message))}});function Ts(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function fo(e){return e===void 0?u.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Me.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-53XGR2NT.js"),{expandEnvVars:r}=await import("./config-QXWKEQON.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(u.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),p=i(l,e);t.json?console.log(JSON.stringify(p)):console.log(fo(p))});Me.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-53XGR2NT.js"),r=Ts(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(u.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would become: ${fo(c)}`)):(console.log(u.green(` \u2713 ${u.cyan(e)} = ${fo(c)}`)),a.reloaded?console.log(u.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(u.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Me.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-53XGR2NT.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(u.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(u.dim(` (no-op) ${u.cyan(e)} was not set`));return}t.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would be removed`)):(console.log(u.green(` \u2713 ${u.cyan(e)} removed`)),i.reloaded&&console.log(u.dim(" Daemon hot-reloaded.")))});Me.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let t=!1,o=0,n;try{let d=P(e.config);t=!!d.business?.enabled,o=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(u.bold(" Governance flags")),console.log(),n&&(console.log(u.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?u.green:s==="shadow"?u.cyan:s==="off"?u.dim:u.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":u.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let p=a?u.green("active"):r?u.yellow("env=true but business.enabled=false \u2192 inactive"):u.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${p}`),console.log(u.dim(` business.enabled ${t?u.green("true"):u.dim("false")}`)),console.log(u.dim(` business.projects[] ${o}`)),console.log(),console.log(u.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(u.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as _s}from"commander";import Le from"chalk";import{resolve as We}from"path";import{existsSync as Ps}from"fs";var Re=new _s().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function He(e){let t=We(e,".agentx/db.sqlite");Ps(t)||(console.log(Le.red(` No SQLite at ${t}`)),console.log(Le.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=en({path:t});return o||(console.log(Le.red(` Could not open ${t}`)),console.log(Le.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Ke(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Le.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}Re.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
19
+ SELECT agent_id, channel, status, duration_ms,
20
+ input_tokens, output_tokens,
21
+ substr(message_preview, 1, 60) AS message,
22
+ started_at
23
+ FROM task_history
24
+ ${o.length?"WHERE "+o.join(" AND "):""}
25
+ ORDER BY started_at DESC
26
+ LIMIT @limit
27
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Ke(i,!!e.json)});Re.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(o.push("reason = @reason"),n.reason=e.reason);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
28
+ SELECT agent_id, reason, COUNT(*) AS n,
29
+ ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
30
+ MAX(last_turn_input_tokens) AS max_input_tokens
31
+ FROM rotations
32
+ ${s}
33
+ GROUP BY agent_id, reason
34
+ ORDER BY n DESC
35
+ `:`
36
+ SELECT agent_id, channel, reason, last_turn_input_tokens, rotated_at
37
+ FROM rotations
38
+ ${s}
39
+ ORDER BY rotated_at DESC
40
+ LIMIT @limit
41
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Ke(r,!!e.json)});Re.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("day = @day"),n.day=e.day);let s=`
42
+ SELECT day, agent_id, model, tasks,
43
+ input_tokens AS in_tok, output_tokens AS out_tok,
44
+ cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
45
+ FROM usage_daily
46
+ ${o.length?"WHERE "+o.join(" AND "):""}
47
+ ORDER BY day DESC, agent_id
48
+ `,i=t.prepare(s).all(n);Ke(i,!!e.json)});Re.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),o=[],n={};e.channel&&(o.push("channel = @channel"),n.channel=e.channel),e.kind&&(o.push("kind = @kind"),n.kind=e.kind);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
49
+ SELECT channel, kind, deciding_stage, COUNT(*) AS n
50
+ FROM route_traces
51
+ ${s}
52
+ GROUP BY channel, kind, deciding_stage
53
+ ORDER BY n DESC
54
+ `:`
55
+ SELECT channel, chat_id, kind, deciding_stage, agent_id,
56
+ substr(reason, 1, 60) AS reason, at
57
+ FROM route_traces
58
+ ${s}
59
+ ORDER BY at DESC
60
+ LIMIT @limit
61
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Ke(r,!!e.json)});Re.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent);let s=`
62
+ SELECT agent_id, channel, duration_ms,
63
+ substr(error, 1, 120) AS error,
64
+ started_at
65
+ FROM task_history
66
+ WHERE ${o.join(" AND ")}
67
+ ORDER BY started_at DESC
68
+ LIMIT @limit
69
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Ke(i,!!e.json)});Re.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=He(We(e.cwd)),n=t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:t.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));Ke(n,!!e.json)});Re.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,t)=>{let o=He(We(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Le.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Le.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();Ke(n,!!t.json)}catch(n){console.log(Le.red(` ${n.message}`)),process.exit(1)}});import{Command as Ls}from"commander";import _ from"chalk";import{mkdtempSync as Ws}from"fs";import{tmpdir as Fs}from"os";import{resolve as xn,join as Sn}from"path";import{existsSync as Bs}from"fs";import Us from"better-sqlite3";function vn(e,t,o,n=[]){let s=new Map;for(let c of t)s.set(c.id,c);let i=[];for(let c of o)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(f){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${f?.message??f}`})}continue}let l=c.decision,p=s.get(l.eventId);if(!p){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=Ns(l),m={id:p.id,ts:p.ts,source:p.source,sourceEventId:p.sourceEventId,project:p.project,subject:p.subject,intent:p.intent,rawJson:p.rawJson},h=Xo(e,m,d,()=>l.decidedAt);a+=1,(h.outcome!==l.outcome||h.agentId!==l.agentId)&&r.push({eventId:p.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:h.agentId,outcome:h.outcome},reason:Ms(l,h)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function Ns(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Ms(e,t){return e.outcome==="dispatched"&&t.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&t.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==t.agentId?`agent-changed (recorded=${e.agentId} replayed=${t.agentId})`:e.outcome!==t.outcome?`outcome-changed (recorded=${e.outcome} replayed=${t.outcome})`:"unknown"}var Fe=new Ls().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function ut(e){let t=xn(e.cwd??process.cwd()),o=xn(t,e.path??".agentx/intent/ledger.sqlite");Bs(o)||(console.log(_.red(` No ledger at ${o}`)),console.log(_.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new Us(o,{readonly:!0})}catch(n){console.log(_.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(_.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Ve(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(_.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}function qs(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Gt(e){if(!e)return;let t=qs(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(_.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}Fe.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let t=ut(e),o=Gt(e.since),n=o!==void 0?"WHERE ts >= @since":"",s=o!==void 0?"WHERE decided_at >= @since":"",i=n,r=t.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:o}),a=t.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:o}).n,c=t.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:o}),l=t.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:o}).n,p=t.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:o}),d=t.prepare(`
70
+ SELECT COUNT(*) as n FROM intent_decisions d
71
+ LEFT JOIN intent_resolutions r
72
+ ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
73
+ WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
74
+ `).get().n;if(e.json){console.log(JSON.stringify({since:o??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:p,inFlight:d},null,2));return}console.log(_.bold("Events by source")),Ve(r,!1),console.log(),console.log(_.bold(`Decisions: ${a}`)),Ve(c,!1),console.log(),console.log(_.bold(`Divergences: ${l}`)),Ve(p,!1),console.log(),console.log(_.bold(`In-flight (dispatched, no resolution): ${d}`))});Fe.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=ut(e),o=Gt(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
75
+ SELECT
76
+ datetime(ts/1000, 'unixepoch') AS at,
77
+ source,
78
+ decided_by,
79
+ ledger_outcome AS L_outcome,
80
+ COALESCE(ledger_agent_id, '-') AS L_agent,
81
+ legacy_outcome AS X_outcome,
82
+ COALESCE(legacy_agent_id, '-') AS X_agent,
83
+ substr(COALESCE(legacy_reason, ledger_reason, ''), 1, 60) AS reason
84
+ FROM intent_divergences
85
+ ${i}
86
+ ORDER BY ts DESC
87
+ LIMIT @limit
88
+ `).all(s);Ve(r,!!e.json)});Fe.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=ut(e),o=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(o.push("e.source = @source"),n.source=e.source);let s=t.prepare(`
89
+ SELECT
90
+ datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
91
+ e.source,
92
+ d.decided_by,
93
+ COALESCE(d.agent_id, '-') AS agent,
94
+ COALESCE(e.project, '-') AS project,
95
+ COALESCE(e.subject, '-') AS subject,
96
+ ROUND((strftime('%s', 'now')*1000 - d.decided_at) / 1000.0) AS age_s
97
+ FROM intent_decisions d
98
+ JOIN intent_events e ON e.id = d.event_id
99
+ LEFT JOIN intent_resolutions r
100
+ ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
101
+ WHERE ${o.join(" AND ")}
102
+ ORDER BY d.decided_at DESC
103
+ LIMIT @limit
104
+ `).all(n);Ve(s,!!e.json)});Fe.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let t=ut(e),o=Gt(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
105
+ SELECT
106
+ datetime(ts/1000, 'unixepoch') AS at,
107
+ source,
108
+ COALESCE(project, '-') AS project,
109
+ COALESCE(subject, '-') AS subject,
110
+ COALESCE(intent, '-') AS intent
111
+ FROM intent_events
112
+ ${i}
113
+ ORDER BY ts DESC
114
+ LIMIT @limit
115
+ `).all(s);Ve(r,!!e.json)});Fe.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,t)=>{let o=ut(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(_.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=o.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(_.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(_.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(_.dim(` project: ${n}`)),s&&console.log(_.dim(` subject: ${s}`)),process.exit(1))}let i=o.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
116
+ FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(_.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,m)=>`@id${m}`).join(", "),c=Object.fromEntries(r.map((d,m)=>[`id${m}`,d])),l=o.prepare(`
117
+ SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
118
+ r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
119
+ FROM intent_decisions d
120
+ LEFT JOIN intent_resolutions r
121
+ ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
122
+ WHERE d.event_id IN (${a})
123
+ ORDER BY d.decided_at ASC
124
+ `).all(c);if(t.json){let d=i.map(m=>({event:m,decisions:l.filter(h=>h.event_id===m.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let p=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&p.add(d.agent_id);console.log(),console.log(_.bold(` Lineage for ${_.cyan(n+":"+s)}`)),console.log(_.dim(` ${i.length} event(s), ${l.length} decision(s), ${p.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let m=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${_.dim(m)} ${_.bold(d.id)} ${_.dim(`(${d.source}/${d.intent})`)}`);let h=l.filter(f=>f.event_id===d.id);if(h.length===0){console.log(_.dim(" (no decisions yet)"));continue}for(let f of h){let w=f.outcome==="dispatched"?_.green(f.outcome):f.outcome==="dropped"?_.dim(f.outcome):_.yellow(f.outcome),y=f.agent_id?_.cyan(f.agent_id):_.dim("-"),k=f.reason?_.dim(` \u2014 ${f.reason.slice(0,60)}`):"";if(console.log(` ${_.dim(f.decided_by)} \u2192 ${w} ${y}${k}`),f.resolution_status){let $=f.resolution_status==="ok"?_.green(f.resolution_status):_.red(f.resolution_status),x=f.duration_ms?`${(f.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${_.dim("resolved")} ${$} ${_.dim(x)}`)}else f.outcome==="dispatched"&&console.log(` ${_.yellow("(in-flight, no resolution)")}`)}}console.log()});Fe.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let t=ut(e),o=Gt(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=t.prepare(`
125
+ SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
126
+ FROM intent_events
127
+ ${n.length?"WHERE "+n.join(" AND "):""}
128
+ ORDER BY ts ASC
129
+ ${i}
130
+ `).all(s).map(f=>({id:f.id,ts:f.ts,source:f.source,sourceEventId:f.source_event_id,project:f.project,subject:f.subject,intent:f.intent,rawJson:f.raw_json}));if(r.length===0){console.log(_.dim(" (no events match filter)"));return}let a=new Set(r.map(f=>f.id)),c=r.map((f,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((f,w)=>[`id${w}`,f.id])),p=t.prepare(`
131
+ SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
132
+ FROM intent_decisions
133
+ WHERE event_id IN (${c})
134
+ `).all(l).map(f=>({eventId:f.event_id,decidedAt:f.decided_at,decidedBy:f.decided_by,agentId:f.agent_id,outcome:f.outcome,reason:f.reason})),d=t.prepare(`
135
+ SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
136
+ FROM intent_resolutions
137
+ WHERE decision_event_id IN (${c})
138
+ `).all(l).map(f=>({decisionEventId:f.decision_event_id,decisionDecidedBy:f.decision_decided_by,resolvedAt:f.resolved_at,status:f.status,durationMs:f.duration_ms,resultSummary:f.result_summary})),m=Ws(Sn(Fs(),"agentx-ledger-replay-")),h=new Ko({path:Sn(m,"target.sqlite")});try{let f=vn(h,r,p,d);if(e.json){console.log(JSON.stringify(f,null,2));return}console.log(_.bold(`Replayed ${f.eventsCount} events, ${f.decisionsCount} decisions, ${d.length} resolutions`)),f.divergences.length===0?console.log(_.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(_.red(` \u2717 ${f.divergences.length} divergences`)),Ve(f.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{h.close()}});import{Command as Js}from"commander";import W from"chalk";import ht from"prompts";var Qe=new Js().name("backlog").description("manage the local backlog used by business workSource=backlog");function Rt(e){let t=P(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new cn(n)}}function zs(e){return e?W.cyan(`${e.type}:${e.project}#${e.iid}`):W.dim("manual")}function Gs(e){return{todo:W.gray("todo"),doing:W.yellow("doing"),blocked:W.red("blocked"),done:W.green("done")}[e]}Qe.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=Rt(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(W.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?W.magenta(`@${n.assignee}`):W.dim("unassigned");console.log(` ${Gs(n.status).padEnd(7)} ${zs(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(W.dim(` ${n.source.url}`))}console.log(),console.log(W.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Qe.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=Rt(o.config);n.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(W.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=ln([t],i.source,n.config),a=await po(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(W.dim(" sync:"),...c));console.log(a.ok?W.dim(` synced -> ${a.url??i.source.type}`):W.yellow(` sync failed: ${a.error}`))}});Qe.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=Rt(t.config);o.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(W.green(` done: ${s.title}`)),s.source){let i=await po(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(W.dim(" sync:"),...r));console.log(i.ok?W.dim(` synced -> ${i.url??s.source.type}`):W.yellow(` sync failed: ${i.error}`))}});Qe.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=Rt(t.config);o.remove(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1)),console.log(W.green(` removed ${e}`))});Qe.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=Rt(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(W.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ht({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(W.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(W.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Hs(t.config):Ks(t.config);y.length?(i=(await ht({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await ht({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await ht({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(W.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Vs(t.config,i,a):await Qs(t.config,i,a);if(!c.length){console.log(W.yellow(" no open issues matched"));return}console.log(W.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,p=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let k=mo({type:s,project:l,iid:y.iid,url:y.url}),$=p.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${$?W.dim(" (already imported)"):""}`,value:y,disabled:$}}),h=(await ht({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!h.length){console.log(W.dim(" nothing selected"));return}let f=h.map(y=>{let k={type:s,host:s==="gitlab"?Ys(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:mo(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=t.store.addMany(f);console.log(W.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(W.dim(` ${y.id} \u2014 ${y.title}`))});function Ys(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Hs(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function Ks(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function Vs(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Qs(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(jn)}i=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(jn):[]}function jn(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as ei}from"commander";import N from"chalk";import{existsSync as ti,readFileSync as oi}from"fs";import{resolve as ni}from"path";import si from"prompts";import Xs from"cronstrue";var bo={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Yt={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function Ce(e){try{return Xs.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function Zs(e){if(/\b(noon|midday)\b/.test(e))return Yt.noon;if(/\bmidnight\b/.test(e))return Yt.midnight;let t=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(t){let o=parseInt(t[1],10),n=t[2]?parseInt(t[2],10):0,s=t[3];return s==="pm"&&o<12&&(o+=12),s==="am"&&o===12&&(o=0),o>23||n>59?null:{h:o,m:n}}return null}function ko(e){let t=e.trim().toLowerCase();if(!t)return null;let o;if(o=t.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let d=parseInt(o[1],10);return d<1||d>59?null:{cron:`*/${d} * * * *`,human:Ce(`*/${d} * * * *`),matched:o[0]}}if(/\bevery\s+minute\b/.test(t))return{cron:"* * * * *",human:Ce("* * * * *"),matched:"every minute"};if(o=t.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let d=parseInt(o[1],10);return d<1||d>23?null:{cron:`0 */${d} * * *`,human:Ce(`0 */${d} * * *`),matched:o[0]}}if(/\b(every hour|hourly)\b/.test(t))return{cron:"0 * * * *",human:Ce("0 * * * *"),matched:"every hour"};let n=Zs(t),s=null;for(let[d,m]of Object.entries(Yt))if(!(d==="noon"||d==="midnight")&&new RegExp(`\\b(every\\s+)?${d}s?\\b`).test(t)){s=m;break}let i=n||s,r=t.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let d=r[1],m=1;if(d==="last"||(/^\d+(st|nd|rd|th)?$/.test(d)?m=parseInt(d,10):d==="first"||d==="1st"?m=1:d==="2nd"?m=2:d==="3rd"&&(m=3),m<1||m>31))return null;let h=i||{h:9,m:0},f=`${h.m} ${h.h} ${m} * *`;return{cron:f,human:Ce(f),matched:r[0]}}let a=[],c=Object.keys(bo).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),p=t.match(l);if(p){let d=p[1];for(let m of Object.keys(bo))if(new RegExp(`\\b${m}s?\\b`).test(d)){let h=bo[m];a.includes(h)||a.push(h)}}if(a.length){let d=i||{h:9,m:0};a.sort((f,w)=>f-w);let m=a.join(","),h=`${d.m} ${d.h} * * ${m}`;return{cron:h,human:Ce(h),matched:`on ${m}`}}if(/\b(weekday|workday|business day)s?\b/.test(t)){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * 1-5`;return{cron:m,human:Ce(m),matched:"weekdays"}}if(/\bweekends?\b/.test(t)){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * 0,6`;return{cron:m,human:Ce(m),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(t)||s){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * *`;return{cron:m,human:Ce(m),matched:s&&Object.entries(Yt).find(([,h])=>h===s)?.[0]||"daily"}}if(n){let d=`${n.m} ${n.h} * * *`;return{cron:d,human:Ce(d),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Cn(e,t){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${t}`}function En(e){let t=e||ni(process.cwd(),"agentx.json");return ti(t)||(console.log(N.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(oi(t,"utf-8"))}function ii(e){return e?e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t==="log"||t==="notify"||t==="disable"):["log"]}async function ri(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(N.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await si([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp/discord):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(N.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Be=new ei().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Be.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>","IANA timezone (default: Africa/Tunis)","Africa/Tunis").option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){Be.help();return}t.agent||(console.log(N.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(N.red(' --do "<prompt>" is required')),process.exit(1));let o=ko(e);o||(console.log(N.red(` Couldn't parse: "${e}"`)),console.log(N.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(N.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(N.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=En(t.config),s=Qo(n);n.agents?.[t.agent]||(console.log(N.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(N.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=ii(t.onError),r=await ri(t.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=t.id||Cn(o.matched,t.agent),c={enabled:!t.disabled,schedule:o.cron,timezone:t.timezone,agent:t.agent,prompt:t.do,timeout:parseInt(t.timeout,10),onError:i};t.model&&(c.model=t.model),r&&(c.notify=r);let l=await re(d=>Q(d,`crons.${a}`,c),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(N.red(` \u2717 ${l.error}`)),process.exit(1));let p=t.dryRun?"would add":"Added";console.log(N.green(` \u2713 ${p} cron ${N.cyan(a)}`)),console.log(N.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(N.dim(` Agent: ${t.agent}`)),r&&console.log(N.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(N.dim(` On error: ${i.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=En(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(N.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?N.green("\u25CF"):N.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${N.cyan(s.padEnd(32))} ${N.dim(i.schedule.padEnd(14))} ${N.dim("\u2192")} ${i.agent}`),console.log(N.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(N.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Be.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await re(s=>{if(!Ye(s,`crons.${o}`))throw new Error(`cron "${o}" not found`);Q(s,`crons.${o}.enabled`,t)});n.success||(console.log(N.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await re(o=>{if(!Ye(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Zo(o,`crons.${e}`)});t.success||(console.log(N.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ko(t);o||(console.log(N.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(N.green(` "${t}"`)),console.log(N.dim(` \u2192 ${o.cron}`)),console.log(N.dim(` \u2192 ${o.human}`))});import{Command as Di}from"commander";import Ze from"chalk";import U from"chalk";import Dt from"prompts";import{readFileSync as ai,writeFileSync as ci,existsSync as li}from"fs";import{resolve as An}from"path";var di=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function gi(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function vo(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function In(e=".env"){let t=An(e);if(!li(t))return[];let o=ai(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(di);i?n.push({kind:"kv",key:i[1],value:gi(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function mi(e){return e.map(t=>t.kind==="kv"?`${t.key}=${vo(t.value)}`:t.raw).join(`
139
+ `)+`
140
+ `}function Xe(e,t,o=".env"){let n=An(o),s=In(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${vo(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${vo(t)}`})),ci(n,mi(s))}function xo(e,t=".env"){return In(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var On="https://t.me/BotFather";async function pi(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function ui(e,t){let o=Date.now()+t,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Rn(e={}){console.log(),console.log(U.bold(" Connect Telegram")),console.log(),console.log(U.dim(` 1. Open ${On}`)),console.log(U.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(U.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Dt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(x,[On],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Dt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(U.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await pi(o.trim());n||(console.log(U.red("\u2717 invalid or revoked")),process.exit(1)),console.log(U.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(U.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(U.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=e.agent;p||(p=(await Dt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),p||(console.log(U.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},m=e.account||p;d[m]&&d[m].agentBinding!==p&&(m=(await Dt({type:"text",name:"account",message:`Account "${m}" is already in use. Pick a different label:`,initial:`${p}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),m||(console.log(U.red(" Aborted")),process.exit(1));let h=`TG_${m.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Xe(h,o.trim()),process.env[h]=o.trim();let f=await re($=>{Q($,"channels.telegram.enabled",!0),Q($,`channels.telegram.accounts.${m}`,{token:`\${${h}}`,agentBinding:p});let x=Ye($,`agents.${p}.mentions`)||[],v=`@${n.username}`;x.includes(v)||(x.push(v),Q($,`agents.${p}.mentions`,x))},{configPath:e.configPath});if(f.success||(console.log(U.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(U.green(` \u2713 Bot @${n.username} bound to agent "${p}"`)),console.log(U.dim(` Token stored in .env as ${h}`)),console.log(U.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(U.dim(" Daemon hot-reloaded.")):console.log(U.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Dt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(U.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(U.dim(" Waiting up to 90s..."));let y=await ui(o.trim(),9e4);if(!y){console.log(U.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(U.dim(" agentx config set notifications.destination.channel telegram")),console.log(U.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(U.dim(` agentx config set notifications.destination.accountId ${m}`));return}let k=await re($=>{Q($,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:m})},{configPath:e.configPath});if(!k.success){console.log(U.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(U.green(" \u2713 Default --notify target set")),console.log(U.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(U.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(U.dim(" Daemon hot-reloaded."))}import K from"chalk";import Ht from"prompts";import{spawn as hi}from"child_process";var Dn="https://discord.com/developers/applications",fi="67584";async function yi(e){try{let t=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return t.ok?await t.json():null}catch{return null}}function Tn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";hi(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function _n(e={}){console.log(),console.log(K.bold(" Connect Discord")),console.log(),console.log(K.dim(" 1. Open the Discord Developer Portal")),console.log(K.dim(` ${Dn}`)),console.log(K.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(K.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(K.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:t}=await Ht({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});t&&Tn(Dn);let{token:o}=await Ht({type:"password",name:"token",message:"Paste the bot token:",validate:y=>y.trim().length>20||"that looks too short for a Discord token"});o||(console.log(K.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yi(o.trim());n||(console.log(K.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=n.discriminator&&n.discriminator!=="0"?`${n.username}#${n.discriminator}`:n.username;console.log(K.green(`\u2713 ${s} (bot id ${n.id})`));let{readFileSync:i,existsSync:r}=await import("fs"),{resolve:a}=await import("path"),c=e.configPath||a(process.cwd(),"agentx.json");r(c)||(console.log(K.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let l=JSON.parse(i(c,"utf-8")),p=Object.keys(l.agents||{});p.length===0&&(console.log(K.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Ht({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:p.map(k=>({title:k,value:k})),initial:0})).agent),d||(console.log(K.red(" Aborted")),process.exit(1));let m="DISCORD_BOT_TOKEN";Xe(m,o.trim()),process.env[m]=o.trim();let h=await re(y=>{Q(y,"channels.discord.enabled",!0),Q(y,"channels.discord.token",`\${${m}}`),Q(y,"channels.discord.agentBinding",d)},{configPath:e.configPath});h.success||(console.log(K.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(K.green(` \u2713 Discord bot ${s} bound to agent "${d}"`)),console.log(K.dim(` Token stored in .env as ${m}`)),h.reloaded?console.log(K.dim(" Daemon hot-reloaded.")):console.log(K.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(K.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${fi}`;console.log(` ${K.cyan(f)}`),console.log();let{openInstall:w}=await Ht({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});w&&Tn(f),console.log(),console.log(K.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(K.dim(" Mention the bot in any channel to route messages to the agent."))}import Y from"chalk";import So from"prompts";import{existsSync as Co,mkdirSync as wi,readdirSync as $i,readFileSync as Pn}from"fs";import{resolve as jo}from"path";var bi=".agentx/whatsapp-sessions";function ki(){let e=jo(process.cwd(),".agentx/daemon.pid");if(!Co(e))return!1;try{let t=parseInt(Pn(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function vi(e){if(!Co(e))return!1;try{return $i(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function xi(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Y.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Y.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;wi(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(p=>{let m=setTimeout(()=>{t(Y.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}p(!1)},12e4);l.ev.on("connection.update",async h=>{if(h.qr){t(Y.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:f}=await import("qrcode-terminal");f.generate(h.qr,{small:!0})}catch{t(` QR: ${h.qr}`)}t("")}if(h.connection==="open"){clearTimeout(m),t(Y.green(" \u2713 Paired"));try{l.end(void 0)}catch{}p(!0)}h.connection==="close"&&!h.qr&&h.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(m),t(Y.red(" \u2717 Authorization failed \u2014 rescan required")),p(!1))})})}async function Nn(e={}){if(console.log(),console.log(Y.bold(" Connect WhatsApp")),console.log(),ki()){console.log(Y.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Y.dim(" agentx daemon stop")),console.log();let{cont:l}=await So({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Y.red(" Aborted")),process.exit(1))}let t=e.configPath||jo(process.cwd(),"agentx.json");Co(t)||(console.log(Y.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Pn(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||bi,s=jo(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(Y.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await So({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(p=>({title:p,value:p})),initial:0})).agent),r||(console.log(Y.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(vi(s)&&a){let{keep:l}=await So({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Y.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await xi(s,p=>console.log(p))||(console.log(Y.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Q(l,"channels.whatsapp.enabled",!0),Q(l,"channels.whatsapp.sessionDir",n),Q(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(Y.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Y.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(Y.dim(` Session: ${n}`)),console.log(Y.dim(" Start the daemon to begin receiving:")),console.log(Y.dim(" agentx daemon start")),console.log(Y.dim(" Add routes later with:")),console.log(Y.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Si}from"crypto";import Z from"chalk";import Mn from"prompts";var Kt="agentx-mesh:",Vt="//join/";function ji(e){return Buffer.from(e,"utf-8").toString("base64url")}function Ci(e){return Buffer.from(e,"base64url").toString("utf-8")}function Ei(e){return`${Kt}${Vt}${ji(JSON.stringify(e))}`}function Ai(e){if(!e.startsWith(`${Kt}${Vt}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kt}${Vt}\u2026`);let t=e.slice(Kt.length+Vt.length),o=JSON.parse(Ci(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function Ii(){return Si(32).toString("hex")}function Oi(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Ri(e){return e?.node?.name||e?.node?.id||"node"}async function Ln(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Z.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=xo("MESH_TOKEN");r||(r=Ii(),Xe("MESH_TOKEN",r),console.log(Z.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Oi(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Mn({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:m=>/^https?:\/\//.test(m)||"must start with http:// or https://"});d||(console.log(Z.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Q(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Z.red(` \u2717 ${l.error}`)),process.exit(1));let p=Ei({url:a,token:r,name:Ri(i),version:1});console.log(),console.log(Z.bold(" Mesh invite")),console.log(),console.log(` ${Z.cyan(p)}`),console.log(),console.log(Z.dim(" Run on the other node:")),console.log(Z.dim(` agentx connect mesh join "${p}"`)),console.log(),console.log(Z.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Wn(e,t={}){let o;try{o=Ai(e)}catch(i){console.log(Z.red(` \u2717 ${i.message}`)),process.exit(1)}let n=xo("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Mn({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Z.red(" Aborted (keeping existing .env)")),process.exit(1))}Xe("MESH_TOKEN",o.token);let s=await re(i=>{Q(i,"mesh.enabled",!0);let r=Ye(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Q(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Z.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Z.green(" \u2713 Joined mesh")),console.log(Z.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Z.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(Z.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Z.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Z.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var et=new Di().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");et.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Rn({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});et.command("discord").description("pair a Discord bot \u2014 verify token, emit install URL, save to .env").option("--agent <id>","agent to bind the bot to").option("-c, --config <path>","path to agentx.json").action(async e=>{await _n({agent:e.agent,configPath:e.config})});et.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Nn({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Fn=et.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Fn.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Ln({url:e.url,configPath:e.config})});Fn.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Wn(e,{configPath:t.config})});et.action(()=>{console.log(),console.log(Ze.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ze.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ze.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${Ze.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ze.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ze.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ze.dim(" GitLab connect is the next slice.")),console.log()});import{Command as Ti}from"commander";import he from"chalk";var Qt=new Ti().name("usage").description("token usage analysis and reporting");Qt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=P(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(he.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(he.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${he.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${he.red(String(s.totalErrors))}`),console.log(),console.log(he.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),p=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${he.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${he.dim(p)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(he.red(" Daemon not running. Start with: agentx daemon start")):console.log(he.red(` ${e.message}`))}});Qt.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(he.red(` Script not found: ${s}`)),console.log(he.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(he.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(he.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as _i}from"commander";import H from"chalk";var Ue=new _i().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ue.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{let t=Pi(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-HXDOYGIG.js");o(t)}catch(t){console.log(H.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(H.dim(t.stack)),process.exit(1)}});function Pi(e,t){try{let o=P();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(H.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(H.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
141
+ `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ue.command("list").description("list configured boards").action(()=>{try{let e=P();if(!e.boards?.length){console.log(H.dim(`
142
+ No boards configured.
143
+ `));return}console.log();for(let t of e.boards){console.log(` ${H.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(H.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(H.dim(` primary label: ${t.primaryToolLabel}`)),console.log(H.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(H.red(` ${e.message}`)),process.exit(1)}});Ue.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'mtgl/system,mtgl/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Tt(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(H.red(` ${o.message}`)),process.exit(1)}});Ue.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{Tt(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(o){console.log(H.red(` ${o.message}`)),process.exit(1)}});var Eo=Ue.command("column").description("manage a board's columns (add / remove / edit / list)");Eo.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(ws("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(H.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${H.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${H.dim(i)}`)}}catch(t){console.log(H.red(` ${t.message}`)),process.exit(1)}});Eo.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{Tt(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log(H.red(` ${n.message}`)),process.exit(1)}});Eo.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Tt(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(H.red(` ${o.message}`)),process.exit(1)}});Ue.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Tt(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(H.red(` ${t.message}`)),process.exit(1)}});function Tt(e){let{summary:t,backupPath:o}=at(n=>e(n));console.log(H.green(`
144
+ \u2713 ${t}
145
+ `)),o&&console.log(H.dim(` Backup: ${o}`)),console.log(H.dim(` Restart the dashboard to pick up the change if not auto-reloading.
146
+ `))}import{Command as Mi}from"commander";import g from"chalk";function Bn(e,t,o,n,s,i){return Ni(t,o,n,s,i)}function Ni(e,t,o,n,s){let i=t?`
147
+ ## Worldview
148
+
149
+ ${t}
150
+ `:"",r=new Map;for(let c of o){let l=c.type||"untyped",p=r.get(l)||[];p.push(c),r.set(l,p)}let a=o.length===0?"":`
151
+ ## Existing Articles (the current catalog)
152
+
153
+ `+Array.from(r.entries()).sort().map(([c,l])=>`**${c}**
154
+ `+l.sort((p,d)=>p.title.localeCompare(d.title)).map(p=>`- [[${p.title}]] \u2014 ${p.path}`).join(`
155
+ `)).join(`
156
+
157
+ `)+`
158
+ `;return`You are compiling a personal wiki for the "${e}" agent in the Karpathy / Farzapedia pattern.
159
+
160
+ ## The Pattern (read this first \u2014 it shapes every decision below)
161
+
162
+ The wiki is a compounding knowledge base of interlinked markdown articles that a future LLM will read by walking the graph, NOT by bag-of-words search. Your job is to produce articles that another agent can navigate via \`type\` + wikilinks. If the wikilinks don't form a coherent graph, the wiki is useless regardless of how many tags you add.
163
+
164
+ **Three rules, in priority order:**
165
+
166
+ 1. **\`type\` is the organizational spine.** Every article has exactly one of: \`person | project | place | concept | event | decision | pattern\`. Choose the type BEFORE writing; if you can't pick one, the article probably isn't needed.
167
+ 2. **\`related\` is the navigation surface.** Every article cross-references 2\u20135 other articles via \`[[Article Title]]\` wikilinks in the body AND lists them in the \`related\` frontmatter field. Links the reader could follow to learn more.
168
+ 3. **Tags are a secondary hint, not a retrieval spine.** 2\u20134 specific tags max. Do NOT tag aggressively. Do NOT tag with dates unless the article is an \`event\`. Do NOT tag with generic terms ("deploy", "work") that will match half the corpus.
169
+
170
+ ## Path convention
171
+
172
+ Path reflects type: \`<type>s/<slug>.md\` where slug is a kebab-case title.
173
+
174
+ - People: \`people/anis-marrouchi.md\`
175
+ - Projects: \`projects/mtgl-system-v2.md\`
176
+ - Concepts: \`concepts/staging-deployment.md\`
177
+ - Events: \`events/YYYY-MM-DD-<slug>.md\` (date in path)
178
+ - Decisions: \`decisions/<slug>.md\`
179
+ - Patterns: \`patterns/<slug>.md\`
180
+ - Places: \`places/<slug>.md\`
181
+
182
+ ## How to process entries
183
+
184
+ For each of the ${s} raw entries below, ask in this order:
185
+
186
+ 1. **Does it extend an existing article?** If a person/project/concept mentioned in the entry already has an article in the catalog, produce an UPDATE with the full merged content. Prefer merging over proliferating.
187
+ 2. **Does it deserve a new article?** Only if the subject is a persistent entity (a person, a project, a recurring concept, a specific event/decision) that future queries will need to find. Not every conversation deserves an article.
188
+ 3. **Does it belong in an existing \`event\` or \`decision\`?** Most work entries fold into one of these.
189
+ 4. **Can you skip it?** If the entry is small talk, a transient status ping, or already covered elsewhere \u2014 skip. The wiki is curated, not exhaustive.
190
+
191
+ ## Writing standards
192
+
193
+ - **Wikipedia-style, flat, factual, encyclopedic.** This is the agent's knowledge, not a diary. Write about the *role* of the entity in our work, not a product description.
194
+ - **Synthesize, don't quote.** At most 2 short quoted lines per article.
195
+ - **Organize by theme, not chronology.** An article about a person lists what they do, who they work with, how they prefer to be contacted \u2014 not a log of every interaction.
196
+ - **Length: 20\u2013100 lines.** Articles exceeding 100 lines should split into multiple type-specific articles.
197
+ - **Every paragraph earns its place.** Cut narrative filler. If you can remove a sentence without losing a fact, remove it.
198
+
199
+ ## Wikilink discipline
200
+
201
+ - Use \`[[Article Title]]\` **inside the body** every time another tracked entity is referenced.
202
+ - List those same targets in the \`related\` frontmatter field.
203
+ - If you reference something that has no article yet (\`[[New Thing]]\`), add "New Thing" to the output \`gaps\` array so the next pass can create it.
204
+
205
+ ## Article frontmatter (exact shape \u2014 do not invent fields)
206
+
207
+ \`\`\`yaml
208
+ ---
209
+ title: "Article Title"
210
+ type: person | project | place | concept | event | decision | pattern
211
+ related: ["Other Article", "Another Article"]
212
+ tags: ["2-4-specific-tags", "no-dates-unless-event"]
213
+ owner: ${e}
214
+ access: public | shared | private
215
+ created: YYYY-MM-DD
216
+ last_updated: YYYY-MM-DD
217
+ sources: ["entry-id-1", "entry-id-2"]
218
+ ---
219
+ \`\`\`
220
+
221
+ Access guidance: default \`public\`; \`private\` only for sensitive credentials or agent-specific learnings; \`shared\` with specific agent IDs when the article matters only to a subset.
222
+ ${i}${a}
223
+ ## Gap Detection
224
+
225
+ After compiling, populate a \`gaps\` array: wikilink targets you referenced but for which no article exists yet. Be specific:
226
+
227
+ - Good: "Karim Rahmouni \u2014 coach for Tunis Padel club, mentioned twice but no \`people/\` article"
228
+ - Bad: "We need more content about deployments"
229
+
230
+ ## Output \u2014 valid JSON only, no markdown fencing
231
+
232
+ \`\`\`
233
+ {
234
+ "articles": [
235
+ {
236
+ "path": "projects/mtgl-system-v2.md",
237
+ "title": "MTGL System V2",
238
+ "type": "project",
239
+ "related": ["Anis Marrouchi", "Laravel", "Staging Deployment"],
240
+ "tags": ["mtgl", "laravel", "react"],
241
+ "content": "MTGL System V2 is [[Anis Marrouchi]]'s production Laravel + React app for \u2026",
242
+ "sources": ["entry-id-1", "entry-id-2"]
243
+ }
244
+ ],
245
+ "gaps": [
246
+ "Karim Rahmouni \u2014 Tunis Padel coach, mentioned in entries but no people/ article"
247
+ ]
248
+ }
249
+ \`\`\`
250
+
251
+ ENTRIES (${s}):
252
+
253
+ ${n}`}import{resolve as D,relative as Un,dirname as qn}from"path";import{execSync as tt}from"child_process";import{writeFileSync as ot,mkdirSync as De,readFileSync as _t,readdirSync as Li,renameSync as Xt,rmSync as Wi,existsSync as ve}from"fs";function de(e,t){return new go(e||D(process.cwd(),".agentx/wiki"),void 0,t||"graph")}function Io(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var V=new Mi().name("wiki").description("wiki knowledge base management");V.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,o=de(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(g.bold(` Wiki Hub Status [${Io(t)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?g.yellow(`${a.unabsorbed} unabsorbed`):g.green("up to date");if(console.log(` ${g.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(g.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(g.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(g.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});V.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let t=de(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let s of o){let r=t.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${g.cyan(s)}: ${g.green("healthy")}`);else{console.log(` ${g.cyan(s)}: ${g.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${g.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(g.green(" All agent wikis are healthy")),console.log()});V.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--max <n>","max entries per agent","10").action(async e=>{let t=e.mode,o=de(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let d=D(process.cwd(),".agentx/graph");return ve(d)?new Ge({baseDir:d}):null}catch{return null}})(),r=new Map;if(i)try{let d=i.loadIndex();for(let[m,h]of Object.entries(d.entries))r.set(m,h.path)}catch{}let a=d=>{let m=d.meta?.intentPath;if(Array.isArray(m)&&m.every(w=>typeof w=="string")&&m.length>0)return m;if(!i||r.size===0)return;let h=String(d.meta?.sender??""),f=i.fingerprint({text:d.content,channel:d.source,sender:h});return r.get(f)},c=(d,m)=>{let h=new Map;for(let w of d){let y=m.find(v=>v.id===w);if(!y)continue;let k=a(y);if(!k?.length)continue;let $=k.join("/"),x=h.get($);x?x.n++:h.set($,{path:k,n:1})}if(h.size===0)return;let f;for(let w of h.values())(!f||w.n>f.n)&&(f=w);return f?.path},l=0,p=0;for(let d of n){let m=o.getUnabsorbedEntries(d).slice(0,s);if(m.length===0){console.log(` ${g.cyan(d)}: ${g.green("all absorbed")}`);continue}console.log(),console.log(g.bold(` ${g.cyan(d)}: ${m.length} entries to absorb`));for(let v of m.slice(0,3))console.log(g.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(m.length>3&&console.log(g.dim(` ... and ${m.length-3} more`)),e.dryRun)continue;let h=o.getAgentWiki(d),f=h.rebuildIndex(),w=h.getWorldview()||o.getSharedStore().getWorldview()||"",y=m.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
254
+ ${v.content}
255
+ --- END ENTRY ---`).join(`
256
+
257
+ `),k=Bn(t,d,w,f.articles,y,m.length);console.log(g.dim(` Mode: ${Io(t)}`));let $=D(h.baseDir,"_tmp");De($,{recursive:!0});let x=D($,"absorb-prompt.txt");ot(x,k),console.log(g.dim(" Compiling with Claude..."));try{let v;try{v=tt(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(E){if(v=E.stdout||"",!v)throw E}let b=v;try{let E=JSON.parse(v);b=E.result||E.content||"",b||(console.log(g.dim(` Claude envelope keys: ${Object.keys(E).join(", ")}`)),console.log(g.dim(` is_error: ${E.is_error}, stop_reason: ${E.stop_reason}`)))}catch{}let C,j=[],M=b.indexOf("{"),L=b.indexOf("["),I=M>=0&&(L<0||M<L)?M:L;if(I===-1){console.log(g.red(" No JSON found in response")),console.log(g.dim(b.slice(0,500)));continue}let le=b[I],ue=le==="{"?"}":"]",Te=0,ie=-1;for(let E=I;E<b.length;E++)if(b[E]===le)Te++;else if(b[E]===ue&&(Te--,Te===0)){ie=E+1;break}if(ie===-1){console.log(g.red(" Unbalanced JSON"));continue}let ye=b.slice(I,ie);try{let E=JSON.parse(ye);Array.isArray(E)?C=E:(C=E.articles||[],j=E.gaps||[])}catch(E){console.log(g.red(` JSON parse error: ${E.message}`)),console.log(g.dim(` First 300 chars: ${ye.slice(0,300)}`));continue}for(let E of C){let Ae=new Date().toISOString().slice(0,10),we=c(E.sources||[],m);h.writeArticle(E.path,{title:E.title,type:E.type,related:Array.isArray(E.related)?E.related:void 0,tags:E.tags||[],owner:d,access:"public",created:Ae,lastUpdated:Ae,sources:E.sources||[],graphPath:we},E.content,d);let Go=E.type?g.magenta(`[${E.type}]`)+" ":"",ao=Array.isArray(E.related)&&E.related.length?` \u2192 ${E.related.slice(0,3).join(", ")}${E.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${Go}${E.path}: ${E.title}${g.dim(ao)}`);let St=(E.tags||[]).slice(0,4).join(", ");St&&console.log(g.dim(` tags: ${St}`)),we?.length&&(console.log(g.dim(` graphPath: ${we.join(" \u203A ")}`)),p++),l++}if(j.length>0){console.log(),console.log(g.yellow(` Gaps detected (${j.length} missing pieces):`));for(let E of j)console.log(g.yellow(` ? ${E}`))}h.rebuildIndex()}catch(v){console.log(g.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(g.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(g.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(g.dim(" Dry run \u2014 no changes made"));else if(l>0&&(console.log(g.green(` ${l} articles compiled across ${n.length} agent(s)`)),i)){let d=l>0?Math.round(p/l*100):0;console.log(g.dim(` ${p}/${l} carry graphPath (${d}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});V.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",D(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-HZYYRCLU.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=de(e.dir),c=e.agent;if(!c){console.log(g.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),p=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(g.yellow(` no task-history at ${d}`));return}let m=[],h=o(d).sort().reverse();for(let y of h){let k=r(d,y),$=[];try{$=o(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of $){if(m.length>=p)break;try{let v=JSON.parse(n(r(k,x),"utf-8")),b=v.message||v.task?.message;typeof b=="string"&&b.trim().length>10&&m.push({id:v.id||x.replace(".json",""),message:b.trim(),ts:v.at||v.timestamp||y})}catch{}}if(m.length>=p)break}if(m.length===0){console.log(g.yellow(` no task messages found under ${d}`));return}console.log(),console.log(g.bold(` A/B harness \u2014 ${m.length} messages from ${c}`)),console.log(g.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(g.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let f=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${m.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<m.length;y++){let k=m[y];process.stdout.write(g.dim(` [${y+1}/${m.length}] querying... `));let x=l.findRelevant(k.message,c,3).map(b=>`- **${b.meta.title}** [${b.meta.type||"?"}] (${b.path})`).join(`
258
+ `)||"_(none returned)_",v;try{let b=await t(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(b.status!=="ok")v=`_(status: ${b.status}${b.error?" \u2014 "+b.error:""})_`;else{let C=b.citations.map(j=>`\`${j.title}\` [${j.type||"?"}]`).join(", ");v=`**Answer:**
259
+
260
+ ${b.answer}
261
+
262
+ **Citations:** ${C}`}}catch(b){v=`_(error: ${b.message})_`}console.log(g.dim("done")),f.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",x,"","### NEW \u2014 agentic query","",v,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=f.join(`
263
+ `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(g.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});V.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'MTGL deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-VECTMYTO.js"),s=e.answers?_t(e.answers,"utf-8").split(/\r?\n/).filter(A=>A.length>0):null,i=0;if(!e.agent){console.log(g.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=de(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(A){console.log(g.red(` can't open wiki for agent "${e.agent}": ${A.message}`));return}let c=s?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async A=>{if(s){let se=s[i++]??"";return process.stdout.write(A+g.dim(`[scripted] ${se.slice(0,80)}${se.length>80?"\u2026":""}`)+`
264
+ `),se.trim()}return(await c.question(A)).trim()};console.log(),console.log(g.bold(" Wiki Interview")),console.log(g.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let p=e.topic||"";if(!p&&(p=await l(g.cyan(" Topic? ")+g.dim("(a person, a procedure, a past event, \u2026) ")),!p||p==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),m=new Set(n);if(!m.has(d)){console.log(g.dim(` Types: ${n.join(" | ")}`));let A=await l(g.cyan(" Type? "));if(A==="/abort"){c?.close();return}m.has(A)?d=A:(console.log(g.yellow(` "${A}" isn't a valid type. Falling back to "concept".`)),d="concept")}let h={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},f=h[d]||h.concept;console.log(),console.log(g.bold(` Topic: ${g.cyan(p)} \xB7 Type: ${g.magenta(d)}`)),console.log(g.dim(` ${f.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let A=0;A<f.length;A++){let se=f[A],be=await l(` ${g.dim(`[${A+1}/${f.length}]`)} ${se}
265
+ ${g.green(">")} `);if(be==="/abort"){y=!0;break}if(be==="/done")break;be!=="/skip"&&be&&w.push({q:se,a:be})}if(!y){let A=await l(`
266
+ ${g.dim("Anything else worth capturing?")}
267
+ ${g.green(">")} `);A&&A!=="/abort"&&A!=="/done"&&w.push({q:"Anything else worth capturing?",a:A})}if(y||w.length===0){console.log(g.yellow(`
268
+ Nothing captured. Exiting.`)),c?.close();return}let $=a.listArticles(e.agent).slice(0,40).map(A=>`- ${A.meta.title} [${A.meta.type||"?"}]`).join(`
269
+ `),x=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${p}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(A=>`
270
+ Q: ${A.q}
271
+ A: ${A.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
272
+ `),v=D(a.baseDir,"_tmp");De(v,{recursive:!0});let b=D(v,`interview-${o().slice(0,8)}.txt`);ot(b,x),console.log(),console.log(g.dim(` Synthesizing draft with ${e.model}...`));let C="";try{let A=`cat '${b}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,se=tt(A,{encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let be=JSON.parse(se);C=String(be.result||be.content||"")}catch{C=se}}catch(A){console.log(g.red(` synthesis failed: ${A.message?.slice(0,200)}`)),c?.close();return}C=C.trim();let j=C.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(C=j[1].trim());let M=C.indexOf("---");M>0&&(C=C.slice(M));let L=C.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!L){console.log(g.red(" LLM output is not a valid frontmatter+body article:")),console.log(C.slice(0,600)),c?.close();return}let I={};for(let A of L[1].split(`
273
+ `)){let se=A.match(/^(\w+):\s*(.+)$/);se&&(I[se[1]]=se[2].trim().replace(/^"(.*)"$/,"$1"))}let le=L[2],ue=I.title||p,Te=ue.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ye=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${Te}.md`;console.log(),console.log(g.bold(" === Draft preview ===")),console.log(g.dim(` Path: ${ye}`)),console.log(),console.log(C),console.log();let E=await l(` ${g.green("save")} / ${g.yellow("edit (opens $EDITOR)")} / ${g.red("scrap")} ? `);if(c?.close(),E==="scrap"||E==="/abort"){console.log(g.dim(" Discarded."));return}if(!e.commit){console.log(g.dim(" --no-commit: not writing.")),console.log(g.dim(` Draft kept at ${b} (prompt only; no article file)`));return}let Ae=le,we={title:ue,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(E==="edit"){let A=process.env.EDITOR||"vi",se=D(v,`draft-${o().slice(0,8)}.md`);ot(se,C);try{tt(`${A} '${se}'`,{stdio:"inherit"});let co=_t(se,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(co){let _e={};for(let jt of co[1].split(`
274
+ `)){let lo=jt.match(/^(\w+):\s*(.+)$/);lo&&(_e[lo[1]]=lo[2].trim().replace(/^"(.*)"$/,"$1"))}Ae=co[2],we={...we,title:_e.title||we.title,type:_e.type||we.type,access:_e.access||we.access,related:_e.related?_e.related.replace(/^\[|\]$/g,"").split(",").map(jt=>jt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.related,tags:_e.tags?_e.tags.replace(/^\[|\]$/g,"").split(",").map(jt=>jt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.tags}}}catch(be){console.log(g.red(` editor failed: ${be.message}`));return}}if(!a.writeArticle(ye,we,Ae,e.agent)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(g.green(` \u2713 ${ye} saved.`));let ao=a.extractWikilinks(Ae),St=new Map;for(let A of a.listArticles(e.agent))St.set(A.meta.title.toLowerCase(),!0);let Yo=ao.filter(A=>!St.has(A.toLowerCase()));if(Yo.length){console.log(),console.log(g.bold(" Gaps referenced but not yet covered:"));for(let A of Yo.slice(0,8))console.log(g.dim(` - ${A}`));console.log(g.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});V.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-HZYYRCLU.js");if(!e.agent){console.log(g.red(" --agent <id> is required."));return}let s=de(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(h){console.log(g.red(` can't open wiki for agent "${e.agent}": ${h.message}`));return}let r=null;if(e.script){let f=_t(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of f){let y=w.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),$=y.slice(1).join(" ").trim();k&&$&&r.push({q:k,verdict:$})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async h=>a?(await a.question(h)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),p=e.commit!==!1;console.log(),console.log(g.bold(" Wiki Quiz")),console.log(g.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${p?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(g.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],m=0;for(let h=0;h<l;h++){let f,w;if(r){let ie=r[h];if(!ie)break;f=ie.q,w=ie.verdict,console.log(g.cyan(` [${h+1}] Q: `)+f)}else{if(f=await c(g.cyan(` [${h+1}] Q: `)),!f||f==="/done"||f==="/abort")break;w=""}process.stdout.write(g.dim(" querying... "));let y;try{y=await n(f,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(ie){console.log(g.red(`failed: ${ie.message?.slice(0,120)}`));continue}if(console.log(g.dim("done")),y.status!=="ok")console.log(g.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let ie=y.citations.map(ye=>`${ye.title} [${ye.type||"?"}]`).join(" \xB7 ");console.log(),console.log(g.dim(" A: ")+y.answer.replace(/\n/g,`
275
+ `)),console.log(g.dim(" citations: "+ie))}r||(w=await c(g.cyan(" verdict > "))),console.log(g.dim(" verdict: ")+w);let k={q:f,answer:y.answer,citations:y.citations,verdict:w},$=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(g.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let x=$[1].toLowerCase(),v=($[2]||"").trim();if(d.push(k),x==="/ok"||x==="/skip")continue;if(!v){console.log(g.yellow(` ${x} without note \u2014 skipping.`));continue}let b=y.citations[0];if(!b){console.log(g.yellow(" no cited article to patch."));continue}let C=i.readArticle(b.path);if(!C){console.log(g.red(` can't read ${b.path} to patch.`));continue}console.log(g.dim(` patching ${b.title} (${b.path})...`));let j=Bi(C.content,x,v,C.meta.title,C.meta.type),M=D(i.baseDir,"_tmp");De(M,{recursive:!0});let L=D(M,`quiz-patch-${o().slice(0,8)}.txt`);ot(L,j);let I="";try{let ie=`cat '${L}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ye=tt(ie,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ae=JSON.parse(ye);I=String(Ae.result||Ae.content||"")}catch{I=ye}let E=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);E&&(I=E[1].trim()),I=I.trim()}catch(ie){console.log(g.red(` patch failed: ${ie.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(g.yellow(" patch returned nothing usable."));continue}let le=C.content.split(`
276
+ `).length,ue=I.split(`
277
+ `).length;if(console.log(g.dim(` diff: ${le} \u2192 ${ue} lines (${ue-le>=0?"+":""}${ue-le})`)),!p){console.log(g.dim(" (--no-commit: patch not written)")),k.patched=b.path+" (dry)";continue}if(!i.writeArticle(b.path,{...C.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(g.red(" write failed (permission?)"));continue}m++,k.patched=b.path,console.log(g.green(` \u2713 patched ${b.path}`))}if(a&&a.close(),m>0&&p&&i.rebuildIndex(),console.log(),console.log(g.bold(` Session done: ${d.length} rounds, ${m} patches applied.`)),e.out){let h=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${m} patches_`,""];for(let f=0;f<d.length;f++){let w=d[f];h.push(`## ${f+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}ot(e.out,h.join(`
278
+ `)),console.log(g.dim(` Transcript written to ${e.out}`))}});V.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=de(o.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(g.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=Gn(s,t,e);if(!i){console.log(g.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(g.dim(` Tip: ${g.green("agentx wiki status")} lists agents; ${g.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=D(s.baseDir,i),a=o.editor||process.env.EDITOR||"vi";console.log(g.dim(` opening ${i} in ${a}...`));try{tt(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(g.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,p=s.extractWikilinks(c.content).filter(h=>l.has(h)?!1:(l.add(h),!0)),d=c.meta.related||[];(p.some(h=>!d.includes(h))||d.some(h=>!p.includes(h)))&&(s.writeArticle(i,{...c.meta,related:p.length?p:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(g.dim(` (synced frontmatter.related from body: ${p.length} wikilink${p.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(g.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(g.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});V.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=de(n.dir),a;try{a=r.getAgentWiki(e)}catch(b){console.log(g.red(` can't open wiki for agent "${e}": ${b.message}`));return}let c=Gn(a,t,e);if(!c){console.log(g.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(g.red(` can't read ${c}.`));return}let p=Fi(l.content,l.meta.title,l.meta.type,o),d=D(a.baseDir,"_tmp");De(d,{recursive:!0});let m=D(d,`patch-${i().slice(0,8)}.txt`);ot(m,p),console.log(),console.log(g.dim(` Target: ${l.meta.title} (${c})`)),console.log(g.dim(` Patching with ${n.patchModel}...`));let h="";try{let b=`cat '${m}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,C=tt(b,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let M=JSON.parse(C);h=String(M.result||M.content||"")}catch{h=C}let j=h.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(h=j[1].trim()),h=h.trim()}catch(b){console.log(g.red(` patch failed: ${b.message?.slice(0,150)}`));return}if(!h||h.length<20){console.log(g.yellow(" patch returned nothing usable."));return}let f=l.content.split(`
279
+ `).length,w=h.split(`
280
+ `).length;if(console.log(),console.log(g.bold(" === Patched preview ===")),console.log(g.dim(` diff: ${f} \u2192 ${w} lines (${w-f>=0?"+":""}${w-f})`)),console.log(),console.log(h),console.log(),!n.commit){console.log(g.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let b=s.createInterface({input:process.stdin,output:process.stdout}),C=(await b.question(g.cyan(" apply? [y/N] "))).trim().toLowerCase();b.close(),y=C==="y"||C==="yes"}if(!y){console.log(g.dim(" aborted."));return}let k=new Set,$=a.extractWikilinks(h).filter(b=>k.has(b)?!1:(k.add(b),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},h,e)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex();let v=(l.meta.related||[]).filter(b=>!$.includes(b));v.length&&console.log(g.dim(` (pruned stale related: ${v.slice(0,3).join(", ")}${v.length>3?", \u2026":""})`)),console.log(g.green(` \u2713 ${c} patched.`))});function Gn(e,t,o){let n=t.trim(),s=e.listArticles(o),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,p=s.find(d=>d.path===l||d.path===n);if(p)return p.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let p=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return p===a||p.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function Fi(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
281
+ `)}function Bi(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
282
+
283
+ ${o}
284
+
285
+ Edit the article to correct ONLY this mistake. Do not rewrite untouched sections. Keep the existing prose style. If the correction invalidates a larger passage, revise the minimum that must change.`,"/add":`The operator wants to add this detail:
286
+
287
+ ${o}
288
+
289
+ Incorporate it into the most relevant existing section, or create a short new section if nothing fits. Keep the prose encyclopedic and under 100 additional words.`,"/link":`The operator wants to add this resource:
290
+
291
+ ${o}
292
+
293
+ Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${o}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[t]||`Make a minimal edit per: ${o}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
294
+ `)}V.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let t=de(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=!!e.commit,s=e.dir?D(e.dir):D(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(g.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(g.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,p=0;for(let d of o){let m=D(s,"agents",d);if(!ve(m))continue;let h=D(m,i),f=r.map($=>({mode:$,dir:D(m,$)})).filter($=>ve($.dir));if(f.length===0)continue;let w=new Map;Ao(h,$=>{let x=Un(h,$);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let v=Jn(_t($,"utf-8"));v?.meta.title&&w.set(v.meta.title.trim().toLowerCase(),{relPath:x,type:v.meta.type,lastUpdated:v.meta.lastUpdated||""})});let y=[];for(let $ of f)Ao($.dir,x=>{let v=Un($.dir,x);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let b=Jn(_t(x,"utf-8"));b?.meta.title&&y.push({mode:$.mode,relPath:v,absPath:x,title:b.meta.title.trim(),type:b.meta.type,lastUpdated:b.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=f.map($=>$.mode).join("+");console.log(g.bold(` ${g.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let $ of y){let x=$.title.toLowerCase(),v=w.get(x),b;v?!v.type&&$.type||!!v.type==!!$.type&&$.lastUpdated&&v.lastUpdated&&$.lastUpdated>v.lastUpdated?b="upgrade":b="archive":b="promote";let C=$.type?g.magenta(`[${$.type}]`):g.yellow("[untyped]"),j=b==="promote"?g.green("\u2192 promote "):b==="upgrade"?g.cyan("\u27F3 upgrade "):g.dim("\u2717 archive "),M=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${j} ${C} ${g.dim($.mode+"/")}${M}`),b==="upgrade"&&console.log(g.dim(` (replaces ${v.relPath}, old version kept under _versions/)`)),!n){b==="promote"?c++:b==="upgrade"?l++:p++;continue}try{if(b==="promote"){let L=D(h,$.relPath);ve(L)?(console.log(g.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),zn(m,$),p++):(De(qn(L),{recursive:!0}),Xt($.absPath,L),w.set(x,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(b==="upgrade"){let L=D(h,v.relPath);if(ve(L)){let I=D(m,"_versions",v.relPath.replace(/\.md$/,""));De(I,{recursive:!0});let le=new Date().toISOString().replace(/[:.]/g,"-");Xt(L,D(I,`${le}.md`))}De(qn(L),{recursive:!0}),Xt($.absPath,L),w.set(x,{relPath:v.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else zn(m,$),p++}catch(L){console.log(g.red(` ! ${b} failed: ${L.message?.slice(0,120)}`))}}if(n){for(let $ of f)try{Wi($.dir,{recursive:!0,force:!0})}catch{}try{t.getAgentWiki(d).rebuildIndex()}catch($){console.log(g.dim(` (catalog rebuild skipped: ${$.message?.slice(0,80)})`))}}}console.log(),console.log(g.dim(` Legacy scanned: ${a}`)),n?(console.log(g.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${p}`)),console.log(g.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(g.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${p}`)),console.log(g.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Ao(e,t){if(ve(e))for(let o of Li(e,{withFileTypes:!0})){let n=D(e,o.name);o.isDirectory()?Ao(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function Jn(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
295
+ `)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function zn(e,t){let o=D(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));De(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Xt(t.absPath,D(o,`${n}.md`))}V.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let t=de(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(g.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(g.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of o){let p=t.getAgentWiki(l),d=p.listArticles(l),m=d.filter(k=>!k.meta.type);if(r+=d.length,a+=m.length,m.length===0){console.log(` ${g.cyan(l)}: ${g.green("all typed")} (${d.length} articles)`);continue}let h=Math.max(0,s-c),f=Math.min(m.length,h);if(f===0){console.log(g.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(g.bold(` ${g.cyan(l)}: ${f}/${m.length} untyped articles`));let w=p.baseDir,y=D(w,"_tmp");De(y,{recursive:!0});for(let k=0;k<f;k+=n){let $=m.slice(k,Math.min(k+n,f)),x=qi($),v=D(y,"migrate-prompt.txt");ot(v,x);let b;try{let C=`cat '${v}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,j=tt(C,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),M=JSON.parse(j),I=String(M.result||M.content||"").match(/\[[\s\S]*\]/);if(!I)throw new Error("no JSON array in classifier response");b=JSON.parse(I[0])}catch(C){console.log(g.red(` LLM classify failed: ${C.message?.slice(0,150)}`));continue}for(let C of $){let j=b.find(Te=>Te.path===C.path),M=Ui(j?.type);if(!j||!M){console.log(g.yellow(` ? ${C.path}: unclassified${j?` (got "${j.type}")`:""}`));continue}let L=p.extractWikilinks(C.content),I={...C.meta,type:M.type,related:L.length?L:void 0,lastUpdated:new Date().toISOString().slice(0,10)},le=L.length?g.dim(` \u2192 ${L.slice(0,3).join(", ")}${L.length>3?", \u2026":""}`):"",ue=M.alias?g.dim(` (from "${M.alias}")`):"";console.log(` ${g.green("+")} ${g.magenta("["+M.type+"]")}${ue} ${C.path}${le}`),i&&(p.writeArticle(C.path,I,C.content,l),c++)}}i&&p.rebuildIndex()}console.log(),console.log(g.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?g.green(` Applied ${c} patches.`):g.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function Ui(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[t];return n?n===t?{type:n}:{type:n,alias:t}:null}function qi(e){let t=e.map((o,n)=>{let s=o.content.replace(/\s+/g," ").slice(0,400),i=(o.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${o.path}"
296
+ title: "${o.meta.title}"
297
+ tags: [${i}]
298
+ body: ${s}${o.content.length>400?"\u2026":""}`}).join(`
299
+
300
+ `);return`Classify each of these ${e.length} wiki articles into EXACTLY ONE type from this closed set (no synonyms, no plurals, no new values):
301
+
302
+ person | project | place | concept | event | decision | pattern
303
+
304
+ What each type means:
305
+ - person: an individual human (team member, stakeholder, contact)
306
+ - project: a named initiative, repo, product, service, bot, agent, team, or org
307
+ - place: a physical or logical location (office, server, environment, infrastructure)
308
+ - concept: a recurring idea, philosophy, methodology, or thinking pattern
309
+ - event: a specific dated thing that happened (incident, deploy, launch, GitLab issue, MR)
310
+ - decision: a specific choice made and why (architecture decision, policy, ADR)
311
+ - pattern: a reusable workflow, template, recipe, procedure, runbook, or SOP
312
+
313
+ Explicit mappings (you WILL be tempted to volunteer these \u2014 don't; use the right-hand value):
314
+ - "agent" / "bot" / "service" / "repo" / "team" \u2192 project
315
+ - "issue" / "MR" / "ticket" / "incident" / "deploy" \u2192 event
316
+ - "process" / "procedure" / "runbook" / "workflow" \u2192 pattern
317
+ - "infrastructure" / "server" / "environment" \u2192 place
318
+ - "ADR" / "decision record" \u2192 decision
319
+
320
+ Rules:
321
+ - Return EXACTLY one type per article, by path, from the 7 allowed values above.
322
+ - Do not invent new types. Do not return plurals. Do not return synonyms.
323
+ - If the title is a person's name, it's person. If it's a repo/product/bot name, it's project. If it's dated + past tense, it's event.
324
+ - If you genuinely cannot decide, pick "concept" as the fallback.
325
+ - Output ONLY valid JSON, no markdown fencing, no prose.
326
+
327
+ Articles:
328
+
329
+ ${t}
330
+
331
+ Output (JSON array, one entry per input article, same order):
332
+ [
333
+ {"path": "path/to/article.md", "type": "project"},
334
+ ...
335
+ ]`}V.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=de(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(g.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${g.dim(s.date)} ${g.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(g.dim(` ... showing last 20 of ${n.length}`)),console.log()});V.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||D(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-QXWKEQON.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(g.bold(" AgentX Wiki Server")),console.log(),console.log(` ${g.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${g.cyan(e.agent)}`):console.log(` Mode: ${g.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${g.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(g.dim(` Wiki: ${t}`)),console.log(g.dim(" Press Ctrl+C to stop")),console.log(),un(t,o,e.agent,n,e.mode)});V.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-HZYYRCLU.js"),n=de(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),p=D(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(p)){i=c;break}}catch{}}if(!i){console.log(g.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(g.bold(` Q: ${e}`)),console.log(g.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(g.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(g.dim(" Citations:"));for(let c of a.citations){let l=c.type?g.magenta(` [${c.type}]`):"";console.log(g.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(t.trace&&a.trace){if(console.log(g.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(g.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(p=>p.path===l.path));console.log(g.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});V.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action((e,t)=>{let o=de(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=o.getAgentWiki(i).findRelevant(e,void 0,10);if(a.length>0){console.log(g.bold(` ${g.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(g.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(g.dim(" No matching articles")),console.log()});V.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=de(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=D(process.cwd(),".agentx/graph");if(!ve(n)){console.log(g.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ge({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,m]of Object.entries(i.entries))r.set(d,m.path);if(r.size===0){console.log(g.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(g.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,p=0;for(let d of o){let m=t.getAgentWiki(d),h=m.listArticles(d),f=t.getSharedStore().listEntries(),w=new Map(f.map(x=>[x.id,x])),y=0,k=0,$=0;for(let x of h){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let v=new Map;for(let C of x.meta.sources){let j=w.get(C);if(!j)continue;let M=String(j.meta?.sender??""),L=s.fingerprint({text:j.content,channel:j.source,sender:M}),I=r.get(L);if(!I?.length)continue;let le=I.join("/"),ue=v.get(le);ue?ue.n++:v.set(le,{path:I,n:1})}if(v.size===0)continue;k++,l++;let b;for(let C of v.values())(!b||C.n>b.n)&&(b=C);b&&(e.dryRun||(m.writeArticle(x.path,{...x.meta,graphPath:b.path},x.content,d),$++,p++))}console.log(` ${g.cyan(d)}: ${g.bold(h.length)} articles \xB7 ${y} eligible \xB7 ${k} matched \xB7 ${g.green($)} written`)}console.log(),console.log(g.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${p} written`)),e.dryRun&&console.log(g.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});V.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.67.108.119:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=de(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-QXWKEQON.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(g.red(" No --peer specified and no daemon config found")),console.log(g.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(n.length===0){console.log(g.dim(" No mesh peers configured"));return}let s=new Set(o.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(g.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(g.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],p=c.nodeId||"unknown";console.log(g.dim(` Node: ${p} \u2014 ${l.length} entries`));let d=0;for(let m of l)s.has(m.id)||(e.dryRun||(o.addEntry({id:m.id,date:m.date,agentId:m.agentId,source:`${m.source}@${p}`,sourceContext:m.sourceContext,content:m.content}),s.add(m.id)),d++);d>0?console.log(g.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(g.dim(" Already up to date")),i+=d;try{let m=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(m.ok){let h=await m.json();for(let f of h.agents||[])f.totalEntries>0&&console.log(g.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(g.red(" Connection refused")):console.log(g.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(g.green(` ${i} entries synced.`)):i>0?console.log(g.dim(` ${i} entries would be synced (dry run)`)):console.log(g.dim(" All peers up to date")),console.log()});V.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||D(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new go(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),m=l.getAgentEntries(o),h=l.getUnabsorbedEntries(o),f=new Set,w=0,y=new Set;for(let $ of d.articles){for(let x of $.tags||[])f.add(x);w+=$.tags?.length||0;for(let x of $.sources||[])y.add(x)}let k=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:Io(c),articles:d.articles.length,entries:m.length,unabsorbed:h.length,uniqueTags:f.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(g.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of r){let p=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${p.join(" ")}`)}console.log();let a=(c,l)=>{let p=Math.max(...s.map(m=>m[c])),d=s.filter(m=>m[c]===p).map(m=>m.label);p>0&&console.log(g.dim(` Best ${l}: ${d.join(", ")} (${p})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});V.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");ve(o)||(console.log(g.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?D(process.cwd(),e):D(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=D(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(g.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(g.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:p}=await import("fs"),d=ve(s)?p(s).size:0;console.log(),console.log(g.green(` \u2713 wrote ${s} (${Ji(d)})`)),console.log(g.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});V.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=D(process.cwd(),e);ve(o)||(console.log(g.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");ve(n)&&!t.force&&(console.log(g.yellow(` ${n} already exists.`)),console.log(g.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=D(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(g.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(g.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(g.green(` \u2713 restored to ${n}`)),console.log(g.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ji(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as zi}from"commander";import T from"chalk";import{resolve as Oo}from"path";import{existsSync as Gi}from"fs";var Pt=new zi().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Pt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=P();if(!t.graph?.enabled){console.log(T.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(T.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(T.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Ge({baseDir:Oo(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(T.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(T.bold(` Graph review \u2014 ${r.length} pending`)),console.log(T.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,p=0,d=0,m=0;for(let f=0;f<r.length;f++){let w=r[f],y=Ho(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${T.cyan(w.msgHash.slice(0,8))} ${T.dim(y)} ... `);let k=Yi(w,a,c),$=null;try{$=await Hi(n,o,k,t.dashboard?.token)}catch(b){m++,console.log(T.red(`ERR ${b.message?.slice(0,80)}`));continue}if(!$||!$.decision){m++,console.log(T.red("ERR no decision"));continue}let x=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(T.green("APPROVE")+" "+T.dim(v)),e.dryRun)l++;else try{Ki(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:v}),l++}catch(b){console.log(T.yellow(` (commit failed, staying pending: ${b.message?.slice(0,100)})`)),m++}else x==="reject"?(console.log(T.red("REJECT")+" "+T.dim(v)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),p++):(console.log(T.yellow("SKIP")+" "+T.dim(v||x)),d++)}console.log();let h=e.dryRun?"would":"did";console.log(T.dim(` Summary: ${h} approve ${l}, ${h} reject ${p}, ${d} skipped, ${m} errors.`)),e.dryRun&&(l>0||p>0)&&console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Pt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let t=P();if(!t.graph){console.log(T.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Oo(process.cwd(),t.graph.baseDir);if(!Gi(o)){console.log(T.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new Ge({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(T.dim(" "),...a)});console.log(),console.log(T.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(T.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Pt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://clawd.noqta.tn:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=P();if(!t.graph?.enabled){console.log(T.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new Ge({baseDir:Oo(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(j=>j.id));console.log(),console.log(T.bold(` graph pull \u2190 ${o}`));let l,p,d;try{let j=await fetch(`${o}/graph/schema`,{headers:s});if(!j.ok)throw new Error(`schema HTTP ${j.status}`);l=(await j.json()).schema;let L=await fetch(`${o}/graph/nodes`,{headers:s});if(!L.ok)throw new Error(`nodes HTTP ${L.status}`);p=(await L.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(j){console.log(T.red(` fetch failed: ${j.message}`));return}let m=r.levels.map(j=>j.id).join(","),h=l?.levels?.map(j=>j.id).join(","),f=m===h;f?console.log(T.dim(` schema matches (${r.levels.length} levels)`)):(console.log(T.yellow(" \u26A0 schema levels differ:")),console.log(T.dim(` local: ${m}`)),console.log(T.dim(` peer: ${h}`)),a.length===0&&!e.dryRun?(console.log(T.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(T.yellow(" keeping local schema; node import may fail if levels disagree")));let w=f?r:l,y=new Map;w.levels.forEach((j,M)=>y.set(j.id,M));let k=[...p].sort((j,M)=>(y.get(j.level)??99)-(y.get(M.level)??99)),$=0,x=0,v=0;for(let j of k){if(c.has(j.id)){x++;continue}if(e.dryRun){$++,c.add(j.id);continue}try{i.addNode({...j,createdBy:j.createdBy?`${j.createdBy} (sync)`:`sync:${o}`}),c.add(j.id),$++}catch(M){v++,console.log(T.yellow(` skip node ${j.id}: ${M.message?.slice(0,100)}`))}}console.log(T.dim(` nodes: +${$} added \xB7 ${x} already-present \xB7 ${v} failed`));let b=0,C=0;for(let j of d)if(!(!j.msgHash||!Array.isArray(j.path))){if(i.getFingerprint(j.msgHash)){C++;continue}if(e.dryRun){b++;continue}i.setFingerprint(j.msgHash,{path:j.path,leaf:j.leaf||{}}),b++}console.log(T.dim(` fingerprints: +${b} cached \xB7 ${C} already-present`)),console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` \u2713 pulled from ${o}`)),console.log()});function Yi(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
336
+ `),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
337
+ `)}async function Hi(e,t,o,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:t,message:o,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Vi((c?.content||"").toString())}finally{clearTimeout(r)}}function Ki(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Vi(e){if(!e)return null;try{return JSON.parse(e)}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)try{return JSON.parse(t[1])}catch{}let o=e.indexOf("{");if(o<0)return null;let n=0;for(let s=o;s<e.length;s++)if(e[s]==="{")n++;else if(e[s]==="}"&&(n--,n===0))try{return JSON.parse(e.slice(o,s+1))}catch{return null}return null}import{Command as Zi}from"commander";import te from"chalk";import{existsSync as Ro,mkdirSync as Qi,readFileSync as Yn,readdirSync as Xi,writeFileSync as Hn}from"fs";import{resolve as Do,relative as To}from"path";import{z as ae}from"zod";var ft=ae.object({id:ae.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:ae.string().min(1),trigger:ae.string().min(1,"procedures must describe when they apply"),inputs:ae.array(ae.string()).default([]),expected:ae.string().optional(),kpis:ae.array(ae.string()).default([]),owner:ae.string().optional(),tags:ae.array(ae.string()).default([]),created:ae.string().optional(),updated:ae.string().optional(),related:ae.array(ae.string()).default([])});function Kn(e){let t=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!t)return{meta:{},body:e};let o={};for(let n of t[1].split(`
338
+ `)){let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let i=s[1],r=s[2].trim();if(r.startsWith("[")&&r.endsWith("]")){try{o[i]=JSON.parse(r);continue}catch{}o[i]=r.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),o[i]=r}return{meta:o,body:t[2]}}function Vn(e){let t=["---"];return t.push(`id: ${e.id}`),t.push(`title: "${e.title.replace(/"/g,'\\"')}"`),t.push(`trigger: "${e.trigger.replace(/"/g,'\\"')}"`),e.inputs?.length&&t.push(`inputs: ${JSON.stringify(e.inputs)}`),e.expected&&t.push(`expected: "${e.expected.replace(/"/g,'\\"')}"`),e.kpis?.length&&t.push(`kpis: ${JSON.stringify(e.kpis)}`),e.owner&&t.push(`owner: ${e.owner}`),e.tags?.length&&t.push(`tags: ${JSON.stringify(e.tags)}`),e.related?.length&&t.push(`related: ${JSON.stringify(e.related)}`),e.created&&t.push(`created: ${e.created}`),e.updated&&t.push(`updated: ${e.updated}`),t.push("---"),t.join(`
339
+ `)}var nt=class{baseDir;constructor(t={}){this.baseDir=t.baseDir??Do(process.cwd(),".agentx/procedures"),Qi(this.baseDir,{recursive:!0})}pathFor(t){return Do(this.baseDir,`${t}.md`)}list(){if(!Ro(this.baseDir))return[];let t=[];for(let o of Xi(this.baseDir,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".md")||o.name.startsWith("_"))continue;let n=Do(this.baseDir,o.name),s=Yn(n,"utf-8"),{meta:i,body:r}=Kn(s),a=ft.safeParse({...i,inputs:i.inputs||[],kpis:i.kpis||[],tags:i.tags||[],related:i.related||[]});a.success&&t.push({meta:a.data,body:r.trim(),path:To(this.baseDir,n)})}return t.sort((o,n)=>o.meta.id.localeCompare(n.meta.id))}get(t){let o=this.pathFor(t);if(!Ro(o))return null;let n=Yn(o,"utf-8"),{meta:s,body:i}=Kn(n),r=ft.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[]});return r.success?{meta:r.data,body:i.trim(),path:To(this.baseDir,o)}:null}add(t,o){let n=ft.parse({...t,created:t.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(Ro(s))throw new Error(`Procedure already exists: ${n.id}`);return Hn(s,Vn(n)+`
340
+
341
+ `+o.trim()+`
342
+ `),{meta:n,body:o.trim(),path:To(this.baseDir,s)}}update(t,o,n){let s=this.get(t);if(!s)throw new Error(`Procedure not found: ${t}`);let i=ft.parse({...s.meta,...o,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),r=n!==void 0?n:s.body;return Hn(this.pathFor(t),Vn(i)+`
343
+
344
+ `+r.trim()+`
345
+ `),{meta:i,body:r.trim(),path:s.path}}};var Nt=new Zi().name("procedure").description("procedures (SOPs) \u2014 list, add, show \xB7 delta extraction coming later");Nt.command("list").description("list all procedures with their trigger line").action(()=>{let t=new nt().list();if(!t.length){console.log(te.dim(" no procedures yet. Add one with: agentx procedure add"));return}console.log();for(let o of t)console.log(` ${te.cyan(o.meta.id)} ${te.bold(o.meta.title)}`),console.log(` ${te.dim("trigger:")} ${o.meta.trigger}`),o.meta.kpis?.length&&console.log(` ${te.dim("kpis:")} ${o.meta.kpis.join(", ")}`);console.log(),console.log(te.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Nt.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-clawd)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new nt,o=e.steps?String(e.steps):`## Steps
346
+
347
+ 1. (fill in)
348
+
349
+ ## Notes
350
+
351
+ `;try{let n=t.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},o);console.log(te.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(te.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(te.red(` add failed: ${n.message}`)),process.exit(1)}});Nt.command("show <id>").description("show a single procedure").action(e=>{let o=new nt().get(e);o||(console.log(te.yellow(` no procedure matches "${e}". Try: agentx procedure list`)),process.exit(1)),console.log(),console.log(te.bold(` ${o.meta.title}`)+te.dim(` (${o.meta.id})`)),console.log(te.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(te.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(te.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(te.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(te.dim(` owner: ${o.meta.owner}`)),o.meta.related?.length&&console.log(te.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});import{Command as er}from"commander";import O from"chalk";import{resolve as tr}from"path";import{existsSync as or,readFileSync as nr}from"fs";var Ee=new er().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ee.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new qt().list();if(!t.length){console.log(O.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(r=>r.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / ");console.log(` ${O.cyan(o.id)} ${O.bold(o.title)} ${O.dim(`v${o.version}`)}`),console.log(` ${O.dim("trigger:")} ${s.source??"?"}${i?` ${O.dim(i)}`:""}`),console.log(` ${O.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(r=>r.type).join(", ")})`)}console.log(),console.log(O.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ee.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new qt().get(e);n||(console.log(O.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(an(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(O.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ee.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=tr(process.cwd(),e);or(i)||(console.log(O.red(` file not found: ${i}`)),process.exit(1));try{let r=nr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?rn(r,{filePath:e}):JSON.parse(r),l=on.safeParse(c);if(!l.success){console.log(O.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let p=nn(l.data);if(p.length){console.log(O.yellow(` ! ${i} (lint)`));for(let d of p)console.log(` ${d}`);process.exit(1)}console.log(O.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof sn?r.message:`parse error: ${r?.message??r}`;console.log(O.red(` ${a}`)),process.exit(1)}return}let o=new qt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(O.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(O.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(O.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ee.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new Ct({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(O.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?O.cyan:s.status==="failed"?O.red:O.green;console.log(` ${O.dim(s.id.slice(0,8))} ${O.bold(s.workflowId)} ${a(r)} ${O.dim(s.status)}`),console.log(` ${O.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${O.dim("home: ")} ${s.homeNode}`),console.log(` ${O.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${O.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(O.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ee.command("run <id>").description("manually trigger a workflow (trigger.manual by default; add --force for any)").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(O.red(" --input must be valid JSON")),process.exit(1)}let n=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(e)}/run`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.force})});if(!s.ok){let r=await s.text();console.log(O.red(` run failed (${s.status}): ${r.slice(0,300)}`)),s.status===409&&console.log(O.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let i=await s.json();console.log(O.green(` \u2713 run started: ${i.runId||"(unknown id)"}${i.force?O.dim(` (forced, source=${i.source})`):""}`))}catch(s){console.log(O.red(` request to daemon failed: ${s.message}`)),process.exit(1)}});Ee.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new Ct({nodeId:o}).setStatus(e,"paused")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 paused ${e}`))});Ee.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new Ct({nodeId:o}).setStatus(e,"running")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 resumed ${e}`))});Ee.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new Ct({nodeId:o}).setStatus(e,"canceled")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 canceled ${e}`))});import{Command as sr}from"commander";import F from"chalk";import Qn from"prompts";function Zt(){let e=P(),[t,o]=(e.node?.bind||"127.0.0.1:18800").split(":");return`http://${t||"127.0.0.1"}:${o||18800}`}async function eo(e,t){let o=await fetch(e,t);if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`HTTP ${o.status}: ${n.slice(0,200)||o.statusText}`)}return await o.json()}var Mt=new sr().name("task").description("workflow user-tasks \u2014 list, show, submit (the terminal inbox)");Mt.command("list").description("list open user-tasks awaiting submission").option("--actor <id>","filter to tasks assigned to this actor id").option("--json","machine-readable JSON output").action(async e=>{try{let t=e.actor?`?actor=${encodeURIComponent(String(e.actor))}`:"",n=(await eo(`${Zt()}/api/workflows/tasks${t}`)).tasks||[];if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(F.dim(" No open tasks.")),console.log();return}console.log(),console.log(F.bold(` ${n.length} open task${n.length===1?"":"s"}`)),console.log();for(let s of n){let i=s.dueAt?F.yellow(` \xB7 due ${s.dueAt.slice(0,16).replace("T"," ")}`):"",r=s.form?.fields?.length||0;console.log(` ${F.bold(s.id)}${i}`),console.log(` ${s.title}`),console.log(F.dim(` workflow=${s.workflowId} node=${s.nodeId} assignee=${s.assignee} fields=${r}`))}console.log(),console.log(F.dim(" agentx task show <id> to see form details")),console.log(F.dim(" agentx task submit <id> to fill it in")),console.log()}catch(t){console.log(F.red(` ${t.message}`)),process.exitCode=1}});Mt.command("show <id>").description("show a single user-task with its form definition").option("--json","machine-readable JSON output").action(async(e,t)=>{try{let n=(await eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(F.dim(` id=${n.id} workflow=${n.workflowId} node=${n.nodeId}`)),console.log(F.dim(` assignee=${n.assignee} status=${n.status}`)),n.dueAt&&console.log(F.yellow(` due ${n.dueAt}`)),console.log();let s=n.form?.fields||[];if(s.length===0)console.log(F.dim(" (no fields)"));else{console.log(F.bold(" Fields:"));for(let i of s){let r=i.required?F.red("*"):" ",a=i.options?.length?F.dim(` [${i.options.join("|")}]`):"",c=i.hint?F.dim(` \u2014 ${i.hint}`):"";console.log(` ${r} ${F.cyan(i.key)} (${i.type})${a}${c}`)}}console.log(),console.log(F.dim(` agentx task submit ${n.id} to fill it in`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});Mt.command("submit <id>").description("fill in and submit a user-task form interactively (or via --json)").option("--as <actor>","submitted-by id (defaults to terminal user)",process.env.USER||"cli").option("--json <body>","non-interactive: pass {action,values} as a JSON string").option("--secondary","click the secondary action instead of primary (e.g. reject)").action(async(e,t)=>{try{let n=(await eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(n.status!=="open"){console.log(F.yellow(` task is ${n.status} \u2014 nothing to submit`));return}let s=t.secondary?"secondary":"primary",i={};if(t.json)try{let c=JSON.parse(t.json);c&&typeof c=="object"&&(i=c.values&&typeof c.values=="object"?c.values:c,c.action==="secondary"&&(s="secondary"))}catch(c){console.log(F.red(` --json parse failed: ${c.message}`)),process.exitCode=1;return}else{console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log();for(let c of n.form?.fields||[]){let l=ir(c.type),p=`${c.label}${c.required?F.red(" *"):""}${c.hint?F.dim(` (${c.hint})`):""}`,d=c.defaultValue!==void 0?c.defaultValue:void 0,m=c.options?.map(w=>({title:w,value:w})),h={type:l,name:c.key,message:p,...d!==void 0?{initial:d}:{},...m?{choices:m}:{},validate:w=>c.required&&(w==null||w==="")?`${c.label} is required`:!0},f=await Qn(h,{onCancel:()=>process.exit(130)});i[c.key]=f[c.key]}if(!t.secondary&&n.form?.secondaryAction){let c=n.form.submitLabel||"Submit",l=n.form.secondaryAction.label;(await Qn({type:"select",name:"action",message:"Action",choices:[{title:c,value:"primary"},{title:l,value:"secondary"}]},{onCancel:()=>process.exit(130)})).action==="secondary"&&(s="secondary")}}let r={submission:{action:s,values:i},submittedBy:t.as},a=await eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if("error"in a){if(console.log(F.red(` ${a.error}`)),a.fieldErrors)for(let[c,l]of Object.entries(a.fieldErrors))console.log(F.red(` ${c}: ${l}`));process.exitCode=1;return}console.log(),console.log(F.green(` Submitted (action=${s}). runId=${a.runId}`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});function ir(e){switch(e){case"long-text":return"text";case"number":return"number";case"boolean":return"confirm";case"date":return"text";case"select":return"select";case"multi-select":return"multiselect";case"file":return"text";default:return"text"}}import{Command as rr}from"commander";import q from"chalk";function yt(e){let{summary:t,backupPath:o}=at(n=>e(n));console.log(q.green(`
352
+ \u2713 ${t}`)),o&&console.log(q.dim(` Backup: ${o}`)),console.log(q.dim(` Restart the daemon (or POST /reload) for the change to take effect.
353
+ `))}function to(){try{return P().business||{}}catch{return{}}}var wt=new rr().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");wt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=to();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(q.yellow(" business block not enabled (or missing).")),console.log(q.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let o=t.orgChart||{},n=t.projects||[],s=t.contactMap||[];console.log(),console.log(q.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(q.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?q.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?q.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${q.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(q.bold(` Projects (${n.length})`)),n.length===0)console.log(q.dim(" (empty)"));else for(let r of n){let a=r.pm?q.dim(` \xB7 pm=${r.pm}`):"",c=r.client?q.dim(` \xB7 client=${r.client}`):"";console.log(` ${q.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(q.bold(` Contact map (${s.length})`)),s.length===0)console.log(q.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${q.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?q.dim(` (${r.displayName})`):""}`)}console.log()});var _o=wt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");_o.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=to(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(q.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${q.cyan(n)} ${s.role}${s.reportsTo?q.dim(` \u2192 ${s.reportsTo}`):""}`)});_o.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,t)=>{let o=String(t.days).split(",").map(n=>n.trim()).filter(Boolean);yt(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:t.role,...t.reportsTo?{reportsTo:t.reportsTo}:{},schedule:{days:o,start:t.start,end:t.end},utilizationTarget:parseFloat(t.utilization)||.8},`orgChart entry "${e}" upserted (role=${t.role}${t.reportsTo?`, reports to ${t.reportsTo}`:""})`))});_o.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{yt(t=>{if(!t.business?.orgChart||!(e in t.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete t.business.orgChart[e],`orgChart entry "${e}" removed`})});var Po=wt.command("project").description("manage business.projects \u2014 id, pm, client");Po.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=to().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(q.dim(" no projects"));return}for(let n of o)console.log(` ${q.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Po.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,t)=>{yt(o=>{o.business=o.business||{},o.business.projects=o.business.projects||[];let n=o.business.projects.findIndex(i=>i.id===e),s={id:e,...t.pm?{pm:t.pm}:{},...t.client?{client:t.client}:{}};return n>=0?o.business.projects[n]={...o.business.projects[n],...s}:o.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Po.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{yt(t=>{let o=t.business?.projects||[],n=o.length;if(t.business.projects=o.filter(s=>s.id!==e),t.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var No=wt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");No.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=to().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(q.dim(" no entries"));return}for(let n of o){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${q.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});No.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(q.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),yt(t=>{t.business=t.business||{},t.business.contactMap=t.business.contactMap||[];let o={client:e.client};e.channel&&(o.channel=e.channel),e.chatId&&(o.chatId=e.chatId),e.username&&(o.username=e.username),e.senderId&&(o.senderId=e.senderId),e.project&&(o.project=e.project),e.displayName&&(o.displayName=e.displayName),t.business.contactMap.push(o);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});No.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{yt(t=>{let o=t.business?.contactMap||[],n=o.length;if(t.business.contactMap=o.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),t.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-t.business.contactMap.length} contact entry/entries removed`})});import{Command as ar}from"commander";import fe from"chalk";function cr(){try{return P().notifications||{}}catch{return{}}}function oo(e){let{summary:t,backupPath:o}=at(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(fe.green(`
354
+ \u2713 ${t}`)),o&&console.log(fe.dim(` Backup: ${o}`)),console.log(fe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
355
+ `))}var $t=new ar().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");$t.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let t=cr();if(e.json){console.log(JSON.stringify(t,null,2));return}if(console.log(),t.destination){let n=t.destination.accountId?` \xB7 account=${t.destination.accountId}`:"";console.log(` destination ${fe.cyan(t.destination.channel+":"+t.destination.chatId)}${fe.dim(n)}`)}else console.log(` destination ${fe.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${fe.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?fe.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?fe.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":fe.dim("off")}`),console.log()});$t.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){oo(t=>(delete t.destination,"notifications destination cleared"));return}oo(t=>(t.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});$t.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,t)=>{let o=["taskComplete","taskError","taskQueued"];o.includes(e)||(console.log(fe.red(` unknown event "${e}". Pick from: ${o.join(", ")}`)),process.exit(1));let n=t.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(fe.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";oo(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});$t.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let t=parseInt(e,10);(!Number.isFinite(t)||t<0)&&(console.log(fe.red(" threshold must be a non-negative integer")),process.exit(1)),oo(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});import{Command as lr}from"commander";import qe from"chalk";import{readdirSync as Mo,statSync as Xn,unlinkSync as dr,rmSync as gr,existsSync as Zn}from"fs";import{resolve as es,join as ts}from"path";var os=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Lo(e,t){if(!Zn(e))return[];let o=[];for(let n of Mo(e,{withFileTypes:!0})){let s=ts(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...Lo(s,!0))}return o}var so=new lr().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");so.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of os){let o=es(process.cwd(),t.dir),n=Lo(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=Xn(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${qe.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${no(s).padStart(10)} oldest=${r}`)}console.log(qe.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${no(e).padStart(10)} total`)),console.log(),console.log(qe.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});so.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let t=parseInt(e.days,10);(!Number.isFinite(t)||t<1)&&(console.log(qe.red(" --days must be a positive integer")),process.exit(1));let o=Date.now()-t*864e5,n=e.target,s=0,i=0;console.log(),console.log(qe.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?qe.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of os){if(n&&r.dir!==n)continue;let a=es(process.cwd(),r.dir),c=Lo(a,!!r.recursive),l=0,p=0;for(let m of c)try{let h=Xn(m);if(h.mtimeMs<o&&(p+=h.size,l++,!e.dryRun))try{dr(m)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ns(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${qe.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${no(p)})`),s+=l,i+=p}console.log(),console.log(qe.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${no(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ns(e){if(Zn(e))for(let t of Mo(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=ts(e,t.name);ns(o);try{Mo(o).length===0&&gr(o,{recursive:!1})}catch{}}}function no(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as ss}from"commander";import J from"chalk";var bt=new ss().name("actor").description("manage actors (humans) that can be assigned to workflow userTasks");bt.command("add").description("add a new actor").argument("<id>","actor id (e.g. alice; 'actor:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--email <email>","email address").option("--telegram <handle>","Telegram user id (numeric)").option("--whatsapp <phone>","WhatsApp phone in E.164 (no +)").option("--slack <memberId>","Slack member id").option("--discord <userId>","Discord user id").option("--timezone <tz>","IANA timezone, e.g. Africa/Tunis").option("--prefer <channel>","mark this channel as preferred for task notifications","").action((e,t)=>{let o=e.startsWith("actor:")?e:`actor:${e}`,n=new xe;if(n.getActor(o)){console.error(J.red(` actor "${o}" already exists. Use 'actor remove' first.`)),process.exitCode=1;return}let s=[],i=(c,l)=>{l&&s.push({channel:c,handle:l,preferredForTasks:t.prefer===c||void 0})};if(i("telegram",t.telegram),i("whatsapp",t.whatsapp),i("slack",t.slack),i("discord",t.discord),t.email&&i("email",t.email),s.length===0){console.error(J.red(" at least one channel handle is required (--telegram, --whatsapp, --slack, --discord, --email)")),process.exitCode=1;return}let r={id:o,name:t.name,email:t.email,channels:s,timezone:t.timezone},a=n.saveActor(r);console.log(J.green(` \u2713 actor "${a.id}" saved (${a.channels.length} channel${a.channels.length===1?"":"s"})`))});bt.command("list").description("list all actors").action(()=>{let t=new xe().listActors();if(!t.length){console.log(J.dim(" no actors yet. Try: agentx actor add alice --name 'Alice' --telegram 12345"));return}console.log();for(let o of t){let n=o.channels.map(s=>`${s.channel}:${s.handle}${s.preferredForTasks?"*":""}`).join(", ");console.log(` ${J.cyan(o.id.padEnd(24))} ${J.bold(o.name)}`),console.log(` ${J.dim(n)}`)}console.log(),console.log(J.dim(` ${t.length} actor${t.length===1?"":"s"}. * = preferred for tasks.`))});bt.command("show").description("print full JSON for an actor").argument("<id>","actor id (with or without 'actor:' prefix)").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`,n=new xe().getActor(t);if(!n){console.error(J.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(JSON.stringify(n,null,2))});bt.command("remove").alias("rm").description("remove an actor (does not clean up role memberships)").argument("<id>","actor id").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`;if(!new xe().deleteActor(t)){console.error(J.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(J.green(` \u2713 actor "${t}" removed`))});var st=new ss().name("role").description("manage roles (groups of actors) for workflow userTasks");st.command("create").description("create a new role").argument("<id>","role id (e.g. reviewers; 'role:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--strategy <strategy>","first-available | round-robin | all | manager-of","first-available").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new xe;if(n.getRole(o)){console.error(J.red(` role "${o}" already exists`)),process.exitCode=1;return}let s=t.strategy,i=n.saveRole({id:o,name:t.name,members:[],assignmentStrategy:s,rotationCursor:0});console.log(J.green(` \u2713 role "${i.id}" created (strategy: ${i.assignmentStrategy})`))});st.command("grant").description("add an actor (or nested role) to a role's members").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new xe,s=n.getRole(o);if(!s){console.error(J.red(` role "${o}" not found`)),process.exitCode=1;return}let i=t.startsWith("actor:")?{actor:t}:t.startsWith("role:")?{role:t}:null;if(!i){console.error(J.red(" member must be 'actor:<id>' or 'role:<id>'")),process.exitCode=1;return}if(s.members.some(a=>JSON.stringify(a)===JSON.stringify(i))){console.log(J.dim(" already a member"));return}let r=n.saveRole({...s,members:[...s.members,i]});console.log(J.green(` \u2713 ${t} granted to ${o} (${r.members.length} member${r.members.length===1?"":"s"})`))});st.command("revoke").description("remove an actor or nested role from a role").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new xe,s=n.getRole(o);if(!s){console.error(J.red(` role "${o}" not found`)),process.exitCode=1;return}let i=s.members.length,r=s.members.filter(a=>"actor"in a?a.actor!==t:a.role!==t);if(r.length===i){console.log(J.dim(` "${t}" was not a member`));return}n.saveRole({...s,members:r}),console.log(J.green(` \u2713 ${t} revoked from ${o}`))});st.command("list").description("list all roles with member counts").action(()=>{let t=new xe().listRoles();if(!t.length){console.log(J.dim(" no roles yet. Try: agentx role create reviewers --name 'Reviewers'"));return}console.log();for(let o of t){console.log(` ${J.cyan(o.id.padEnd(24))} ${J.bold(o.name)} ${J.dim(o.assignmentStrategy)}`);for(let n of o.members){let s="actor"in n?n.actor:n.role;console.log(` ${J.dim("\u2022")} ${s}`)}}console.log(),console.log(J.dim(` ${t.length} role${t.length===1?"":"s"}.`))});st.command("show").description("print full JSON for a role, including resolved members").argument("<id>","role id").action(e=>{let t=e.startsWith("role:")?e:`role:${e}`,o=new xe,n=o.getRole(t);if(!n){console.error(J.red(` role "${t}" not found`)),process.exitCode=1;return}let s=o.resolveMembers({kind:"role",id:n.id});console.log(JSON.stringify({...n,_resolvedActors:s},null,2))});import{Command as mr}from"commander";import B from"chalk";var is=new mr().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let r=P(e.config);t||(t=r.dashboard?.daemonUrl||""),o||(o=r.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${t.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(B.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};o&&(i.Authorization=`Bearer ${o}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(B.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(B.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:p,value:d}=await a.read();if(p)break;l+=c.decode(d,{stream:!0});let m;for(;(m=l.indexOf(`
356
+
357
+ `))>=0;){let h=l.slice(0,m);l=l.slice(m+2),pr(h)}}}catch(r){console.error(B.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function pr(e){let t="message",o="";for(let i of e.split(`
358
+ `))i.startsWith("event: ")?t=i.slice(7):i.startsWith("data: ")&&(o=i.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?B.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=B.cyan(n.phase?.padEnd(9)??"run"),r=B.bold(n.workflowId??""),a=B.dim((n.runId??"").slice(0,8)),c=n.nodeId?B.yellow(n.nodeId):"",l=n.note?B.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=B.magenta(`task.${n.phase}`.padEnd(14)),r=B.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?B.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${B.cyan(a)} ${c}`);break}case"signal":{let i=B.green("signal".padEnd(9)),r=B.bold(n.name),a=B.dim(`(${n.scope})`),c=n.workflowId?B.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=B.blue("mesh".padEnd(9)),r=B.bold(n.peer),a=n.healthy?B.green("\u2713 healthy"):B.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${B.dim(n.delta??"")}`);break}case"channel":{let i=B.yellow("channel".padEnd(9)),r=n.direction==="in"?B.cyan("\u2190"):B.magenta("\u2192"),a=B.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?B.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(B.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}import{Command as ur}from"commander";import ce from"chalk";import{readFileSync as hr}from"fs";var io=["user","feedback","project","reference"],it=new ur().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");it.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!io.includes(e.type)){console.error(ce.red(` --type must be one of: ${io.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await fr();else try{t=hr(e.file,"utf-8")}catch(s){console.error(ce.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(ce.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new rt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(ce.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});it.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let o=new rt().list(e.agent);if(e.type){if(!io.includes(e.type)){console.error(ce.red(` --type must be one of: ${io.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(ce.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of o)s.type!==n&&(console.log(ce.bold(` ${s.type}`)),n=s.type),console.log(` ${ce.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ce.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});it.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{let n=new rt().get(t.agent,e);if(!n){console.error(ce.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ce.bold(`${n.type}/${n.name}`)+ce.dim(` (${n.description})`)),console.log(ce.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});it.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new rt().remove(t.agent,e)){console.error(ce.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ce.green(` \u2713 memory "${e}" removed`))});it.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let o=new rt().indexMarkdown(e.agent);if(!o){console.log(ce.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});async function fr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}import Wo from"chalk";import{Command as yr}from"commander";var rs=new yr().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{e.stdio!==!1?await Vo():(Ie.error("Only stdio transport is currently supported."),Ie.info(`Usage: ${Wo.green("agentx serve --stdio")} or configure in your MCP client.`),Ie.break(),Ie.info("Add to Claude Code:"),Ie.info(Wo.dim(" claude mcp add agentx -- npx agentx serve --stdio")),Ie.break(),Ie.info("Add to Cursor/MCP config:"),Ie.info(Wo.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){dn(t)}});import{Command as wr}from"commander";import ge from"chalk";var Fo=new wr().name("bench").description("benchmark harnesses (context strategies, ...)");Fo.command("context").description("run the same message under 'layered' vs 'planner' strategies and compare").requiredOption("--agent <id>","agent id to send the message to").requiredOption("--message <text>","the user message to bench").option("--channel <name>","channel label for the request context","bench").option("--chat-id <id>","chatId for session scoping","bench-harness").option("--sender <name>","sender label for the request context","bench").option("--runs <n>","number of runs per strategy (averaged)","1").option("--preview <chars>","how many response chars to print","280").option("--url <url>","daemon URL override (default: from agentx.json)").action(async e=>{let t=Math.max(1,parseInt(e.runs,10)||1),o=Math.max(0,parseInt(e.preview,10)||280),n=e.url||kr();console.log(),console.log(ge.bold(" Context-strategy benchmark")),console.log(ge.dim(` agent=${e.agent}, channel=${e.channel}, chatId=${e.chatId}, runs=${t}`)),console.log(ge.dim(` daemon=${n}`)),console.log();let s=await as(n,"layered",e,t),i=await as(n,"planner",e,t);br(s,i,o)});async function as(e,t,o,n){let s=0,i=0,r=0,a=0,c=0,l=0,p=0,d="",m;for(let f=0;f<n;f++){let w=Date.now();try{let k=await(await fetch(`${e}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:o.agent,message:o.message,contextStrategy:t,context:{channel:o.channel,chatId:o.chatId,sender:o.sender}}),signal:AbortSignal.timeout(6e5)})).json();if(k.error){p++,m=k.error;continue}s+=k.duration??Date.now()-w,i+=k.usage?.inputTokens??0,r+=k.usage?.outputTokens??0,a+=k.usage?.cacheReadTokens??0,c+=k.usage?.cacheCreateTokens??0,l+=$r(k.usage),d=k.content??""}catch(y){p++,m=y.message??String(y)}}let h=n-p||1;return{strategy:t,runs:n,errors:p,avgDurationMs:Math.round(s/h),avgInput:Math.round(i/h),avgOutput:Math.round(r/h),avgCacheRead:Math.round(a/h),avgCacheCreate:Math.round(c/h),avgTotalInput:Math.round((i+a+c)/h),avgCost:l/h,lastResponse:d,lastError:m}}function $r(e){if(!e)return 0;let t=3/1e6,o=15/1e6,n=.3/1e6,s=3.75/1e6;return(e.inputTokens??0)*t+(e.outputTokens??0)*o+(e.cacheReadTokens??0)*n+(e.cacheCreateTokens??0)*s}function br(e,t,o){let n=(a,c)=>a.length>=c?a:a+" ".repeat(c-a.length),s=a=>a.toLocaleString();console.log(ge.bold(" "+n("metric",22)+n("layered",18)+n("planner",18)+"delta")),console.log(ge.dim(" "+"-".repeat(74)));let i=[["input tokens",e.avgInput,t.avgInput,s],["output tokens",e.avgOutput,t.avgOutput,s],["cache read",e.avgCacheRead,t.avgCacheRead,s],["cache create",e.avgCacheCreate,t.avgCacheCreate,s],["total input",e.avgTotalInput,t.avgTotalInput,s],["est. cost ($)",e.avgCost,t.avgCost,a=>a.toFixed(4)],["duration (ms)",e.avgDurationMs,t.avgDurationMs,s]];for(let[a,c,l,p]of i){let d=l-c,m=c===0?0:d/c*100,h=d===0?ge.dim("\xB10"):d<0?ge.green(`${p(d)} (${m.toFixed(0)}%)`):ge.red(`+${p(d)} (+${m.toFixed(0)}%)`);console.log(" "+n(a,22)+n(p(c),18)+n(p(l),18)+h)}console.log(ge.dim(" "+"-".repeat(74))),(e.errors>0||t.errors>0)&&console.log(ge.yellow(` errors: layered=${e.errors} (${e.lastError??""}), planner=${t.errors} (${t.lastError??""})`)),console.log(),o>0&&(console.log(ge.bold(" Response preview (last run of each):")),console.log(ge.dim(" layered:")),console.log(" "+cs(e.lastResponse,o).split(`
359
+ `).join(`
360
+ `)),console.log(ge.dim(" planner:")),console.log(" "+cs(t.lastResponse,o).split(`
361
+ `).join(`
362
+ `)),console.log());let r=t.avgTotalInput-e.avgTotalInput;if(r<0){let a=e.avgTotalInput===0?0:Math.abs(r/e.avgTotalInput)*100;console.log(ge.green(` Planner saved ${s(Math.abs(r))} input tokens/run (${a.toFixed(0)}% less).`))}else r>0&&console.log(ge.yellow(` Planner used ${s(r)} MORE input tokens \u2014 investigate before enabling.`));console.log()}function cs(e,t){return e?e.length>t?e.slice(0,t)+"\u2026":e:"(empty)"}function kr(){try{let e=P(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}import{Command as vr}from"commander";import oe from"chalk";var Je=new vr().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Je.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let o=(await Lt("/whatsapp/chats")).chats??[];if(e.group&&(o=o.filter(n=>n.isGroup)),e.dm&&(o=o.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(oe.dim(" no chats cached yet"));return}console.log(),console.log(oe.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?oe.cyan("group"):oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${oe.dim(n.jid.padEnd(40))} ${oe.dim(i)}`)}console.log()}catch(t){kt(t)}});Je.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let o=(await Lt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(oe.dim(" no contacts cached yet"));return}console.log(),console.log(oe.bold(` ${o.length} contact${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${oe.dim(i)} ${oe.dim(n.jid)}`)}console.log()}catch(t){kt(t)}});Je.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let o=await Uo("/whatsapp/ingest",t);Bo(o,!!e.dryRun)}catch(t){kt(t)}});Je.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(o.agent=t.agent);let n=await Uo("/whatsapp/ingest",o);Bo(n,!!t.dryRun)}catch(o){kt(o)}});Je.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(o.agent=t.agent),t.messages&&(o.forceMode="messages");let n=await Uo("/whatsapp/ingest",o);Bo(n,!!t.dryRun)}catch(o){kt(o)}});Je.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Lt("/whatsapp/state"),t=await Lt("/whatsapp/chats"),o=await Lt("/whatsapp/contacts");console.log(),console.log(oe.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${o.contacts?.length??0}`),console.log()}catch(e){kt(e)}});function Bo(e,t){if(console.log(),console.log(oe.bold(t?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(oe.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(oe.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(oe.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(oe.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function ls(){try{let e=P(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function Lt(e){let t=await fetch(`${ls()}${e}`,{signal:AbortSignal.timeout(1e4)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(o.error||`HTTP ${t.status}`);return o}async function Uo(e,t){let o=await fetch(`${ls()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function kt(e){console.error(oe.red(` ${e.message||e}`)),process.exit(1)}import{Command as xr}from"commander";import z from"chalk";import{existsSync as Sr,mkdirSync as ds,writeFileSync as Wt}from"fs";import{join as vt,resolve as jr}from"path";var Ft=new xr().name("plugin").description("manage agentx plugins (Move B)");Ft.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(z.dim(" No plugins configured.")),console.log(z.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(z.bold(` Plugins configured: ${t.length}`)),console.log();for(let o of t)console.log(` ${z.cyan(o)}`);console.log(),console.log(z.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(z.red(` ${e.message}`)),process.exitCode=1}});Ft.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,t)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(z.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let o=e.startsWith("@")?e.split("/")[1]:e,n=jr(t.cwd,o);Sr(n)&&!t.force&&(console.log(z.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),ds(n,{recursive:!0}),ds(vt(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Wt(vt(n,"package.json"),Ir(e,s)),Wt(vt(n,"tsconfig.json"),Or()),Wt(vt(n,"src/index.ts"),Rr(e)),Wt(vt(n,"README.md"),Dr(e,s)),Wt(vt(n,".gitignore"),Tr()),console.log(),console.log(z.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(z.bold(" Next steps:")),console.log(z.dim(` cd ${o}`)),console.log(z.dim(" pnpm install")),console.log(z.dim(" pnpm build")),console.log(z.dim(" pnpm link --global # for local testing")),console.log(z.dim(" # then in your agentx project:")),console.log(z.dim(` pnpm link --global ${e}`)),console.log(z.dim(` agentx config set plugins[0] "${e}"`)),console.log(z.dim(" agentx plugin doctor")),console.log()});Ft.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(z.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Cr(n);s.kind==="ok"?console.log(` ${z.green("\u2713")} ${z.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${z.red("\u2717")} ${z.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(z.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(z.red(` ${e.message}`)),process.exitCode=1}});async function Cr(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=Er(t);if(!Ar(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=tn.safeParse(o.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function Er(e){if(e==null||typeof e!="object")return e;let t=e;if(t.default&&typeof t.default=="object"){let o=t.default;if(o.manifest&&typeof o.setup=="function")return o;if(o.default&&typeof o.default=="object"){let n=o.default;if(n.manifest&&typeof n.setup=="function")return n}}return t.manifest&&typeof t.setup=="function"?t:t.default??t}function Ar(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Ir(e,t){return JSON.stringify({name:e,version:"0.1.0",description:t,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
363
+ `}function Or(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
364
+ `}function Rr(e){return`// ${e} \u2014 AgentX plugin
365
+ //
366
+ // A plugin's default export is { manifest, setup }. The daemon calls
367
+ // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
368
+ // registers a custom channel adapter; ctx.log() namespaces output.
369
+
370
+ const plugin = {
371
+ manifest: {
372
+ name: ${JSON.stringify(e)},
373
+ version: "0.1.0",
374
+ // agentxRange: "0.x", // optional \u2014 gate against the daemon's major.minor
375
+ },
376
+
377
+ setup(ctx: any) {
378
+ ctx.log("hello from", ${JSON.stringify(e)})
379
+
380
+ // Example: log every completed task.
381
+ ctx.on("task:completed", (payload: any) => {
382
+ ctx.log("task done:", payload.agentId, payload.durationMs + "ms")
383
+ })
384
+
385
+ // Example: register a no-op channel adapter.
386
+ // ctx.addChannel({
387
+ // name: "my-channel",
388
+ // start: async () => {},
389
+ // stop: async () => {},
390
+ // send: async (out) => { ctx.log("send:", out) },
391
+ // })
392
+ },
393
+
394
+ // Optional \u2014 only needed for resources you own (timers, sockets).
395
+ // Bus subscriptions are removed automatically.
396
+ // teardown() {},
397
+ }
398
+
399
+ export default plugin
400
+ `}function Dr(e,t){return`# ${e}
401
+
402
+ ${t}
403
+
404
+ ## Install
405
+
406
+ \`\`\`bash
407
+ pnpm install ${e}
408
+ \`\`\`
409
+
410
+ ## Use
411
+
412
+ Add to \`agentx.json\`:
413
+
414
+ \`\`\`json
415
+ {
416
+ "plugins": ["${e}"]
417
+ }
418
+ \`\`\`
419
+
420
+ Then verify the load:
421
+
422
+ \`\`\`bash
423
+ agentx plugin doctor
424
+ \`\`\`
425
+
426
+ Restart the daemon to activate.
427
+ `}function Tr(){return`node_modules/
428
+ dist/
429
+ *.log
430
+ .env
431
+ `}import{Command as _r}from"commander";import ne from"chalk";import{writeFileSync as Pr,mkdirSync as Nr,existsSync as ro,readFileSync as gs,appendFileSync as ms}from"fs";import{resolve as xt,dirname as hs}from"path";import{homedir as Jo}from"os";var fs=new _r().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-SASDC2GV.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Wr(o);break;case"bash":s=Jr(o);break;case"fish":s=zr(o);break;default:console.error(ne.red(`unsupported shell: ${n}`)),console.error(ne.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?xt(String(e.output)):Mr(n);Nr(hs(i),{recursive:!0}),Pr(i,s),console.log(ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Lr(n,i,!!e.yes)});function Mr(e){let t=Jo();switch(e){case"zsh":return xt(t,".zsh","completions","_agentx");case"bash":return xt(t,".bash_completion.d","agentx.bash");case"fish":return xt(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Lr(e,t,o){if(e==="zsh"){let n=xt(Jo(),".zshrc"),s=hs(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ro(n)?gs(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(ne.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&ro(n)){let p=["","# agentx completion"];c&&p.push(i),l&&p.push(r),ms(n,p.join(`
432
+ `)+`
433
+ `),console.log(ne.green("\u2713 Patched ~/.zshrc")),console.log(ne.dim("Reload your shell: exec zsh"));return}console.log(ne.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(ne.cyan(` ${i}`)),l&&console.log(ne.cyan(` ${r}`)),console.log(),console.log(ne.dim("Then reload: exec zsh")),console.log(ne.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=xt(Jo(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((ro(n)?gs(n,"utf-8"):"").includes(t)){console.log(ne.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&ro(n)){ms(n,`
434
+ # agentx completion
435
+ ${s}
436
+ `),console.log(ne.green("\u2713 Patched ~/.bashrc")),console.log(ne.dim("Reload your shell: exec bash"));return}console.log(ne.dim("Add this to ~/.bashrc:")),console.log(ne.cyan(` ${s}`)),console.log(),console.log(ne.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(ne.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function pe(e){return e._name||e.name()||""}function ze(e){return e.commands.filter(t=>{let o=pe(t);return!(!o||o==="help"||t._hidden)})}function Bt(e){return e.options.filter(t=>!t.hidden)}function Wr(e){let t=[];return t.push("#compdef agentx"),t.push(""),ys(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
437
+ `)}function ps(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function ys(e,t,o){let n=ze(e),i=Bt(e).map(Ur).filter(c=>!!c),r=ps(t);if(o.push(`${r}() {`),o.push(" local -a commands"),o.push(" local -a options"),o.push(" "),i.length===0&&n.length===0){o.push(" return 0"),o.push("}"),o.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(qr).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}o.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;o.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){o.push(""),o.push(" case $state in"),o.push(" (args)"),o.push(" case $line[1] in");for(let c of n){let l=ps([...t,pe(c)]);o.push(` (${pe(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)ys(c,[...t,pe(c)],o)}function Fr(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Br(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Ur(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=Fr(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function qr(e){let t=Br(e.description()||"");return`'${pe(e)}[${t}]'`}function Jr(e){let t=ze(e),o=[];o.push("# bash completion for agentx"),o.push("_agentx_complete() {"),o.push(" local cur prev words cword"),o.push(" COMPREPLY=()"),o.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),o.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),o.push(""),o.push(` local top="${t.map(pe).join(" ")}"`),o.push(""),o.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),o.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),o.push(" return 0"),o.push(" fi"),o.push(""),o.push(' local cmd="${COMP_WORDS[1]}"'),o.push(' local sub2="${COMP_WORDS[2]:-}"'),o.push(' case "$cmd" in');for(let n of t){let s=ze(n).map(pe),i=us(n);if(o.push(` ${pe(n)})`),s.length>0){o.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),o.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),o.push(" return 0"),o.push(" fi"),o.push(' case "$sub2" in');for(let r of ze(n)){let a=us(r);o.push(` ${pe(r)})`),o.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),o.push(" return 0"),o.push(" ;;")}o.push(" esac")}else o.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push("complete -F _agentx_complete agentx"),o.push(""),o.join(`
438
+ `)}function us(e){let t=[];for(let o of Bt(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function zr(e){let t=[];t.push("# fish completion for agentx"),t.push(""),t.push("complete -c agentx -f"),t.push(""),t.push("# top-level commands");for(let o of ze(e)){let n=zo(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${pe(o)}" -d "${n}"`)}t.push("");for(let o of Bt(e)){let n=qo(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of ze(e)){let n=pe(o);t.push(`# ${n}`);for(let s of Bt(o)){let i=qo(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of ze(o)){let i=zo(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${ze(o).map(pe).join(" ")}" -a "${pe(s)}" -d "${i}"`);for(let r of Bt(s)){let a=qo(r,[`__fish_seen_subcommand_from ${pe(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
439
+ `)}function zo(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function qo(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=zo(e.description||""),r=["complete -c agentx",t.map(a=>`-n "${a}"`).join(" ")];return o&&r.push(`-s ${o}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function bg(){let e=await gn(),t=new Gr().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");return t.addCommand(Se).addCommand(kn).addCommand(wn).addCommand(dt).addCommand(zt).addCommand(et).addCommand(gt).addCommand(Be).addCommand(mt).addCommand(pt).addCommand(Ot).addCommand(Re).addCommand(Fe).addCommand(Qe).addCommand(wo).addCommand($o).addCommand(Me).addCommand(Qt).addCommand(Ue).addCommand(V).addCommand(Pt).addCommand(Nt).addCommand(Ee).addCommand(Mt).addCommand(wt).addCommand($t).addCommand(so).addCommand(bt).addCommand(st).addCommand(is).addCommand(it).addCommand(It).addCommand(pn).addCommand(rs).addCommand(Fo).addCommand(Je).addCommand(Ft).addCommand(fs),t}export{bg as a};
440
+ //# sourceMappingURL=chunk-SV3I4CI7.js.map