agentix-cli 0.69.4 → 0.70.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.
- package/dist/{agent-IDAWXA3K.js → agent-V223TG6H.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js → board-dashboard-HR3PQPFW.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js.map → board-dashboard-HR3PQPFW.js.map} +1 -1
- package/dist/{chunk-CKBAVCGU.js → chunk-3IY2YWXP.js} +2 -2
- package/dist/{chunk-J7HA7ZTU.js → chunk-3RC4LO2G.js} +2 -2
- package/dist/{chunk-M6GPRMCQ.js → chunk-6QDOUOKD.js} +2 -2
- package/dist/{chunk-64P4QHSZ.js → chunk-CECHWYJ2.js} +1 -1
- package/dist/{chunk-64P4QHSZ.js.map → chunk-CECHWYJ2.js.map} +1 -1
- package/dist/{chunk-K63IOY6A.js → chunk-FBDIJEKL.js} +4 -4
- package/dist/chunk-FBDIJEKL.js.map +1 -0
- package/dist/{chunk-OHRTBD7U.js → chunk-LHLNARRW.js} +9 -9
- package/dist/chunk-ML6CNRBK.js +105 -0
- package/dist/chunk-ML6CNRBK.js.map +1 -0
- package/dist/{chunk-5ONI54E6.js → chunk-PHDS2HIN.js} +118 -118
- package/dist/chunk-PHDS2HIN.js.map +1 -0
- package/dist/{chunk-2UYV24UD.js → chunk-SN5N2FPG.js} +2 -2
- package/dist/chunk-TLDQWTSW.js +49 -0
- package/dist/chunk-TLDQWTSW.js.map +1 -0
- package/dist/chunk-TTVVXBCM.js +2 -0
- package/dist/chunk-TTVVXBCM.js.map +1 -0
- package/dist/{chunk-IU6L4V3A.js → chunk-W7SEPJFH.js} +2 -2
- package/dist/chunk-WLMQ5JMX.js +6 -0
- package/dist/chunk-WLMQ5JMX.js.map +1 -0
- package/dist/{chunk-DQQ3BCJW.js → chunk-YK7GFEGO.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/graph-FJ53FDWK.js +2 -0
- package/dist/index.d.ts +20 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate-v2-ZOIMGITH.js +4 -0
- package/dist/{migrate-v2-KOMPDC6U.js.map → migrate-v2-ZOIMGITH.js.map} +1 -1
- package/dist/program-UTELWTXC.js +2 -0
- package/dist/promote-B5AOKPQR.js +2 -0
- package/dist/query-QLJNQUUP.js +2 -0
- package/dist/registry-CTZFLXGB.js +2 -0
- package/dist/types-NZOBHQGS.js +2 -0
- package/dist/wiki-X76JUHXT.js +2 -0
- package/dist/wiki-X76JUHXT.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-4DRNEOOW.js +0 -2
- package/dist/chunk-4DRNEOOW.js.map +0 -1
- package/dist/chunk-535MLOSB.js +0 -109
- package/dist/chunk-535MLOSB.js.map +0 -1
- package/dist/chunk-5ONI54E6.js.map +0 -1
- package/dist/chunk-K63IOY6A.js.map +0 -1
- package/dist/chunk-V2TLFYKH.js +0 -45
- package/dist/chunk-V2TLFYKH.js.map +0 -1
- package/dist/migrate-v2-KOMPDC6U.js +0 -4
- package/dist/program-T275Y2V6.js +0 -2
- package/dist/promote-VZAUTV6E.js +0 -2
- package/dist/query-7QQZPMXM.js +0 -2
- package/dist/registry-WQ65MQEY.js +0 -2
- package/dist/types-S6NHM5C3.js +0 -2
- package/dist/wiki-J4MMCONT.js +0 -2
- /package/dist/{agent-IDAWXA3K.js.map → agent-V223TG6H.js.map} +0 -0
- /package/dist/{chunk-CKBAVCGU.js.map → chunk-3IY2YWXP.js.map} +0 -0
- /package/dist/{chunk-J7HA7ZTU.js.map → chunk-3RC4LO2G.js.map} +0 -0
- /package/dist/{chunk-M6GPRMCQ.js.map → chunk-6QDOUOKD.js.map} +0 -0
- /package/dist/{chunk-OHRTBD7U.js.map → chunk-LHLNARRW.js.map} +0 -0
- /package/dist/{chunk-2UYV24UD.js.map → chunk-SN5N2FPG.js.map} +0 -0
- /package/dist/{chunk-IU6L4V3A.js.map → chunk-W7SEPJFH.js.map} +0 -0
- /package/dist/{chunk-DQQ3BCJW.js.map → chunk-YK7GFEGO.js.map} +0 -0
- /package/dist/{program-T275Y2V6.js.map → graph-FJ53FDWK.js.map} +0 -0
- /package/dist/{promote-VZAUTV6E.js.map → program-UTELWTXC.js.map} +0 -0
- /package/dist/{query-7QQZPMXM.js.map → promote-B5AOKPQR.js.map} +0 -0
- /package/dist/{registry-WQ65MQEY.js.map → query-QLJNQUUP.js.map} +0 -0
- /package/dist/{types-S6NHM5C3.js.map → registry-CTZFLXGB.js.map} +0 -0
- /package/dist/{wiki-J4MMCONT.js.map → types-NZOBHQGS.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Gc,b as Zn,g as zc}from"./chunk-OVX6NRMD.js";import{a as Mc,c as Lc}from"./chunk-KLHG5ZQH.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-
|
|
1
|
+
import{a as Gc,b as Zn,g as zc}from"./chunk-OVX6NRMD.js";import{a as Mc,c as Lc}from"./chunk-KLHG5ZQH.js";import{a as ct,b as Rc,f as _c,g as Dc,h as Pc,i as Qn,j as Fc,k as Uc,l as hi,m as Jc,o as Hc}from"./chunk-6QDOUOKD.js";import{a as qc,c as Wc,d as Bc}from"./chunk-Z3IP66SL.js";import{a as ni,b as ma}from"./chunk-RKPAVWXF.js";import{c as na}from"./chunk-SZDACK6O.js";import{a as ho}from"./chunk-GV7S5BAX.js";import{e as oa}from"./chunk-GSX4NK2N.js";import{$ as Cc,A as ri,B as cc,C as lc,D as dc,E as gc,F as mc,G as pc,H as wc,I as bc,J as wo,K as Yn,L as di,M as $c,N as kc,O as vc,P as xc,Q as bo,R as $o,S as Sc,T as Ec,U as Re,V as Vn,W as an,X as gi,Y as Ac,Z as Tc,_ as ui,a as $a,aa as Kn,b as ka,ba as ko,ca as Xn,da as fi,ea as Nc,h as Un,i as Ea,j as nn,k as qn,l as Oa,m as Ta,n as Ia,o as Ca,p as Ba,q as Ja,r as Hn,s as ii,t as Va,u as ec,v as nc,w as sc,x as ic,y as rc,z as ac}from"./chunk-PHDS2HIN.js";import{A as Qa,B as Za,Ma as at,N as sn,Oa as Ic,P as ai,Q as Gn,R as uc,ba as Et,ca as fc,da as ci,fa as li,ha as hc,ia as yc,ja as rn,m as St,na as zn,q as Ka,t as Xa,va as jc,wa as mi,xa as Oc,ya as pi}from"./chunk-3IY2YWXP.js";import{a as va,d as xa,e as Sa}from"./chunk-YBF2QVZ7.js";import{a as Wn,b as Bn,c as Na,d as Ra,e as _a,g as Da,h as Pa,j as Ma,k as La,l as Fa,m as Ua,p as Jn,r as qa,s as Wa}from"./chunk-BYJ3A55Y.js";import{a as Aa,p as ja}from"./chunk-YK7GFEGO.js";import{a as Ha,b as Ga,c as za,d as Ya}from"./chunk-2D3RYIDU.js";import{a as tc,b as oc}from"./chunk-EKJG63EJ.js";import{B as xt,H as da,S as ga,h as Vr,q as Kr,v as ei,w as ea}from"./chunk-FBDIJEKL.js";import{b as mo,g as uo,h as Ln,i as Fn,j as fo,k as ta,l as Ht,m as on}from"./chunk-W7SEPJFH.js";import{e as aa,f as oi,k as ca}from"./chunk-WP6KLXTP.js";import{a as Yr}from"./chunk-N6EWZGIX.js";import{b as po}from"./chunk-DP7RTNDM.js";import{a as si,e as pa,f as ua,h as fa,i as ha,k as ya,l as wa,m as ba}from"./chunk-FSYA4GNU.js";import{f as sa,g as ia,h as ti}from"./chunk-76Z4VHDX.js";import{a as Qr,k as ra}from"./chunk-OPUPVGYP.js";import{b as ye,c as Te,d as yo,e as la}from"./chunk-YL223TEU.js";import{a as Qs}from"./chunk-SN5N2FPG.js";import{a as Zs,b as Xr}from"./chunk-GQ76J72O.js";import{j as Zr}from"./chunk-X5C5W3E4.js";import{h as zr}from"./chunk-DWADWDMU.js";import{b as go,d as Gr}from"./chunk-2GIDVZ4H.js";import{b as vt,e as Mn}from"./chunk-WLMQ5JMX.js";import{a as Xs,b as Cr,c as em,d as Dn,e as Nr,f as Ur,g as nm,h as qr,i as sm,m as lo,n as Br,o as Jr,s as Hr,v as rt,w as tn}from"./chunk-BBIWAJRX.js";import{a as Wr,b as im}from"./chunk-FX3D7YON.js";import{a as ft,b as co,e as Mr,f as en}from"./chunk-72SZI2UW.js";import{a as ut,b as Zg}from"./chunk-7I7IEX4S.js";import{m as Rr,n as _r,p as Dr,q as tm,v as Pr,w as I,x as Pn,z as ae}from"./chunk-DTX4I5LQ.js";import{g as Lr,k as Fr,l as om}from"./chunk-RGDKHYY2.js";import{Command as rm}from"commander";var Yc=new rm().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new ka({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});ae();import{Command as am}from"commander";import{execFileSync as Xe}from"node:child_process";import{cpSync as Vc,existsSync as bi,mkdirSync as yi,mkdtempSync as cm,readdirSync as lm,rmSync as Kc,writeFileSync as Xc}from"node:fs";import{dirname as Qc,join as De}from"node:path";import{homedir as es,release as dm,tmpdir as gm}from"node:os";import{setTimeout as mm}from"node:timers/promises";function ts(){let e=Na(process.platform,process.arch,dm());if(e)throw new Error(e)}function os(){let e=De(es(),"Library/LaunchAgents"),t=[];try{t=lm(e).filter(Da)}catch{}let o=t.flatMap(n=>{let s=De(e,n);try{return[{file:s,plist:Xe("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Pa(e,o)}function cn(e){return`gui/${process.getuid()}/${e.label}`}async function wi(e){try{Xe("launchctl",["bootout",cn(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{return}await mm(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Zc(e){if(!bi(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Xe("launchctl",["print",cn(e)],{stdio:"pipe"})}catch{t=!1}t||Xe("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Xe("launchctl",["kickstart",cn(e)],{stdio:"pipe"})}function pm(){let e=Ua();if(e&&bi(De(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var vo=new am("desktop").description("install and control the macOS desktop assistant");vo.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{ts();let t=I(),o=Ra(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=pm(),r=De(es(),"Applications"),{keep:a,remove:c}=os();if(console.log(`Desktop assistant \u2192 ${De(r,Wn)}
|
|
2
2
|
Computer-use helper \u2192 ${De(r,Bn)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -403,7 +403,7 @@ return aid ?? null`}function Yu(e,t){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
403
403
|
settings \u2014 without this an attached production identity would be less
|
|
404
404
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(N.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});Pt.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let t=sl({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(t.path)} (${t.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(N.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});ae();import{Command as Cf}from"commander";import we from"chalk";var As=new Cf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Ld(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=I(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Fd(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Md(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function Nf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}As.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:t,token:o}=Ld(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Fd(o)})}catch(r){console.log(we.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.red(` HTTP ${n.status} from ${t}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(we.dim(" (no processes)"));return}for(let r of i){let a=Nf(r.state)(r.state.padEnd(9)),c=Md(r.spawnedAt),l=r.lastTurnAt?Md(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});As.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,t,o,n)=>{let{baseUrl:s,token:i}=Ld(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Fd(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${t}:${o}`))});import{Command as Rf}from"commander";import Me from"chalk";import{existsSync as Vi,rmSync as _f}from"fs";import{resolve as Ki}from"path";var _o=new Rf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");_o.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(Me.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),i=await sa(e,t,{verbose:n}),r=Date.now()-s;console.log(Me.green(` \u2713 indexed ${i.docs} doc(s) for ${Me.bold(e)} in ${r}ms`)),console.log(Me.dim(` \u2192 ${i.path}`))});_o.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Ki(e.cwd,".agentx","rag");if(!Vi(t)){console.log(Me.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Vi(Ki(t,s,"index.json")));if(n.length===0){console.log(Me.dim(" (no indexes)"));return}for(let s of n.sort()){let i=ti(s);console.log(` ${Me.bold(s)} ${i.docs} doc(s) ${Me.dim(i.path)}`)}});_o.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=ia(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=ti(e);i.exists?console.log(Me.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Me.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Me.bold(i.title)} ${Me.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Me.dim(i.path)}`),console.log(` ${Me.dim(i.snippet.slice(0,200))}`)});_o.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Ki(process.cwd(),".agentx","rag",e);if(!Vi(t)){console.log(Me.dim(` no index for ${e} \u2014 nothing to clear`));return}_f(t,{recursive:!0,force:!0}),console.log(Me.green(` \u2713 cleared index for ${e}`))});ae();import{Command as Df}from"commander";import X from"chalk";import Do from"prompts";var no=new Df().name("backlog").description("manage the local backlog used by business workSource=backlog");function kn(e){let t=I(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new jc(n)}}function Pf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function Mf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}no.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}=kn(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(X.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${Mf(n.status).padEnd(7)} ${Pf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});no.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=kn(o.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Oc([t],i.source,n.config),a=await pi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});no.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=kn(t.config);o.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await pi(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});no.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}=kn(t.config);o.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});no.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=kn(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(X.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 Do({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Ff(t.config):Uf(t.config);y.length?(i=(await Do({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Do({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Do({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await qf(t.config,i,a):await Wf(t.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let $=mi({type:s,project:l,iid:y.iid,url:y.url}),b=g.has($),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Do({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(X.dim(" nothing selected"));return}let p=f.map(y=>{let $={type:s,host:s==="gitlab"?Lf(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:mi($),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:$,importedAt:new Date().toISOString()}}),w=t.store.addMany(p);console.log(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function Lf(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ff(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 Uf(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 qf(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 Wf(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(Ud)}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(Ud):[]}function Ud(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 Bf}from"commander";import W from"chalk";import{existsSync as Jf,readFileSync as Hf}from"fs";import{resolve as Gf}from"path";import zf from"prompts";ae();function qd(e){let t=e||Gf(process.cwd(),"agentx.json");return Jf(t)||(console.log(W.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Hf(t,"utf-8"))}async function Yf(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(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await zf([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{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(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var wt=new Bf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wt.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: ${si})`,si).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){wt.help();return}t.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let o=ni(e);o||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=qd(t.config),s=Pr(n);n.agents?.[t.agent]||(console.log(W.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Yf(t.notify,s),r=t.id||ma(o.matched,t.agent),a=ua({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:i,onError:pa(t.onError),enabled:!t.disabled}),c=a.onError,l=await ye(d=>Te(d,`crons.${r}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(W.dim(` Agent: ${t.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.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=qd(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=ha(fa(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])wt.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await ba(o,t);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ye(o=>{if(!yo(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);la(o,`crons.${e}`)});t.success||(console.log(W.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ya,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",wa,"reject an agent's pending create/delete request (drops the request)"]])wt.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await t(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});wt.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ni(t);o||(console.log(W.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(W.green(` "${t}"`)),console.log(W.dim(` \u2192 ${o.cron}`)),console.log(W.dim(` \u2192 ${o.human}`))});import{Command as Vf}from"commander";import xe from"chalk";var Mt=new Vf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Kf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Wd(){return{root:process.cwd()}}function Xi(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Xf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Kf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Xi(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Xi(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mt.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Qa(Wd(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let o of t.errors)console.log(xe.red(` couldn't read ${o.kind}: ${o.error}`));if(t.items.length===0){console.log(xe.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let o of t.items)Xf(o),console.log();console.log(xe.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Qi(e,t,o){let n=Qn(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Za(Wd(),e,t,{force:o.force,note:o.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mt.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,t)=>Qi(e,"yes",t));Mt.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>Qi(e,"no",t));Mt.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>Qi(e,"later",t));Mt.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Ka.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let t=Qn(),o=Xa(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:t});if(!o.ok){console.error(xe.red(` ${o.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${o.card.id} raised; expires ${Xi(o.card.expires)}, then: ${o.card.if_silent}`))});Mt.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let t={},o=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),t.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let a=Fc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(t).some(a=>a!==void 0)){let a=await Uc(t);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Qn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as $h}from"commander";import Po from"chalk";import se from"chalk";import xn from"prompts";import{readFileSync as Qf,writeFileSync as Zf,existsSync as eh}from"fs";import{resolve as Bd}from"path";var th=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function oh(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Zi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Jd(e=".env"){let t=Bd(e);if(!eh(t))return[];let o=Qf(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(th);i?n.push({kind:"kv",key:i[1],value:oh(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function nh(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Zi(t.value)}`:t.raw).join(`
|
|
405
405
|
`)+`
|
|
406
|
-
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(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 ih(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 Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.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(se.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(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Te(b,"channels.telegram.enabled",!0),Te(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Te(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({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(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let y=await ih(o.trim(),9e4);if(!y){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let $=await ye(b=>{Te(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(se.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(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(g=>{let u=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Te(l,"channels.whatsapp.enabled",!0),Te(l,"channels.whatsapp.sessionDir",n),Te(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ae from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(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 yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(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(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Te(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Te(i,"mesh.enabled",!0);let r=yo(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),Te(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.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(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.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 Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.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 Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.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 Kd({url:e.url,configPath:e.config})});Qd.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 Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[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(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-T275Y2V6.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.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{try{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-MAP6A2N7.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
406
|
+
`}function vn(e,t,o=".env"){let n=Bd(o),s=Jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Zi(t)}`})),Zf(n,nh(s))}function er(e,t=".env"){return Jd(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Hd="https://t.me/BotFather";async function sh(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 ih(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 Gd(e={}){console.log(),console.log(se.bold(" Connect Telegram")),console.log(),console.log(se.dim(` 1. Open ${Hd}`)),console.log(se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await xn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[Hd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await sh(o.trim());n||(console.log(se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(se.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(se.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(se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(se.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;vn(f,o.trim()),process.env[f]=o.trim();let p=await ye(b=>{Te(b,"channels.telegram.enabled",!0),Te(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=yo(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Te(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(se.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(se.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(se.dim(` Token stored in .env as ${f}`)),console.log(se.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(se.dim(" Daemon hot-reloaded.")):console.log(se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await xn({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(se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(se.dim(" Waiting up to 90s..."));let y=await ih(o.trim(),9e4);if(!y){console.log(se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(se.dim(" agentx config set notifications.destination.channel telegram")),console.log(se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(se.dim(` agentx config set notifications.destination.accountId ${u}`));return}let $=await ye(b=>{Te(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!$.success){console.log(se.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(se.green(" \u2713 Default --notify target set")),console.log(se.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(se.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(se.dim(" Daemon hot-reloaded."))}import be from"chalk";import tr from"prompts";import{existsSync as nr,mkdirSync as rh,readdirSync as ah,readFileSync as zd}from"fs";import{resolve as or}from"path";var ch=".agentx/whatsapp-sessions";function lh(){let e=or(process.cwd(),".agentx/daemon.pid");if(!nr(e))return!1;try{let t=parseInt(zd(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function dh(e){if(!nr(e))return!1;try{return ah(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function gh(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rh(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(g=>{let u=setTimeout(()=>{t(be.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(be.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(u),t(be.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),t(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Yd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),lh()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await tr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let t=e.configPath||or(process.cwd(),"agentx.json");nr(t)||(console.log(be.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(zd(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ch,s=or(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await tr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dh(s)&&a){let{keep:l}=await tr({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gh(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Te(l,"channels.whatsapp.enabled",!0),Te(l,"channels.whatsapp.sessionDir",n),Te(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mh}from"crypto";import Ae from"chalk";import Vd from"prompts";var js="agentx-mesh:",Os="//join/";function ph(e){return Buffer.from(e,"utf-8").toString("base64url")}function uh(e){return Buffer.from(e,"base64url").toString("utf-8")}function fh(e){return`${js}${Os}${ph(JSON.stringify(e))}`}function hh(e){if(!e.startsWith(`${js}${Os}`))throw new Error(`Not a mesh invite link \u2014 expected ${js}${Os}\u2026`);let t=e.slice(js.length+Os.length),o=JSON.parse(uh(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 yh(){return mh(32).toString("hex")}function wh(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function bh(e){return e?.node?.name||e?.node?.id||"node"}async function Kd(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(Ae.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=er("MESH_TOKEN");r||(r=yh(),vn("MESH_TOKEN",r),console.log(Ae.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wh(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Vd({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(Ae.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Te(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ae.red(` \u2717 ${l.error}`)),process.exit(1));let g=fh({url:a,token:r,name:bh(i),version:1});console.log(),console.log(Ae.bold(" Mesh invite")),console.log(),console.log(` ${Ae.cyan(g)}`),console.log(),console.log(Ae.dim(" Run on the other node:")),console.log(Ae.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ae.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Xd(e,t={}){let o;try{o=hh(e)}catch(i){console.log(Ae.red(` \u2717 ${i.message}`)),process.exit(1)}let n=er("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Vd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ae.red(" Aborted (keeping existing .env)")),process.exit(1))}vn("MESH_TOKEN",o.token);let s=await ye(i=>{Te(i,"mesh.enabled",!0);let r=yo(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),Te(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Ae.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ae.green(" \u2713 Joined mesh")),console.log(Ae.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ae.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ae.dim(" Daemon hot-reloaded.")):console.log(Ae.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(Ae.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ae.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ae.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Mo=new $h().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Mo.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 Gd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Mo.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 Yd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Qd=Mo.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Qd.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 Kd({url:e.url,configPath:e.config})});Qd.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 Xd(e,{configPath:t.config})});Mo.action(()=>{console.log(),console.log(Po.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Po.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Po.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Po.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Po.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Po.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as kh}from"commander";import ue from"chalk";var Sn=new kh().name("usage").description("token usage analysis and reporting");Sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[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(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});Sn.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});Sn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-HVVP22SA.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-UTELWTXC.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vh}from"commander";import $e from"chalk";import{readFileSync as xh}from"fs";import{resolve as Sh}from"path";ae();var Lt=new vh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lt.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{try{Gr(Sh(process.cwd(),".env"))}catch{}let t=Eh(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-HR3PQPFW.js");o(t)}catch(t){console.log($e.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log($e.dim(t.stack)),process.exit(1)}});function Eh(e,t){try{let o=I();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
407
407
|
`)),{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}}}}Lt.command("list").description("list configured boards").action(()=>{try{let e=I();if(!e.boards?.length){console.log($e.dim(`
|
|
408
408
|
No boards configured.
|
|
409
409
|
`));return}console.log();for(let t of e.boards){console.log(` ${$e.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log($e.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log($e.dim(` primary label: ${t.primaryToolLabel}`)),console.log($e.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lt.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. 'globex/system,globex/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{En(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($e.red(` ${o.message}`)),process.exit(1)}});Lt.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{En(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($e.red(` ${o.message}`)),process.exit(1)}});var sr=Lt.command("column").description("manage a board's columns (add / remove / edit / list)");sr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(xh("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($e.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(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(t){console.log($e.red(` ${t.message}`)),process.exit(1)}});sr.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{En(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($e.red(` ${n.message}`)),process.exit(1)}});sr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{En(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($e.red(` ${o.message}`)),process.exit(1)}});Lt.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{En(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($e.red(` ${t.message}`)),process.exit(1)}});function En(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log($e.green(`
|
|
@@ -416,13 +416,13 @@ ${k.content}
|
|
|
416
416
|
|
|
417
417
|
`),v="";if(e.facts!==!1){let{extractHints:k,resolveFacts:R,mergeRecords:C,renderFactsBlock:T,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-X44PF73W.js");if(!a){let J=new Set;for(let Oe of o.listAgents())for(let ke of o.getAgentWiki(Oe).listArticles(Oe))ke.meta.type==="person"&&J.add(ke.meta.title);a=[...J]}let G=k(p.map(J=>({context:J.sourceContext,content:J.content,sender:typeof J.meta?.sender=="string"?J.meta.sender:void 0})),{known:a}),me=L(p);if(G.length>0||me.length>0){let J=B(),{records:Oe,results:ke}=G.length>0?await R(G,{sources:J}):{records:[],results:[]},M=C([...me,...Oe]);v=T(M);let Ye=[...me.length>0?[`entries:${me.length}`]:[],...ke.filter(ve=>ve.records.length>0).map(ve=>`${ve.source}:${ve.records.length}`)];console.log(m.dim(` Facts: ${G.length} entities \u2192 ${M.length} resolved${Ye.length?` (${Ye.join(" ")})`:""}`));for(let ve of P(ke,J))console.log(m.yellow(` ! ${ve.source} ${ve.kind} \u2014 would supply ${ve.provides.join(", ")}`)),console.log(m.dim(` ${ve.hint}`))}}let A=Aa(t,u,$,y.articles,b,p.length,v);console.log(m.dim(` Mode: ${rr(t)}`));let S=F(w.baseDir,"_tmp");bt(S,{recursive:!0});let x=F(S,"absorb-prompt.txt");io(x,A),console.log(m.dim(" Compiling with Claude..."));try{let k;try{k=so(`cat '${x}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:go({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(k=M.stdout||"",!k)throw M}let R=k;try{let M=JSON.parse(k);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let C,T=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let G=R[L],me=G==="{"?"}":"]",J=0,Oe=-1;for(let M=L;M<R.length;M++)if(R[M]===G)J++;else if(R[M]===me&&(J--,J===0)){Oe=M+1;break}if(Oe===-1){console.log(m.red(" Unbalanced JSON"));continue}let ke=R.slice(L,Oe);try{let M=JSON.parse(ke);Array.isArray(M)?C=M:(C=M.articles||[],T=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let M of C){let Ye=new Date().toISOString().slice(0,10),ve=l(M.sources||[],p);w.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Ye,lastUpdated:Ye,sources:M.sources||[],graphPath:ve},M.content,u);let Jt=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${Jt}${M.path}: ${M.title}${m.dim(_)}`);let he=(M.tags||[]).slice(0,4).join(", ");he&&console.log(m.dim(` tags: ${he}`)),ve?.length&&(console.log(m.dim(` graphPath: ${ve.join(" \u203A ")}`)),d++),g++}if(T.length>0){console.log(),console.log(m.yellow(` Gaps detected (${T.length} missing pieces):`));for(let M of T)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Ye=new M(ro(e.dir)).add(T.map(ve=>({kind:"article",agentId:u,path:"",subject:String(ve).slice(0,120),question:`No article yet for: ${String(ve).slice(0,160)}`})));Ye.added>0&&console.log(m.dim(` queued ${Ye.added} for follow-up (agentx wiki questions)`))}catch{}}w.rebuildIndex()}catch(k){console.log(m.red(` Absorb failed: ${k.message?.slice(0,200)}`)),k.stderr&&console.log(m.dim(String(k.stderr).slice(0,300))),k.stdout&&console.log(m.dim("stdout: "+String(k.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=Ch(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-FLY6HZEN.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ve(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{g.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:c,failuresToCandidates:l}=await import("./failure-candidates-RIXA3Y6D.js"),{default:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ve(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(t??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let w=p[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await ja({extraCandidates:i,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.clusters){let c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.memory.description}`))}if(console.log(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.proposed){let c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var Is=Z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Cs(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Is.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(Cs(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${r}`))}});Is.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(Cs(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
418
418
|
`).map(s=>` ${s}`).join(`
|
|
419
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-
|
|
419
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});Is.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-B5AOKPQR.js"),n=o(Cs(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});Is.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-B5AOKPQR.js"),n=o(Cs(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Ch(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Z.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",F(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-QLJNQUUP.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=je(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=o(d).sort().reverse();for(let y of f){let $=r(d,y),b=[];try{b=o($).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(u.length>=g)break;try{let A=JSON.parse(n(r($,v),"utf-8")),S=A.message||A.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:A.id||v.replace(".json",""),message:S.trim(),ts:A.at||A.timestamp||y})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.length} messages from ${c}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.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<u.length;y++){let $=u[y];process.stdout.write(m.dim(` [${y+1}/${u.length}] querying... `));let v=l.findRelevant($.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
420
420
|
`)||"_(none returned)_",A;try{let S=await t($.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")A=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let x=S.citations.map(k=>`\`${k.title}\` [${k.type||"?"}]`).join(", ");A=`**Answer:**
|
|
421
421
|
|
|
422
422
|
${S.answer}
|
|
423
423
|
|
|
424
424
|
**Citations:** ${x}`}}catch(S){A=`_(error: ${S.message})_`}console.log(m.dim("done")),p.push(`## ${y+1}. ${$.id}`,"",`> ${$.message.replace(/\n/g," ").slice(0,400)}${$.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",v,"","### NEW \u2014 agentic query","",A,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=p.join(`
|
|
425
|
-
`);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Z.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. 'Globex 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-
|
|
425
|
+
`);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(m.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});Z.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. 'Globex 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-NZOBHQGS.js"),s=e.answers?An(e.answers,"utf-8").split(/\r?\n/).filter(_=>_.length>0):null,i=0;if(!e.agent){console.log(m.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=je(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(_){console.log(m.red(` can't open wiki for agent "${e.agent}": ${_.message}`));return}let c=s?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async _=>{if(s){let he=s[i++]??"";return process.stdout.write(_+m.dim(`[scripted] ${he.slice(0,80)}${he.length>80?"\u2026":""}`)+`
|
|
426
426
|
`),he.trim()}return(await c.question(_)).trim()};console.log(),console.log(m.bold(" Wiki Interview")),console.log(m.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let g=e.topic||"";if(!g&&(g=await l(m.cyan(" Topic? ")+m.dim("(a person, a procedure, a past event, \u2026) ")),!g||g==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),u=new Set(n);if(!u.has(d)){console.log(m.dim(` Types: ${n.join(" | ")}`));let _=await l(m.cyan(" Type? "));if(_==="/abort"){c?.close();return}u.has(_)?d=_:(console.log(m.yellow(` "${_}" isn't a valid type. Falling back to "concept".`)),d="concept")}let f={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?"]},p=f[d]||f.concept;console.log(),console.log(m.bold(` Topic: ${m.cyan(g)} \xB7 Type: ${m.magenta(d)}`)),console.log(m.dim(` ${p.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let _=0;_<p.length;_++){let he=p[_],Ke=await l(` ${m.dim(`[${_+1}/${p.length}]`)} ${he}
|
|
427
427
|
${m.green(">")} `);if(Ke==="/abort"){y=!0;break}if(Ke==="/done")break;Ke!=="/skip"&&Ke&&w.push({q:he,a:Ke})}if(!y){let _=await l(`
|
|
428
428
|
${m.dim("Anything else worth capturing?")}
|
|
@@ -433,7 +433,7 @@ Q: ${_.q}
|
|
|
433
433
|
A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(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(`
|
|
434
434
|
`),A=F(a.baseDir,"_tmp");bt(A,{recursive:!0});let S=F(A,`interview-${o().slice(0,8)}.txt`);io(S,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let x="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,he=so(_,{env:go({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ke=JSON.parse(he);x=String(Ke.result||Ke.content||"")}catch{x=he}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}x=x.trim();let k=x.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(x=k[1].trim());let R=x.indexOf("---");R>0&&(x=x.slice(R));let C=x.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!C){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(x.slice(0,600)),c?.close();return}let T={};for(let _ of C[1].split(`
|
|
435
435
|
`)){let he=_.match(/^(\w+):\s*(.+)$/);he&&(T[he[1]]=he[2].trim().replace(/^"(.*)"$/,"$1"))}let P=C[2],B=T.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),me=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${me}`)),console.log(),console.log(x),console.log();let J=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),J==="scrap"||J==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Oe=P,ke={title:B,type:T.type||d,related:T.related?T.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:T.tags?T.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:T.access||"public",created:T.created||new Date().toISOString().slice(0,10),lastUpdated:T.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(J==="edit"){let _=process.env.EDITOR||"vi",he=F(A,`draft-${o().slice(0,8)}.md`);io(he,x);try{so(`${_} '${he}'`,{stdio:"inherit"});let Vs=An(he,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Vs){let kt={};for(let Zo of Vs[1].split(`
|
|
436
|
-
`)){let Ks=Zo.match(/^(\w+):\s*(.+)$/);Ks&&(kt[Ks[1]]=Ks[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=Vs[2],ke={...ke,title:kt.title||ke.title,type:kt.type||ke.type,access:kt.access||ke.access,related:kt.related?kt.related.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:kt.tags?kt.tags.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ke){console.log(m.red(` editor failed: ${Ke.message}`));return}}if(!a.writeArticle(me,ke,Oe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ye=a.extractWikilinks(Oe),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Jt=Ye.filter(_=>!ve.has(_.toLowerCase()));if(Jt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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-
|
|
436
|
+
`)){let Ks=Zo.match(/^(\w+):\s*(.+)$/);Ks&&(kt[Ks[1]]=Ks[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=Vs[2],ke={...ke,title:kt.title||ke.title,type:kt.type||ke.type,access:kt.access||ke.access,related:kt.related?kt.related.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.related,tags:kt.tags?kt.tags.replace(/^\[|\]$/g,"").split(",").map(Zo=>Zo.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ke.tags}}}catch(Ke){console.log(m.red(` editor failed: ${Ke.message}`));return}}if(!a.writeArticle(me,ke,Oe,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${me} saved.`));let Ye=a.extractWikilinks(Oe),ve=new Map;for(let _ of a.listArticles(e.agent))ve.set(_.meta.title.toLowerCase(),!0);let Jt=Ye.filter(_=>!ve.has(_.toLowerCase()));if(Jt.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of Jt.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.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-QLJNQUUP.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=je(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=An(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of p){let y=w.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let $=y[0].replace(/^Q:\s*/i,"").trim(),b=y.slice(1).join(" ").trim();$&&b&&r.push({q:$,verdict:b})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,w;if(r){let G=r[f];if(!G)break;p=G.q,w=G.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(G){console.log(m.red(`failed: ${G.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let G=y.citations.map(me=>`${me.title} [${me.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
437
437
|
`)),console.log(m.dim(" citations: "+G))}r||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let $={q:p,answer:y.answer,citations:y.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push($);continue}let v=b[1].toLowerCase(),A=(b[2]||"").trim();if(d.push($),v==="/ok"||v==="/skip")continue;if(!A){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let x=i.readArticle(S.path);if(!x){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let k=Rh(x.content,v,A,x.meta.title,x.meta.type),R=F(i.baseDir,"_tmp");bt(R,{recursive:!0});let C=F(R,`quiz-patch-${o().slice(0,8)}.txt`);io(C,k);let T="";try{let G=`cat '${C}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,me=so(G,{env:go({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Oe=JSON.parse(me);T=String(Oe.result||Oe.content||"")}catch{T=me}let J=T.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);J&&(T=J[1].trim()),T=T.trim()}catch(G){console.log(m.red(` patch failed: ${G.message?.slice(0,120)}`));continue}if(!T||T.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=x.content.split(`
|
|
438
438
|
`).length,B=T.split(`
|
|
439
439
|
`).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),$.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...x.meta,lastUpdated:new Date().toISOString().slice(0,10)},T,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,$.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let w=d[p];f.push(`## ${p+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}\``:""),"")}io(e.out,f.join(`
|
|
@@ -496,12 +496,12 @@ Output (JSON array, one entry per input article, same order):
|
|
|
496
496
|
...
|
|
497
497
|
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=je(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});Z.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||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-FZ4D4EAV.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),Hc(t,o,e.agent,n,e.mode)});Z.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-F3S2HG5G.js"),c=je(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let y of l){let $=c.getAgentWiki(y);for(let b of $.listArticles(y)){if(u.length>=g)break e;let v=$.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let A={...t(v.meta.type),...e.fields?i(v.meta.type):{}},S=await a(s,o({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),A,{links:[{kind:"article",id:b.path}],features:{agent:y,type:v.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let x=n(S.answers),k=e.fields?r(v.meta.type,S.answers):null;x.completeness>=d&&!(k&&!k.fit)||u.push({agent:y,type:v.meta.type??"?",score:x.completeness.toFixed(2),standsAlone:x.standsAlone.toFixed(2),gap:x.biggestGap,...k?{missing:k.missingCritical.join(",")||"-",cov:`${Math.round(k.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((y,$)=>parseFloat(y.score)-parseFloat($.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(y=>Math.max(y.length,...u.map($=>String($[y]).length))),w=y=>y.map(($,b)=>String($).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let y of u)console.log(w(f.map($=>y[$])));if(e.fields){let y=u.filter($=>$.missing!=="-").length;console.log(m.dim(`
|
|
498
498
|
${u.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
|
|
499
|
-
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});Z.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-7QQZPMXM.js"),n=je(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.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(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(t.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.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(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.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(async(e,t)=>{let o=je(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});Z.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=je(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ve(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vt({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let k=w.get(x);if(!k)continue;let R=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:R}),T=r.get(C);if(!T?.length)continue;let P=T.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:T,n:1})}if(A.size===0)continue;$++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=je(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-FZ4D4EAV.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.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(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Z.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||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Qs(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:rr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.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 g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.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?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ve(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Ph(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-F3S2HG5G.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=je(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let k=l.getAgentWiki(x);for(let R of k.listArticles(x)){if(f>=u)break e;let C=k.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let T=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,T.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(ro(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...p.map(k=>$(k[x]).length))),v=(x,k)=>String(x)+" ".repeat(Math.max(0,b[k]-$(x).length));console.log(),console.log(m.bold(y.map((x,k)=>v(x,k)).join(" ")));for(let x of p)console.log(y.map((k,R)=>v(x[k],R)).join(" "));let A=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),k=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=k);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-FZ4D4EAV.js"),T=C(),P=T?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
499
|
+
${u.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});Z.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-QLJNQUUP.js"),n=je(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=F(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.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(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(t.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.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(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.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(async(e,t)=>{let o=je(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=await o.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});Z.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=je(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ve(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new vt({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of o){let u=t.getAgentWiki(d),f=u.listArticles(d),p=t.getSharedStore().listEntries(),w=new Map(p.map(v=>[v.id,v])),y=0,$=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let A=new Map;for(let x of v.meta.sources){let k=w.get(x);if(!k)continue;let R=String(k.meta?.sender??""),C=s.fingerprint({text:k.content,channel:k.source,sender:R}),T=r.get(C);if(!T?.length)continue;let P=T.join("/"),B=A.get(P);B?B.n++:A.set(P,{path:T,n:1})}if(A.size===0)continue;$++,l++;let S;for(let x of A.values())(!S||x.n>S.n)&&(S=x);S&&(e.dryRun||(u.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${$} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let o=je(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-FZ4D4EAV.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.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(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});Z.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||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Qs(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),u=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),p=new Set,w=0,y=new Set;for(let b of d.articles){for(let v of b.tags||[])p.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])y.add(v)}let $=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:rr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:$.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.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 g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.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?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=F(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:g}=await import("fs"),d=Ve(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Ph(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-F3S2HG5G.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=je(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let x of d){let k=l.getAgentWiki(x);for(let R of k.listArticles(x)){if(f>=u)break e;let C=k.readArticle(R.path);if(!C||e.type&&C.meta.type!==e.type)continue;f++;let T=await a(r,n({title:C.meta.title,type:C.meta.type,body:C.content}),t(C.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:x,type:C.meta.type??"?"}});if(!T){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=o(C.meta.type,T.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:x,path:R.path,subject:C.meta.title,field:B.field,tier:B.tier,question:`${C.meta.title} (${C.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:x,article:C.meta.title.slice(0,40)}))}}let w={added:0,skipped:0};if(e.ask&&g.length>0&&(w=new c(ro(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],$=x=>String(x).replace(/\u001b\[[0-9;]*m/g,""),b=y.map(x=>Math.max(x.length,...p.map(k=>$(k[x]).length))),v=(x,k)=>String(x)+" ".repeat(Math.max(0,b[k]-$(x).length));console.log(),console.log(m.bold(y.map((x,k)=>v(x,k)).join(" ")));for(let x of p)console.log(y.map((k,R)=>v(x[k],R)).join(" "));let A=p.filter(x=>x.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${A} can be closed by a lookup; ${p.length-A} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:x}=await import("./article-fields-PITN4NHA.js"),k=x[e.notifyTier]??x.pillar,R=g.filter(C=>(x[C.tier??"furniture"]??9)<=k);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:C}=await import("./config-FZ4D4EAV.js"),T=C(),P=T?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(J=>`\u2022 ${J.question}`).join(`
|
|
500
500
|
`),L=R.length>10?`
|
|
501
501
|
\u2026and ${R.length-10} more`:"",G=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
502
502
|
${B}${L}
|
|
503
503
|
|
|
504
|
-
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-F3S2HG5G.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=je(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(d(f.getSharedStore().listEntries())),b=new Map($.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Oe]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(k)));for(let T of S)console.log(C(k.map(P=>T[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir)),a=r.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!r.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=r.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-CH7R756S.js"),y=new w(ro(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=je(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});Z.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-F3S2HG5G.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=je(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ke)=>ke.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ph(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"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.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=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let $=Fh(w,a,c),b=null;try{b=await Uh(n,o,$,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.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=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-KOMPDC6U.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com: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=I();if(!t.graph?.enabled){console.log(D.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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let k=await fetch(`${o}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch(k){console.log(D.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=l?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${o}`}),c.add(k.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let k of d)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(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(`
|
|
504
|
+
agentx wiki questions`,me=T?.daemon?.port??T?.port??18800;try{let J=await fetch(`http://127.0.0.1:${me}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:G})});console.log(J.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${J.status}) \u2014 questions are still queued.`))}catch(J){console.log(m.yellow(` Push failed (${String(J?.message??J).slice(0,80)}) \u2014 questions are still queued.`))}}}}});Z.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-F3S2HG5G.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-X44PF73W.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=je(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),y=g(),$=c(d(f.getSharedStore().listEntries())),b=new Map($.map(T=>[T.name.toLowerCase().trim(),T])),v=0,A=0,S=[],x=!1;e:for(let T of p){let P=f.getAgentWiki(T);for(let B of P.listArticles(T)){if(v>=w)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;v++;let G=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),t(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:T,op:"backfill"}});if(!G){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let J=o(L.meta.type,G.answers).missing.filter(_=>i.includes(_));if(J.length===0)continue;let{records:Oe,results:ke}=await a([{name:L.meta.title,type:"person"}],{sources:y}),M=b.get(L.meta.title.toLowerCase().trim());if(!x){for(let _ of l(ke,y))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));x=!0}let Ye=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,he])=>[_,he.value]))}]:[],...Oe]);if(Ye.length===0)continue;let{content:ve,edits:Jt}=u(L.content,Ye[0],J);if(Jt.length!==0){for(let _ of Jt)S.push({agent:T,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,ve,T)?A++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let k=["agent","article","field","action","got"],R=k.map(T=>Math.max(T.length,...S.map(P=>String(P[T]).length))),C=T=>T.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(C(k)));for(let T of S)console.log(C(k.map(P=>T[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${A} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});Z.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(ro(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,i)=>(o[s.tier??"furniture"]??9)-(o[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});Z.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(ro(o.dir)),a=r.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!r.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=r.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-CH7R756S.js"),y=new w(ro(o.dir));try{let $=y.get(c.factId);if($){let b=y.write({subject:$.subject,attribute:$.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:$.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${$.id} ${$.subject} \xB7 ${$.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch($){$?.name!=="LedgerCorruptError"&&console.log(m.red(` ${$?.message??$}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=je(o.dir,o.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});Z.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-F3S2HG5G.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=je(e.dir,"graph").getSharedStore(),p=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:y,backlog:$}=r(p,w),b=a(y,L=>L.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},A=[],S=0,x=Date.now();if(e.load){let{readFileSync:L}=await import("fs");A.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${A.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${$} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let G=await i(t,n(L),o,{features:{source:L.source??"",absorbed:L.absorbed}});if(!G){S++;continue}let me=G.answers;A.push({entry:L,verdict:s(G.answers,v),citeWorthy:me.citeWorthy?.noul})}if(A.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(A)),console.log(m.dim(` saved ${A.length} outcome(s) to ${e.save}`))}let k=c(A,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(A,"seat","seat"),C=d(R,{minN:50}),T=((Date.now()-x)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:k,calibration:C,failures:S,elapsed:T},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${k.n} (${k.positives} kept by absorb, ${k.negatives} passed over)`),console.log(` recall ${P(k.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(k.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(k.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${k.lostPositives>0?m.yellow(`lost ${k.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in C)||!C.insufficient)&&console.log(` ECE ${C.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),k.lostPositives>0){let L=k.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=k.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${T}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:G,points:me}=g(A,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${me.length} policies, recall floor ${P(L)})`)),G)console.log(` best: ${G.requireTyped?`typed & type>=${G.minType}`:"type gate OFF"} worth>=${G.minWorth} durability>=${G.minDurability}`),console.log(` recall ${P(G.recall)} \xB7 filtered ${P(G.filtered)} \xB7 precision ${P(G.precision)} \xB7 lost ${G.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let J=me.slice().sort((Oe,ke)=>ke.recall-Oe.recall)[0];J&&console.log(m.dim(` Best recall available: ${P(J.recall)} at ${J.requireTyped?`type>=${J.minType}`:"type gate OFF"} worth>=${J.minWorth} dur>=${J.minDurability}, filtering ${P(J.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});Z.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=F(process.cwd(),e);Ve(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ve(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=F(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Ph(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"}im();import{Command as Mh}from"commander";import D from"chalk";import{resolve as Ns}from"path";import{existsSync as Lh}from"fs";ae();var Uo=new Mh().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Uo.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=I();if(!t.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(D.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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let w=r[p],y=Mn(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(w.msgHash.slice(0,8))} ${D.dim(y)} ... `);let $=Fh(w,a,c),b=null;try{b=await Uh(n,o,$,t.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),A=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(A)),e.dryRun)l++;else try{qh(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:A}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else v==="reject"?(console.log(D.red("REJECT")+" "+D.dim(A)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:A}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(A||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Uo.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=I();if(!t.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ns(process.cwd(),t.graph.baseDir);if(!Lh(o)){console.log(D.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-ZOIMGITH.js"),s=new vt({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Uo.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com: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=I();if(!t.graph?.enabled){console.log(D.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 vt({baseDir:Ns(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(k=>k.id));console.log(),console.log(D.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let k=await fetch(`${o}/graph/schema`,{headers:s});if(!k.ok)throw new Error(`schema HTTP ${k.status}`);l=(await k.json()).schema;let C=await fetch(`${o}/graph/nodes`,{headers:s});if(!C.ok)throw new Error(`nodes HTTP ${C.status}`);g=(await C.json()).nodes||[];let T=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!T.ok)throw new Error(`classifications HTTP ${T.status}`);d=(await T.json()).classifications||[]}catch(k){console.log(D.red(` fetch failed: ${k.message}`));return}let u=r.levels.map(k=>k.id).join(","),f=l?.levels?.map(k=>k.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let w=p?r:l,y=new Map;w.levels.forEach((k,R)=>y.set(k.id,R));let $=[...g].sort((k,R)=>(y.get(k.level)??99)-(y.get(R.level)??99)),b=0,v=0,A=0;for(let k of $){if(c.has(k.id)){v++;continue}if(e.dryRun){b++,c.add(k.id);continue}try{i.addNode({...k,createdBy:k.createdBy?`${k.createdBy} (sync)`:`sync:${o}`}),c.add(k.id),b++}catch(R){A++,console.log(D.yellow(` skip node ${k.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${A} failed`));let S=0,x=0;for(let k of d)if(!(!k.msgHash||!Array.isArray(k.path))){if(i.getFingerprint(k.msgHash)){x++;continue}if(e.dryRun){S++;continue}i.setFingerprint(k.msgHash,{path:k.path,leaf:k.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${x} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${o}`)),console.log()});function Fh(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(`
|
|
505
505
|
`),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(`
|
|
506
506
|
`)}async function Uh(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 Wr((c?.content||"").toString())}finally{clearTimeout(r)}}function qh(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function ar(){let e=I();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let t=Ns(process.cwd(),e.graph.baseDir);return{store:new vt({baseDir:t}),baseDir:t}}var cr=Uo.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");cr.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let t=ar();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=t.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(Mn(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});cr.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ar();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${t}: ${Mn(r[0].path,c)||r[0].path.join(" \u203A ")}`)),o.path&&console.log(D.dim(` should have been: ${o.path}`))});cr.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=ar();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),i=new o(t.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as zh}from"commander";import V from"chalk";import{Command as rg}from"commander";import le from"chalk";import{existsSync as Wh}from"fs";import{resolve as Bh}from"path";import Jh from"better-sqlite3";function Hh(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(le.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Gh(e){let t=Bh(process.cwd(),e);return Wh(t)||(console.log(le.red(` No db at ${t}`)),process.exit(1)),new Jh(t,{readonly:!0})}var ag=new rg().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(nn)).option("--max <n>","max clusters distilled per run",String(qn)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(le.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=Gh(e.path),o=await Oa(t,{since:Hh(e.since),agentId:e.agent,sessions:new Kr(process.cwd()),minOccurrences:Number(e.minOccurrences)||nn,max:Number(e.max)||qn,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(le.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${le.cyan(n.key)} ${le.bold(`\xD7${n.count}`)} ${le.dim(n.status)}`),n.sampleMessage&&console.log(le.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(le.dim(`
|
|
507
507
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(le.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(le.green(` \u2713 draft written: ${n.id}`)+le.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(le.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(le.yellow(` \u26A0 ${n}`));o.dryRun?console.log(le.dim(`
|
|
@@ -630,7 +630,7 @@ Restart the daemon to activate.
|
|
|
630
630
|
dist/
|
|
631
631
|
*.log
|
|
632
632
|
.env
|
|
633
|
-
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().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-
|
|
633
|
+
`}import{Command as aw}from"commander";import Ne from"chalk";import{writeFileSync as cw,mkdirSync as lw,existsSync as Gs,readFileSync as qg,appendFileSync as Wg}from"fs";import{resolve as Ko,dirname as Hg}from"path";import{homedir as Er}from"os";var Gg=new aw().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-UTELWTXC.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=mw(o);break;case"bash":s=yw(o);break;case"fish":s=ww(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?Ko(String(e.output)):dw(n);lw(Hg(i),{recursive:!0}),cw(i,s),console.log(Ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),gw(n,i,!!e.yes)});function dw(e){let t=Er();switch(e){case"zsh":return Ko(t,".zsh","completions","_agentx");case"bash":return Ko(t,".bash_completion.d","agentx.bash");case"fish":return Ko(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function gw(e,t,o){if(e==="zsh"){let n=Ko(Er(),".zshrc"),s=Hg(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Gs(n)?qg(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&&Gs(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Wg(n,g.join(`
|
|
634
634
|
`)+`
|
|
635
635
|
`),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=Ko(Er(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Gs(n)?qg(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&&Gs(n)){Wg(n,`
|
|
636
636
|
# agentx completion
|
|
@@ -646,4 +646,4 @@ ${bw({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
646
646
|
${o.url}`)}catch(t){console.error(Qo.red(` ${t.message}`)),process.exitCode=1}});_n.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",jr).action(async(e,t)=>{try{let o=await Ir(t.models);if(!Or(t.model,o)){console.log(Tr(t.model,o)),process.exitCode=1;return}let n=e==="-"?await vw():await kw(e,"utf8"),s=JSON.parse(n),{version:i}=await Un(),r=Kg({...s,fields:s.fields??{}},{model:t.model,version:i??"unknown"});console.log(r)}catch(o){console.error(Qo.red(` ${o.message}`)),process.exitCode=1}});async function vw(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Sj(){let e=await Un(),t=new xw().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");t.hook("preAction",(o,n)=>{let s=Wc(n);Bc(s)&&qc("cli",s)});for(let o of[yl,ul,Mo,vo,Eo,Qe,Lc,Yt,cs,wt,Mt,Pt,as,Ag,Rt,Ml,Gl,bn,nd,ad,cd,Ed,Td,Id,Ro,Sn,Cg,mn,Ot,Gg,_n])t.addCommand(o);for(let o of Qg)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Qg.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Sw(o,74," "),""].join(`
|
|
647
647
|
`)}),t}var Qg=[Z,Uo,qt,it,un,_o,Ge,$t,Lt,no,Jo,Ho,Ct,Be,To,As,xg,Sg,ht,Vt,Yc,Kt,Nn,Ti,Ut,jo,Ii,Ls,pt,Wt,Pg,Lg,Ig];function Sw(e,t,o){let n=[],s="";for(let i of e)s&&s.length+i.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+i;return s&&n.push(o+s),n.join(`
|
|
648
648
|
`)}export{Sj as a};
|
|
649
|
-
//# sourceMappingURL=chunk-
|
|
649
|
+
//# sourceMappingURL=chunk-LHLNARRW.js.map
|