agentix-cli 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +12 -6
  2. package/dist/agent-4AOMVXRJ.js +2 -0
  3. package/dist/board-dashboard-CXIVJKDP.js +7282 -0
  4. package/dist/board-dashboard-CXIVJKDP.js.map +1 -0
  5. package/dist/chunk-34NG7UDX.js +11 -0
  6. package/dist/chunk-34NG7UDX.js.map +1 -0
  7. package/dist/chunk-4HP6UC2X.js +13 -0
  8. package/dist/chunk-4HP6UC2X.js.map +1 -0
  9. package/dist/chunk-5F3J55LG.js +2 -0
  10. package/dist/chunk-5F3J55LG.js.map +1 -0
  11. package/dist/chunk-5WNGHDFC.js +164 -0
  12. package/dist/chunk-5WNGHDFC.js.map +1 -0
  13. package/dist/{chunk-7MBTMCKY.js → chunk-63UYRJIC.js} +2 -2
  14. package/dist/chunk-64P4QHSZ.js +2 -0
  15. package/dist/chunk-64P4QHSZ.js.map +1 -0
  16. package/dist/chunk-6PPIFDOQ.js +1742 -0
  17. package/dist/chunk-6PPIFDOQ.js.map +1 -0
  18. package/dist/chunk-ABCHHNG6.js +625 -0
  19. package/dist/chunk-ABCHHNG6.js.map +1 -0
  20. package/dist/chunk-AFRHKA7B.js +2 -0
  21. package/dist/chunk-AFRHKA7B.js.map +1 -0
  22. package/dist/chunk-BFZUG66X.js +45 -0
  23. package/dist/chunk-BFZUG66X.js.map +1 -0
  24. package/dist/chunk-CDNWCYF7.js +2 -0
  25. package/dist/chunk-CDNWCYF7.js.map +1 -0
  26. package/dist/{chunk-6MKAXEE5.js → chunk-EKTPCSN4.js} +2 -2
  27. package/dist/{chunk-6MKAXEE5.js.map → chunk-EKTPCSN4.js.map} +1 -1
  28. package/dist/chunk-EW27SCCC.js +2 -0
  29. package/dist/chunk-EW27SCCC.js.map +1 -0
  30. package/dist/chunk-HCFSHGK4.js +46 -0
  31. package/dist/chunk-HCFSHGK4.js.map +1 -0
  32. package/dist/chunk-HHJGKD5B.js +71 -0
  33. package/dist/chunk-HHJGKD5B.js.map +1 -0
  34. package/dist/chunk-LEIYC3BF.js +104 -0
  35. package/dist/chunk-LEIYC3BF.js.map +1 -0
  36. package/dist/{chunk-HLRVDCNH.js → chunk-MBEQASP3.js} +2 -2
  37. package/dist/chunk-N67JZAXU.js +2 -0
  38. package/dist/chunk-N67JZAXU.js.map +1 -0
  39. package/dist/{chunk-RGUYBH77.js → chunk-SRHLXZRF.js} +2 -2
  40. package/dist/chunk-TT2Q7YMZ.js +118 -0
  41. package/dist/chunk-TT2Q7YMZ.js.map +1 -0
  42. package/dist/{chunk-HI24KAEY.js → chunk-WJXU5F4Z.js} +3 -4
  43. package/dist/{chunk-HI24KAEY.js.map → chunk-WJXU5F4Z.js.map} +1 -1
  44. package/dist/chunk-WZEYII2S.js +6 -0
  45. package/dist/chunk-WZEYII2S.js.map +1 -0
  46. package/dist/chunk-XDJSYQST.js +6 -0
  47. package/dist/chunk-XDJSYQST.js.map +1 -0
  48. package/dist/chunk-YPOELN6Z.js +798 -0
  49. package/dist/chunk-YPOELN6Z.js.map +1 -0
  50. package/dist/{chunk-QZP65I2H.js → chunk-ZE2YFX4K.js} +2 -2
  51. package/dist/cli.js +1 -302
  52. package/dist/cli.js.map +1 -1
  53. package/dist/{compaction-JBZZ7I7Y.js → compaction-X46EQEPS.js} +6 -6
  54. package/dist/compaction-X46EQEPS.js.map +1 -0
  55. package/dist/{config-DCJYECL4.js → config-KCYHMKCT.js} +2 -2
  56. package/dist/config-mutator-QP4GLBOE.js +2 -0
  57. package/dist/context-planner-G2J7FNNU.js +17 -0
  58. package/dist/context-planner-G2J7FNNU.js.map +1 -0
  59. package/dist/editor-chat-R54E65W5.js +137 -0
  60. package/dist/editor-chat-R54E65W5.js.map +1 -0
  61. package/dist/heal-JDXUPRET.js +2 -0
  62. package/dist/inbox-L5ZZ623Y.js +315 -0
  63. package/dist/inbox-L5ZZ623Y.js.map +1 -0
  64. package/dist/index.d.ts +1996 -18
  65. package/dist/index.js +22 -49
  66. package/dist/index.js.map +1 -1
  67. package/dist/ingest-whatsapp-NS4OWDOU.js +6 -0
  68. package/dist/ingest-whatsapp-NS4OWDOU.js.map +1 -0
  69. package/dist/memory-extract-WH4FZ456.js +2 -0
  70. package/dist/processes-XF5CV4LK.js +256 -0
  71. package/dist/processes-XF5CV4LK.js.map +1 -0
  72. package/dist/program-FFWEILAS.js +2 -0
  73. package/dist/providers-AKQ4HTB4.js +2 -0
  74. package/dist/query-PKGYE5HR.js +2 -0
  75. package/dist/registry-IFMDJWQ7.js +2 -0
  76. package/dist/scheduler-63D5KFO7.js +2 -0
  77. package/dist/scheduler-63D5KFO7.js.map +1 -0
  78. package/dist/slack-PSQLVTGB.js +3 -0
  79. package/dist/slack-PSQLVTGB.js.map +1 -0
  80. package/dist/store-5MJOO74U.js +2 -0
  81. package/dist/store-5MJOO74U.js.map +1 -0
  82. package/dist/task-store-NM7VKNLE.js +2 -0
  83. package/dist/task-store-NM7VKNLE.js.map +1 -0
  84. package/dist/telegram-W4SLFMNY.js +3 -0
  85. package/dist/telegram-W4SLFMNY.js.map +1 -0
  86. package/dist/timers-PCB4ZIBD.js +2 -0
  87. package/dist/timers-PCB4ZIBD.js.map +1 -0
  88. package/dist/types-C7IFH42Z.js +2 -0
  89. package/dist/types-C7IFH42Z.js.map +1 -0
  90. package/dist/types-OIFU3KSQ.js +2 -0
  91. package/dist/types-OIFU3KSQ.js.map +1 -0
  92. package/dist/usage-dashboard-AXPXB2KP.js +803 -0
  93. package/dist/usage-dashboard-AXPXB2KP.js.map +1 -0
  94. package/dist/web/workflow-editor.global.js +1427 -0
  95. package/dist/web/workflow-editor.global.js.map +1 -0
  96. package/dist/whatsapp-DCHRBRVV.js +3 -0
  97. package/dist/whatsapp-DCHRBRVV.js.map +1 -0
  98. package/dist/wiki-UDPYFJBL.js +2 -0
  99. package/dist/wiki-UDPYFJBL.js.map +1 -0
  100. package/dist/workspace-setup-C4VB3QZV.js +2 -0
  101. package/dist/workspace-setup-C4VB3QZV.js.map +1 -0
  102. package/package.json +10 -3
  103. package/dist/agent-LRSSVFDR.js +0 -2
  104. package/dist/board-dashboard-DAPHL6W2.js +0 -4508
  105. package/dist/board-dashboard-DAPHL6W2.js.map +0 -1
  106. package/dist/chunk-3XULOWYB.js +0 -199
  107. package/dist/chunk-3XULOWYB.js.map +0 -1
  108. package/dist/chunk-6U2XOQHU.js +0 -7
  109. package/dist/chunk-6U2XOQHU.js.map +0 -1
  110. package/dist/chunk-AU37OREL.js +0 -108
  111. package/dist/chunk-AU37OREL.js.map +0 -1
  112. package/dist/chunk-B4Q4X7D5.js +0 -6
  113. package/dist/chunk-B4Q4X7D5.js.map +0 -1
  114. package/dist/chunk-CXY2RYNI.js +0 -11
  115. package/dist/chunk-CXY2RYNI.js.map +0 -1
  116. package/dist/chunk-IEVEMKAI.js +0 -168
  117. package/dist/chunk-IEVEMKAI.js.map +0 -1
  118. package/dist/chunk-KXZMYLHQ.js +0 -46
  119. package/dist/chunk-KXZMYLHQ.js.map +0 -1
  120. package/dist/chunk-M7HKBG3V.js +0 -2
  121. package/dist/chunk-M7HKBG3V.js.map +0 -1
  122. package/dist/chunk-RB7265LO.js +0 -12
  123. package/dist/chunk-RB7265LO.js.map +0 -1
  124. package/dist/chunk-WVNSWBCU.js +0 -138
  125. package/dist/chunk-WVNSWBCU.js.map +0 -1
  126. package/dist/compaction-JBZZ7I7Y.js.map +0 -1
  127. package/dist/config-mutator-6EJHSP3Y.js +0 -2
  128. package/dist/heal-WKY5I4KB.js +0 -2
  129. package/dist/memory-extract-AD7KMRPC.js +0 -2
  130. package/dist/providers-VUIWO3ZK.js +0 -2
  131. package/dist/registry-5ND7GLFJ.js +0 -2
  132. package/dist/scheduler-FCXOXCN5.js +0 -2
  133. package/dist/usage-dashboard-QX3CF6KK.js +0 -404
  134. package/dist/usage-dashboard-QX3CF6KK.js.map +0 -1
  135. package/dist/workspace-setup-ZWTT42XT.js +0 -2
  136. /package/dist/{agent-LRSSVFDR.js.map → agent-4AOMVXRJ.js.map} +0 -0
  137. /package/dist/{chunk-7MBTMCKY.js.map → chunk-63UYRJIC.js.map} +0 -0
  138. /package/dist/{chunk-HLRVDCNH.js.map → chunk-MBEQASP3.js.map} +0 -0
  139. /package/dist/{chunk-RGUYBH77.js.map → chunk-SRHLXZRF.js.map} +0 -0
  140. /package/dist/{chunk-QZP65I2H.js.map → chunk-ZE2YFX4K.js.map} +0 -0
  141. /package/dist/{config-DCJYECL4.js.map → config-KCYHMKCT.js.map} +0 -0
  142. /package/dist/{config-mutator-6EJHSP3Y.js.map → config-mutator-QP4GLBOE.js.map} +0 -0
  143. /package/dist/{heal-WKY5I4KB.js.map → heal-JDXUPRET.js.map} +0 -0
  144. /package/dist/{memory-extract-AD7KMRPC.js.map → memory-extract-WH4FZ456.js.map} +0 -0
  145. /package/dist/{providers-VUIWO3ZK.js.map → program-FFWEILAS.js.map} +0 -0
  146. /package/dist/{registry-5ND7GLFJ.js.map → providers-AKQ4HTB4.js.map} +0 -0
  147. /package/dist/{scheduler-FCXOXCN5.js.map → query-PKGYE5HR.js.map} +0 -0
  148. /package/dist/{workspace-setup-ZWTT42XT.js.map → registry-IFMDJWQ7.js.map} +0 -0
@@ -0,0 +1,104 @@
1
+ import{e as _}from"./chunk-WZEYII2S.js";import{b as L}from"./chunk-64P4QHSZ.js";import{c as D,d as S}from"./chunk-QOYAX2FT.js";import{readFileSync as y,writeFileSync as b,appendFileSync as j,existsSync as k,mkdirSync as v,readdirSync as A,statSync as R}from"fs";import{resolve as h,join as T,relative as w,dirname as O}from"path";var $=class{baseDir;rawDir;log;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,v(this.rawDir,{recursive:!0}),v(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,s]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(s)}`);return i.push("---","",t.content),b(r,i.join(`
2
+ `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}listEntries(t){if(!k(this.rawDir))return[];let e=A(this.rawDir).filter(i=>i.endsWith(".md")).sort(),r=[];for(let i of e){let n=y(h(this.rawDir,i),"utf-8"),s=this.parseEntry(n,i);s&&(t?.agentId&&s.agentId!==t.agentId||t?.after&&s.date<t.after||t?.before&&s.date>t.before||r.push(s))}return r}parseEntry(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let i=r[1],n=r[2].trim(),s=o=>i.match(new RegExp(`^${o}:\\s*(.+)$`,"m"))?.[1]?.trim()||"";return{id:s("id")||e.replace(".md",""),date:s("date"),agentId:s("agent"),source:s("source"),sourceContext:s("context")||void 0,content:n}}writeArticle(t,e,r,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!L(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=h(this.baseDir,t);n&&this.saveVersion(t,s),v(O(s),{recursive:!0});let o=["---",`title: "${e.title}"`];e.type&&o.push(`type: ${e.type}`),e.related?.length&&o.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),o.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&o.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),o.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&o.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),o.push("---","",r),b(s,o.join(`
3
+ `));let a=n?"update":"create";return this.appendLog(a,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!k(e))return;let r=y(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));v(n,{recursive:!0}),b(h(n,`${i}.md`),r)}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!k(e))return[];try{return A(e).filter(r=>r.endsWith(".md")).sort().reverse().map(r=>({timestamp:r.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,r)}))}catch{return[]}}restoreVersion(t,e){let i=this.getVersions(t).find(n=>n.timestamp.startsWith(e));if(!i)return!1;try{let n=y(i.path,"utf-8"),s=h(this.baseDir,t);return this.saveVersion(t,s),b(s,n),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!k(e))return null;let r=y(e,"utf-8");return this.parseArticle(r,t)}readArticleAs(t,e){let r=this.readArticle(t);return!r||!this.canRead(r.meta,e)?null:r}parseArticle(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let i=r[1],n=r[2].trim(),s=p=>i.match(new RegExp(`^${p}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",o=p=>{let l=i.match(new RegExp(`^${p}:\\s*\\[(.*)\\]$`,"m"));return l?l[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},a=s("type")||s("kind"),g=new Set(["person","project","place","concept","event","decision","pattern"]).has(a)?a:void 0,m=o("tags").filter((p,l,f)=>p&&f.indexOf(p)===l),d=o("related"),u=o("graph_path");return{meta:{title:s("title"),type:g,related:d.length?d:void 0,tags:m,owner:s("owner"),access:s("access")||"public",sharedWith:o("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:o("sources"),graphPath:u.length?u:void 0},content:n,path:e}}listArticles(t){let e=[];return this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let i=w(this.baseDir,r);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);n&&this.canRead(n.meta,t)&&e.push(n)}),e}search(t,e,r=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let u=w(this.baseDir,d);if(u.startsWith("raw/")||u.startsWith("_"))return;let p=this.readArticle(u);!p||!this.canRead(p.meta,e)||n.push(p)}),n.length===0)return[];let s=n.map(d=>d.content),o=h(this.baseDir,"_bm25_cache.json"),a=S(s,o),c=D(t,a),g=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,u)=>{let p=g.get(u)??0;return d.meta.title.toLowerCase().includes(i)&&(p+=10),d.meta.tags?.some(l=>l.toLowerCase().includes(i))&&(p+=5),{article:d,score:p}}).filter(d=>d.score>0).sort((d,u)=>u.score-d.score).slice(0,r).map(d=>d.article)}findRelevant(t,e,r=3,i,n={graph:.6,bm25:.4}){let s=[];if(this.walkDir(this.baseDir,l=>{if(!l.endsWith(".md"))return;let f=w(this.baseDir,l);if(f.startsWith("raw/")||f.startsWith("_"))return;let W=this.readArticle(f);!W||!this.canRead(W.meta,e)||s.push(W)}),s.length===0)return[];let o=s.map(l=>`${l.meta.title} ${(l.meta.tags||[]).join(" ")} ${l.content}`),a=h(this.baseDir,"_bm25_relevance_cache.json"),c=S(o,a),g=D(t,c),m=g.reduce((l,f)=>Math.max(l,f.score),0)||1,d=new Map(g.map(l=>[l.docIndex,l.score/m])),u=!!(i&&i.length>0);return s.map((l,f)=>{let W=d.get(f)??0,E=0;u&&l.meta.graphPath?.length&&(E=_(i,l.meta.graphPath));let I=u?n.graph*E+n.bm25*W:W;return{article:l,score:I}}).filter(l=>l.score>0).sort((l,f)=>f.score-l.score).slice(0,r).map(l=>l.article)}buildContext(t,e=4e3){if(t.length===0)return"";let r=["[Wiki Knowledge]"],i=0;for(let n of t){let s=`
4
+ ## ${n.meta.title} [${(n.meta.tags||[]).slice(0,3).join(", ")}]`,o=n.content.length>600?n.content.slice(0,600)+"...":n.content,a=s+`
5
+ `+o;if(i+a.length>e)break;r.push(a),i+=a.length}return r.push(`
6
+ [End Wiki Knowledge]`),r.join(`
7
+ `)}rebuildIndex(){let t=[],e=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let o=w(this.baseDir,s);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a)return;let c=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let m of c){let d=m.replace(/\[\[|\]\]/g,"");e.set(d,(e.get(d)||0)+1)}let g=[a.meta.title.toLowerCase()];a.meta.tags&&g.push(...a.meta.tags.map(m=>m.toLowerCase())),t.push({path:o,title:a.meta.title,type:a.meta.type,related:a.meta.related,tags:a.meta.tags||[],owner:a.meta.owner,access:a.meta.access,sharedWith:a.meta.sharedWith,aliases:g,backlinks:e.get(a.meta.title)||0,sources:a.meta.sources,lastUpdated:a.meta.lastUpdated})});let r={articles:t,lastRebuilt:new Date().toISOString()};b(h(this.baseDir,"_index.json"),JSON.stringify(r,null,2)),this.writeCatalog(t,r.lastRebuilt);let i=["# Wiki Index","",`Last rebuilt: ${r.lastRebuilt}`,""],n=new Map;for(let s of t){let o=s.access||"public",a=n.get(o)||[];a.push(s),n.set(o,a)}for(let[s,o]of Array.from(n.entries()).sort()){i.push(`## ${s}`,"");for(let a of o.sort((c,g)=>c.title.localeCompare(g.title))){let c=a.type?` [${a.type}]`:"";i.push(`- [${a.title}](${a.path})${c} \u2014 owner: ${a.owner}`)}i.push("")}return b(h(this.baseDir,"WIKI.md"),i.join(`
8
+ `)),this.log(`Index rebuilt: ${t.length} articles`),this.appendLog("rebuild-index",`${t.length} articles indexed`),r}writeCatalog(t,e){let r=["person","project","place","concept","event","decision","pattern","untyped"],i={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},n=new Map;for(let o of t){let a=o.type||"untyped",c=n.get(a)||[];c.push(o),n.set(a,c)}let s=["# Wiki Content Catalog","",`_Last rebuilt: ${e}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let o of r){let a=n.get(o);if(!(!a||a.length===0)){s.push(i[o]||`## ${o}`,"");for(let c of a.sort((g,m)=>g.title.localeCompare(m.title))){let g=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",m=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";s.push(`- [${c.title}](${c.path})${g}${m}`)}s.push("")}}b(h(this.baseDir,"_index.md"),s.join(`
9
+ `))}stats(){let t=0,e={},r={},i={};this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let o=w(this.baseDir,s);if(o.startsWith("raw/")||o.startsWith("_")||o==="WIKI.md")return;let a=this.readArticle(o);if(a){t++;for(let c of a.meta.tags||[])e[c]=(e[c]||0)+1;r[a.meta.access]=(r[a.meta.access]||0)+1,i[a.meta.owner]=(i[a.meta.owner]||0)+1}});let n=k(this.rawDir)?A(this.rawDir).filter(s=>s.endsWith(".md")).length:0;return{totalArticles:t,totalEntries:n,articlesByType:e,articlesByAccess:r,articlesByOwner:i}}appendLog(t,e){let r=h(this.baseDir,"log.md"),n=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${t} | ${e}
10
+
11
+ `;k(r)||b(r,`# Wiki Log
12
+
13
+ Chronological record of all wiki operations.
14
+
15
+ `),j(r,n)}getLog(t=20){let e=h(this.baseDir,"log.md");return k(e)?y(e,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-t).map(n=>n.trim()):[]}ensureSchema(){let t=h(this.baseDir,"_schema.md");if(k(t))return;b(t,`# Wiki Schema
16
+
17
+ A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
18
+ structure emerges from data. The wiki is a compounding artifact.
19
+
20
+ ## Structure
21
+
22
+ \`\`\`
23
+ wiki/
24
+ _schema.md # This file
25
+ worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
26
+ raw/entries/ # Immutable raw sources (conversations, imports, anything)
27
+ [LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
28
+ \`\`\`
29
+
30
+ The LLM decides how to organize articles. You describe YOUR world in worldview.md.
31
+
32
+ ## Article Format
33
+
34
+ \`\`\`yaml
35
+ ---
36
+ title: "Staging Deployment Process"
37
+ tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
38
+ owner: devops-agent
39
+ access: public
40
+ created: 2026-04-06
41
+ last_updated: 2026-04-06
42
+ sources: ["entry-id-1", "entry-id-2"]
43
+ ---
44
+
45
+ Article content with [[wikilinks]] and section tags.
46
+
47
+ ## Deploy Steps
48
+ <!-- tags: process, runbook, staging -->
49
+ Content specific to this section...
50
+ \`\`\`
51
+
52
+ ## Tags
53
+
54
+ Tags are the primary context-narrowing mechanism. The more tags, the better.
55
+
56
+ Tag aggressively:
57
+ - **Who**: people, agents, teams involved
58
+ - **What**: project, client, topic, technology
59
+ - **When**: dates, periods, milestones
60
+ - **Where**: server, environment, channel
61
+ - **How**: process, decision, pattern
62
+ - **Your terms**: whatever vocabulary makes sense in YOUR world
63
+
64
+ Section tags (\`<!-- tags: ... -->\`) let different parts of an article
65
+ match different queries. A deploy article might have sections tagged
66
+ "runbook" and "incident" separately.
67
+
68
+ ## Operations
69
+
70
+ ### Absorb
71
+ Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
72
+ Also identify GAPS: "We mention X but have no article for it."
73
+
74
+ ### Query
75
+ Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
76
+ If agent is working on a specific project, only send content tagged for that project.
77
+
78
+ ### Lint
79
+ Check for: orphan articles, broken [[wikilinks]], untagged articles,
80
+ articles over 100 lines that should split, mentioned-but-missing topics.
81
+
82
+ ## Worldview
83
+
84
+ Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
85
+ mental model. The LLM reads it during absorb to understand where things go.
86
+
87
+ Example worldview.md:
88
+ \`\`\`
89
+ I'm the founder of Acme Corp.
90
+ We build software products.
91
+ Our agents: Marketing Bot, DevOps Bot, Coordinator.
92
+ Clients: ClientA (enterprise), ClientB (startup).
93
+ Infrastructure: local dev machine, cloud server.
94
+ We use GitLab for version control.
95
+ \`\`\`
96
+ `),this.log("Created _schema.md")}extractWikilinks(t){return(t.match(/\[\[([^\]]+)\]\]/g)||[]).map(r=>r.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let t={};return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=w(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_")||r==="WIKI.md"||r==="log.md")return;let i=y(e,"utf-8"),n=this.extractWikilinks(i);for(let s of n)t[s]||(t[s]=[]),t[s].push(r)}),b(h(this.baseDir,"_backlinks.json"),JSON.stringify(t,null,2)),t}getBacklinks(t){let e=h(this.baseDir,"_backlinks.json");if(!k(e))return[];try{return JSON.parse(y(e,"utf-8"))[t]||[]}catch{return[]}}findByTags(t,e,r=10){let i=t.map(s=>s.toLowerCase()),n=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let o=w(this.baseDir,s);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a||e&&!this.canRead(a.meta,e))return;let c=(a.meta.tags||[]).map(u=>u.toLowerCase()),g=(a.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(p=>p.trim().toLowerCase())),m=[...c,...g],d=i.filter(u=>m.includes(u)).length;d>0&&n.push({article:a,score:d})}),n.sort((s,o)=>o.score-s.score).slice(0,r).map(s=>s.article)}getAllTags(){let t=new Map;return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=w(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_"))return;let i=this.readArticle(r);if(i?.meta.tags)for(let n of i.meta.tags)t.set(n,(t.get(n)||0)+1)}),t}getWorldview(){let t=h(this.baseDir,"worldview.md");return k(t)?y(t,"utf-8"):null}setWorldview(t){b(h(this.baseDir,"worldview.md"),t),this.appendLog("worldview","Updated worldview")}lint(){let t=[],e=new Set,r=new Map,i=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let o=w(this.baseDir,s);if(o.startsWith("raw/")||o.startsWith("_")||o==="WIKI.md"||o==="log.md")return;let a=this.readArticle(o);if(!a)return;e.add(a.meta.title),i.set(a.meta.title,o);let c=this.extractWikilinks(a.content);r.set(o,c);let g=a.content.split(`
97
+ `).length;g>100&&t.push({type:"bloated",article:o,message:`${g} lines \u2014 consider splitting`}),a.meta.sources?.length||t.push({type:"unsourced",article:o,message:"No sources listed in frontmatter"}),g<10&&a.content.trim().length<100&&t.push({type:"stub",article:o,message:"Very short article \u2014 needs enrichment"})});for(let[s,o]of r)for(let a of o)e.has(a)||t.push({type:"broken-link",article:s,message:`[[${a}]] \u2014 target article not found`});let n=this.buildBacklinks();for(let[s,o]of i)(!n[s]||n[s].length===0)&&t.push({type:"orphan",article:o,message:`No other articles link to "${s}"`});return this.appendLog("lint",`Found ${t.length} issues`),t}getUnabsorbedEntries(){let t=new Set;return this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let i=w(this.baseDir,r);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);if(n?.meta.sources)for(let s of n.meta.sources)t.add(s)}),this.listEntries().filter(r=>!t.has(r.id))}buildAbsorbPrompt(t=20){let e=this.getUnabsorbedEntries().slice(0,t);if(e.length===0)return null;let r=e.map(i=>`[${i.date} ${i.agentId} via ${i.source}] ${i.content.slice(0,200)}`).join(`
98
+
99
+ `);return`/wiki absorb
100
+
101
+ There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
102
+
103
+ ${r}`}walkDir(t,e){if(k(t))for(let r of A(t)){let i=T(t,r);R(i).isDirectory()?this.walkDir(i,e):e(i)}}};import{resolve as x}from"path";import{existsSync as P,readdirSync as B,mkdirSync as U}from"fs";var M=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=x(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=x(t,"agents"),this.mode=r,this.log=e,U(this.agentsDir,{recursive:!0}),this.sharedStore=new $(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=x(this.agentsDir,t,this.mode),i=new $(r,this.log);return this.agentStores.set(e,i),i}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(P(this.agentsDir))for(let r of B(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let o of s.sources)i.add(o);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{$ as a,M as b};
104
+ //# sourceMappingURL=chunk-LEIYC3BF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/store.ts","../src/wiki/hub.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync } from \"fs\"\nimport { resolve, join, relative, dirname } from \"path\"\nimport { isWikiArticleType } from \"./types\"\nimport type { WikiArticle, WikiArticleMeta, WikiEntry, WikiIndex, WikiAccess } from \"./types\"\nimport { buildIndex, buildIndexCached, scoreAll } from \"../memory/bm25\"\nimport { ancestryScore as ancestryOf } from \"@/graph\"\n\n// --- Wiki Store: filesystem-based knowledge base with permissions ---\n//\n// Structure:\n// .agentx/wiki/\n// _index.md # Master index with aliases\n// _backlinks.json # Reverse link index\n// raw/entries/ # One .md per ingested entry\n// {directories}/ # Articles organized by type\n//\n// Permission model:\n// - private: only owner agent reads/writes\n// - shared: owner writes, listed agents read\n// - public: owner writes, all agents read\n\nexport class WikiStore {\n readonly baseDir: string\n private rawDir: string\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki]\"),\n ) {\n this.baseDir = baseDir\n this.rawDir = resolve(baseDir, \"raw/entries\")\n this.log = log\n\n mkdirSync(this.rawDir, { recursive: true })\n mkdirSync(resolve(baseDir, \"raw\"), { recursive: true })\n\n // Initialize schema if missing\n this.ensureSchema()\n }\n\n // --- Permission checks ---\n\n /**\n * Check if an agent can read an article.\n */\n canRead(article: WikiArticleMeta, agentId?: string): boolean {\n if (article.access === \"public\") return true\n if (!agentId) return false\n if (article.owner === agentId) return true\n if (article.access === \"shared\" && article.sharedWith?.includes(agentId)) return true\n return false\n }\n\n /**\n * Check if an agent can write an article.\n */\n canWrite(article: WikiArticleMeta, agentId: string): boolean {\n return article.owner === agentId\n }\n\n // --- Raw entries (ingestion) ---\n\n /**\n * Add a raw entry (from a conversation, cron result, etc.)\n */\n addEntry(entry: WikiEntry): string {\n const filename = `${entry.date}_${entry.id}.md`\n const filepath = resolve(this.rawDir, filename)\n\n const frontmatter = [\n \"---\",\n `id: ${entry.id}`,\n `date: ${entry.date}`,\n `agent: ${entry.agentId}`,\n `source: ${entry.source}`,\n ]\n if (entry.sourceContext) frontmatter.push(`context: ${entry.sourceContext}`)\n if (entry.meta) {\n for (const [k, v] of Object.entries(entry.meta)) {\n frontmatter.push(`${k}: ${JSON.stringify(v)}`)\n }\n }\n frontmatter.push(\"---\", \"\", entry.content)\n\n writeFileSync(filepath, frontmatter.join(\"\\n\"))\n this.appendLog(\"ingest\", `${entry.id} from ${entry.agentId} via ${entry.source}`)\n return filename\n }\n\n /**\n * List raw entries, optionally filtered by agent or date range.\n */\n listEntries(filter?: { agentId?: string; after?: string; before?: string }): WikiEntry[] {\n if (!existsSync(this.rawDir)) return []\n\n const files = readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).sort()\n const entries: WikiEntry[] = []\n\n for (const file of files) {\n const content = readFileSync(resolve(this.rawDir, file), \"utf-8\")\n const entry = this.parseEntry(content, file)\n if (!entry) continue\n\n if (filter?.agentId && entry.agentId !== filter.agentId) continue\n if (filter?.after && entry.date < filter.after) continue\n if (filter?.before && entry.date > filter.before) continue\n\n entries.push(entry)\n }\n\n return entries\n }\n\n private parseEntry(content: string, filename: string): WikiEntry | null {\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const body = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim() || \"\"\n }\n\n return {\n id: get(\"id\") || filename.replace(\".md\", \"\"),\n date: get(\"date\"),\n agentId: get(\"agent\"),\n source: get(\"source\"),\n sourceContext: get(\"context\") || undefined,\n content: body,\n }\n }\n\n // --- Articles (compiled knowledge) ---\n\n /**\n * Write or update a wiki article.\n */\n writeArticle(\n path: string,\n meta: WikiArticleMeta,\n content: string,\n agentId: string,\n ): boolean {\n // LLM picks the path. We just write the file.\n const existing = this.readArticle(path)\n if (existing && !this.canWrite(existing.meta, agentId)) {\n this.log(`Permission denied: \"${agentId}\" cannot write \"${path}\" (owner: ${existing.meta.owner})`)\n return false\n }\n\n // Drop invalid `type` at write time. The parser already rejects invalid\n // values on read (returns type=undefined), so silently serialising a\n // stray value would cause the round-trip to look fine but the article\n // to render as \"untyped\" in the catalog. Log + drop beats surprise.\n if (meta.type && !isWikiArticleType(meta.type)) {\n this.log(`Dropping invalid article type \"${meta.type}\" for \"${path}\" — enum is [person, project, place, concept, event, decision, pattern]`)\n meta = { ...meta, type: undefined }\n }\n\n const fullPath = resolve(this.baseDir, path)\n\n // Version the previous content before overwriting (immutable history)\n if (existing) {\n this.saveVersion(path, fullPath)\n }\n\n mkdirSync(dirname(fullPath), { recursive: true })\n\n const frontmatter = [\n \"---\",\n `title: \"${meta.title}\"`,\n ]\n if (meta.type) frontmatter.push(`type: ${meta.type}`)\n if (meta.related?.length) {\n frontmatter.push(`related: [${meta.related.map(t => `\"${t}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `tags: [${(meta.tags || []).map(t => `\"${t}\"`).join(\", \")}]`,\n `owner: ${meta.owner}`,\n `access: ${meta.access}`,\n )\n if (meta.sharedWith?.length) {\n frontmatter.push(`shared_with: [${meta.sharedWith.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `created: ${meta.created}`,\n `last_updated: ${meta.lastUpdated}`,\n `sources: [${meta.sources.map(s => `\"${s}\"`).join(\", \")}]`,\n )\n if (meta.graphPath?.length) {\n frontmatter.push(`graph_path: [${meta.graphPath.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\"---\", \"\", content)\n\n writeFileSync(fullPath, frontmatter.join(\"\\n\"))\n const action = existing ? \"update\" : \"create\"\n this.appendLog(action, `${meta.title} [${(meta.tags || []).slice(0, 5).join(\", \")}] by ${agentId} at ${path}`)\n return true\n }\n\n // --- Article Versioning ---\n\n /**\n * Save current article content as an immutable version before overwriting.\n * Versions stored in _versions/{article-path}/{timestamp}.md\n */\n private saveVersion(articlePath: string, fullPath: string): void {\n try {\n if (!existsSync(fullPath)) return\n const content = readFileSync(fullPath, \"utf-8\")\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\")\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n mkdirSync(versionDir, { recursive: true })\n writeFileSync(resolve(versionDir, `${ts}.md`), content)\n } catch {\n // Version save is best-effort\n }\n }\n\n /**\n * List all versions of an article (newest first).\n */\n getVersions(articlePath: string): Array<{ timestamp: string; path: string }> {\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n if (!existsSync(versionDir)) return []\n\n try {\n return readdirSync(versionDir)\n .filter(f => f.endsWith(\".md\"))\n .sort()\n .reverse()\n .map(f => ({\n timestamp: f.replace(/\\.md$/, \"\").replace(/-/g, (m, i) => i < 19 ? (i === 10 ? \"T\" : i === 13 || i === 16 ? \":\" : \"-\") : m),\n path: resolve(versionDir, f),\n }))\n } catch {\n return []\n }\n }\n\n /**\n * Restore a specific version of an article.\n */\n restoreVersion(articlePath: string, versionTimestamp: string): boolean {\n const versions = this.getVersions(articlePath)\n const version = versions.find(v => v.timestamp.startsWith(versionTimestamp))\n if (!version) return false\n\n try {\n const content = readFileSync(version.path, \"utf-8\")\n const fullPath = resolve(this.baseDir, articlePath)\n // Save current as a version too before restoring\n this.saveVersion(articlePath, fullPath)\n writeFileSync(fullPath, content)\n this.appendLog(\"restore\", `${articlePath} restored to ${versionTimestamp}`)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Read an article. Returns null if not found.\n */\n readArticle(path: string): WikiArticle | null {\n const fullPath = resolve(this.baseDir, path)\n if (!existsSync(fullPath)) return null\n\n const raw = readFileSync(fullPath, \"utf-8\")\n return this.parseArticle(raw, path)\n }\n\n /**\n * Read an article with permission check.\n */\n readArticleAs(path: string, agentId: string): WikiArticle | null {\n const article = this.readArticle(path)\n if (!article) return null\n if (!this.canRead(article.meta, agentId)) return null\n return article\n }\n\n private parseArticle(raw: string, path: string): WikiArticle | null {\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const content = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim().replace(/^\"(.*)\"$/, \"$1\") || \"\"\n }\n\n const getArray = (key: string): string[] => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*\\\\[(.*)\\\\]$`, \"m\"))\n if (!m) return []\n return m[1].split(\",\").map(s => s.trim().replace(/^\"(.*)\"$/, \"$1\")).filter(Boolean)\n }\n\n // `type` and `kind` are the new structural spine; no longer stuffed into tags.\n // Legacy articles may have a `kind:` field; we promote it to `type` on read so\n // the migration (Phase 2) can patch it in place.\n const rawType = get(\"type\") || get(\"kind\")\n const validTypes = new Set([\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\",\n ])\n const type = validTypes.has(rawType) ? (rawType as WikiArticleMeta[\"type\"]) : undefined\n\n const tags = getArray(\"tags\").filter((v, i, a) => v && a.indexOf(v) === i)\n const related = getArray(\"related\")\n const graphPath = getArray(\"graph_path\")\n return {\n meta: {\n title: get(\"title\"),\n type,\n related: related.length ? related : undefined,\n tags,\n owner: get(\"owner\"),\n access: (get(\"access\") as WikiAccess) || \"public\",\n sharedWith: getArray(\"shared_with\"),\n created: get(\"created\"),\n lastUpdated: get(\"last_updated\"),\n sources: getArray(\"sources\"),\n graphPath: graphPath.length ? graphPath : undefined,\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n listArticles(agentId: string): WikiArticle[] {\n const articles: WikiArticle[] = []\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article && this.canRead(article.meta, agentId)) {\n articles.push(article)\n }\n })\n return articles\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full)\n }\n }\n }\n}\n","import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\n private log: (...args: unknown[]) => void\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n listAgents(): string[] {\n const agents = new Set<string>()\n\n const entries = this.sharedStore.listEntries()\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n const agentWiki = this.getAgentWiki(agentId)\n const agentEntries = this.getAgentEntries(agentId)\n\n const absorbedIds = new Set<string>()\n const index = agentWiki.rebuildIndex()\n for (const article of index.articles) {\n if (article.sources) {\n for (const s of article.sources) absorbedIds.add(s)\n }\n }\n\n return agentEntries.filter(e => !absorbedIds.has(e.id))\n }\n\n summary(): AgentWikiSummary[] {\n const agents = this.listAgents()\n return agents.map(agentId => {\n const entries = this.getAgentEntries(agentId)\n const wiki = this.getAgentWiki(agentId)\n const index = wiki.rebuildIndex()\n const unabsorbed = this.getUnabsorbedEntries(agentId)\n\n return {\n agentId,\n totalEntries: entries.length,\n totalArticles: index.articles.length,\n unabsorbed: unabsorbed.length,\n articles: index.articles,\n }\n })\n }\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"+HAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,EAAW,eAAAC,EAAa,YAAAC,MAAgB,KAC1G,OAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,WAAAC,MAAe,OAoB1C,IAAMC,EAAN,KAAgB,CACZ,QACD,OACA,IAER,YACEC,EAAkBC,EAAQ,QAAQ,IAAI,EAAG,cAAc,EACvDC,EAAoC,QAAQ,MAAM,KAAK,QAAS,QAAQ,EACxE,CACA,KAAK,QAAUF,EACf,KAAK,OAASC,EAAQD,EAAS,aAAa,EAC5C,KAAK,IAAME,EAEXC,EAAU,KAAK,OAAQ,CAAE,UAAW,EAAK,CAAC,EAC1CA,EAAUF,EAAQD,EAAS,KAAK,EAAG,CAAE,UAAW,EAAK,CAAC,EAGtD,KAAK,aAAa,CACpB,CAOA,QAAQI,EAA0BC,EAA2B,CAC3D,OAAID,E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ACH,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","readdirSync","statSync","resolve","join","relative","dirname","WikiStore","baseDir","resolve","log","mkdirSync","article","agentId","entry","filename","filepath","frontmatter","k","v","writeFileSync","filter","existsSync","files","readdirSync","f","entries","file","content","readFileSync","fmMatch","fm","body","get","key","path","meta","existing","isWikiArticleType","fullPath","dirname","t","s","action","articlePath","ts","versionDir","m","i","versionTimestamp","version","raw","getArray","rawType","type","tags","a","related","graphPath","articles","filePath","relPath","relative","query","maxResults","queryLower","docs","cachePath","index","buildIndexCached","bm25Scores","scoreAll","scoreMap","r","score","b","message","maxArticles","messagePath","weights","maxBm25","bm25Map","hasGraph","bm25","ancestry","ancestryScore","combined","maxChars","lines","totalChars","header","chunk","backlinks","links","link","target","aliases","md","byAccess","bucket","list","x","y","lastRebuilt","typeOrder","typeHeaders","byType","access","totalArticles","byOwner","tag","entryFiles","details","logPath","appendFileSync","limit","e","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync","resolve","existsSync","readdirSync","mkdirSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","agents","entries","e","dir","agentWiki","agentEntries","absorbedIds","index","article","s","unabsorbed"]}
@@ -1,5 +1,5 @@
1
- import{d as m,e as $,i as S}from"./chunk-B4Q4X7D5.js";S();import{readFileSync as x,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=x(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{d as m,e as $,i as S}from"./chunk-XDJSYQST.js";S();import{readFileSync as x,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=x(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{J as a,N as b,j as c,A as d};
5
- //# sourceMappingURL=chunk-HLRVDCNH.js.map
5
+ //# sourceMappingURL=chunk-MBEQASP3.js.map
@@ -0,0 +1,2 @@
1
+ import{e as b}from"./chunk-CDNWCYF7.js";import{existsSync as p,mkdirSync as k,readdirSync as A,readFileSync as m,unlinkSync as v,writeFileSync as T}from"fs";import{resolve as d}from"path";import{randomUUID as w}from"crypto";import{z as s}from"zod";var D=s.enum(["open","claimed","completed","canceled"]),f=s.object({id:s.string(),runId:s.string(),workflowId:s.string(),nodeId:s.string(),title:s.string(),description:s.string().optional(),assignee:s.string(),assignedTo:s.array(s.string()),form:b,status:D,delivered:s.array(s.object({channel:s.string(),handle:s.string(),messageId:s.string().optional(),at:s.string()})).default([]),dueAt:s.string().optional(),submittedBy:s.string().optional(),submittedAt:s.string().optional(),submittedValues:s.record(s.unknown()).optional(),submittedAction:s.enum(["primary","secondary"]).optional(),createdAt:s.string(),updatedAt:s.string()}),y=class{baseDir;archiveDir;constructor(t={}){let e=t.baseDir??d(process.cwd(),".agentx/workflows");this.baseDir=d(e,"_tasks"),this.archiveDir=d(this.baseDir,"_completed"),k(this.baseDir,{recursive:!0}),k(this.archiveDir,{recursive:!0})}pathFor(t){return d(this.baseDir,`${t}.json`)}archivePath(t){return d(this.archiveDir,`${t}.json`)}create(t){let e=new Date().toISOString(),r={id:w(),runId:t.runId,workflowId:t.workflowId,nodeId:t.nodeId,title:t.title,description:t.description,assignee:t.assignee,assignedTo:t.assignedTo,form:t.form,status:"open",delivered:[],dueAt:t.dueAt,createdAt:e,updatedAt:e};return T(this.pathFor(r.id),JSON.stringify(r,null,2)),r}get(t){let e=this.pathFor(t);if(p(e))try{let i=JSON.parse(m(e,"utf-8")),a=f.safeParse(i);return a.success?a.data:null}catch{return null}let r=this.archivePath(t);if(p(r))try{let i=JSON.parse(m(r,"utf-8")),a=f.safeParse(i);return a.success?a.data:null}catch{return null}return null}save(t){let e={...t,updatedAt:new Date().toISOString()},r=e.status==="completed"||e.status==="canceled"?this.archivePath(e.id):this.pathFor(e.id);return T(r,JSON.stringify(e,null,2)),r===this.archivePath(e.id)&&p(this.pathFor(e.id))&&v(this.pathFor(e.id)),e}listOpen(){if(!p(this.baseDir))return[];let t=[];for(let e of A(this.baseDir,{withFileTypes:!0}))if(!(!e.isFile()||!e.name.endsWith(".json")))try{let r=JSON.parse(m(d(this.baseDir,e.name),"utf-8")),i=f.safeParse(r);i.success&&i.data.status==="open"&&t.push(i.data)}catch{}return t.sort((e,r)=>e.createdAt<r.createdAt?1:-1)}listForActor(t){return this.listOpen().filter(e=>e.assignedTo.includes(t))}findByRunNode(t,e){return this.listOpen().find(r=>r.runId===t&&r.nodeId===e)??null}listArchived(){if(!p(this.archiveDir))return[];let t=[];for(let e of A(this.archiveDir,{withFileTypes:!0}))if(!(!e.isFile()||!e.name.endsWith(".json")))try{let r=JSON.parse(m(d(this.archiveDir,e.name),"utf-8")),i=f.safeParse(r);i.success&&t.push(i.data)}catch{}return t.sort((e,r)=>e.createdAt<r.createdAt?1:-1)}};function x(u){let t=u.listOpen(),e=u.listArchived(),r=new Map,i=o=>{let n=r.get(o);return n||(n={open:0,completed:0,durations:[],dueCount:0,breached:0},r.set(o,n)),n};for(let o of t)for(let n of o.assignedTo)i(n).open++;for(let o of e){if(o.status!=="completed"||!o.submittedAt)continue;let n=Date.parse(o.createdAt),l=Date.parse(o.submittedAt);if(Number.isNaN(n)||Number.isNaN(l))continue;let g=Math.max(0,l-n),S=o.submittedBy??o.assignedTo[0]??"unknown",h=i(S);h.completed++,h.durations.push(g),o.dueAt&&(h.dueCount++,l>Date.parse(o.dueAt)&&h.breached++)}let a=Array.from(r.entries()).map(([o,n])=>({actorId:o,openTasks:n.open,completedTasks:n.completed,avgDurationMs:n.durations.length?Math.round(n.durations.reduce((l,g)=>l+g,0)/n.durations.length):null,slaBreachRate:n.dueCount?n.breached/n.dueCount:null,breachedCount:n.breached})).sort((o,n)=>n.completedTasks-o.completedTasks||o.actorId.localeCompare(n.actorId)),c=I(r);return{byActor:a,totals:c,generatedAt:new Date().toISOString()}}function I(u){let t=0,e=0,r=[],i=0,a=0;for(let c of u.values())t+=c.open,e+=c.completed,r.push(...c.durations),i+=c.dueCount,a+=c.breached;return{actorId:"__total__",openTasks:t,completedTasks:e,avgDurationMs:r.length?Math.round(r.reduce((c,o)=>c+o,0)/r.length):null,slaBreachRate:i?a/i:null,breachedCount:a}}export{D as a,f as b,y as c,x as d};
2
+ //# sourceMappingURL=chunk-N67JZAXU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/workflows/task-store.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { randomUUID } from \"crypto\"\nimport { z } from \"zod\"\nimport { formSchemaSchema, type FormSchema } from \"../forms/types\"\n\n// --- UserTask store ---\n//\n// Persists open `userTask` records (the live inbox). One JSON file per task\n// under .agentx/workflows/_tasks/<taskId>.json. When a task is submitted the\n// record is moved to _tasks/_completed/ for historical lookup (keeps the\n// live inbox fast) and the paused run is resumed via the dispatcher.\n//\n// Task state machine:\n// open — freshly created, awaiting any assignee action\n// claimed — a specific assignee has started (optional in v1; reserved)\n// completed — submitted successfully, record archived\n// canceled — workflow canceled or timer-escalated past this task\n\nexport const taskStatusSchema = z.enum([\"open\", \"claimed\", \"completed\", \"canceled\"])\nexport type TaskStatus = z.infer<typeof taskStatusSchema>\n\nexport const userTaskRecordSchema = z.object({\n id: z.string(),\n runId: z.string(),\n workflowId: z.string(),\n nodeId: z.string(),\n title: z.string(),\n description: z.string().optional(),\n /** Assignee ref (\"actor:<id>\" or \"role:<id>\"). */\n assignee: z.string(),\n /** Concrete actors who currently see this task (resolved via role strategy). */\n assignedTo: z.array(z.string()),\n form: formSchemaSchema,\n status: taskStatusSchema,\n /** Channel-delivery tracking. Populated by the userTask handler after it\n * renders the form to the assignee's preferred channel(s). */\n delivered: z.array(z.object({\n channel: z.string(),\n handle: z.string(),\n messageId: z.string().optional(),\n at: z.string(),\n })).default([]),\n /** Optional due date (ISO-8601). Set by dueIn config. */\n dueAt: z.string().optional(),\n /** Set on completion. */\n submittedBy: z.string().optional(),\n submittedAt: z.string().optional(),\n submittedValues: z.record(z.unknown()).optional(),\n submittedAction: z.enum([\"primary\", \"secondary\"]).optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\nexport type UserTaskRecord = z.infer<typeof userTaskRecordSchema>\n\nexport interface TaskStoreOptions {\n baseDir?: string\n}\n\nexport class TaskStore {\n readonly baseDir: string\n readonly archiveDir: string\n\n constructor(opts: TaskStoreOptions = {}) {\n const root = opts.baseDir ?? resolve(process.cwd(), \".agentx/workflows\")\n this.baseDir = resolve(root, \"_tasks\")\n this.archiveDir = resolve(this.baseDir, \"_completed\")\n mkdirSync(this.baseDir, { recursive: true })\n mkdirSync(this.archiveDir, { recursive: true })\n }\n\n private pathFor(id: string): string {\n return resolve(this.baseDir, `${id}.json`)\n }\n\n private archivePath(id: string): string {\n return resolve(this.archiveDir, `${id}.json`)\n }\n\n create(args: {\n runId: string\n workflowId: string\n nodeId: string\n title: string\n description?: string\n assignee: string\n assignedTo: string[]\n form: FormSchema\n dueAt?: string\n }): UserTaskRecord {\n const now = new Date().toISOString()\n const record: UserTaskRecord = {\n id: randomUUID(),\n runId: args.runId,\n workflowId: args.workflowId,\n nodeId: args.nodeId,\n title: args.title,\n description: args.description,\n assignee: args.assignee,\n assignedTo: args.assignedTo,\n form: args.form,\n status: \"open\",\n delivered: [],\n dueAt: args.dueAt,\n createdAt: now,\n updatedAt: now,\n }\n writeFileSync(this.pathFor(record.id), JSON.stringify(record, null, 2))\n return record\n }\n\n get(id: string): UserTaskRecord | null {\n const live = this.pathFor(id)\n if (existsSync(live)) {\n try {\n const raw = JSON.parse(readFileSync(live, \"utf-8\"))\n const parsed = userTaskRecordSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n } catch { return null }\n }\n const archived = this.archivePath(id)\n if (existsSync(archived)) {\n try {\n const raw = JSON.parse(readFileSync(archived, \"utf-8\"))\n const parsed = userTaskRecordSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n } catch { return null }\n }\n return null\n }\n\n save(record: UserTaskRecord): UserTaskRecord {\n const updated = { ...record, updatedAt: new Date().toISOString() }\n const dest = updated.status === \"completed\" || updated.status === \"canceled\"\n ? this.archivePath(updated.id)\n : this.pathFor(updated.id)\n writeFileSync(dest, JSON.stringify(updated, null, 2))\n // If we just moved to archive, clean up the live file.\n if (dest === this.archivePath(updated.id) && existsSync(this.pathFor(updated.id))) {\n unlinkSync(this.pathFor(updated.id))\n }\n return updated\n }\n\n /** Open tasks only — drives the inbox page. */\n listOpen(): UserTaskRecord[] {\n if (!existsSync(this.baseDir)) return []\n const out: UserTaskRecord[] = []\n for (const entry of readdirSync(this.baseDir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue\n try {\n const raw = JSON.parse(readFileSync(resolve(this.baseDir, entry.name), \"utf-8\"))\n const parsed = userTaskRecordSchema.safeParse(raw)\n if (parsed.success && parsed.data.status === \"open\") out.push(parsed.data)\n } catch { /* skip */ }\n }\n return out.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))\n }\n\n /** Open tasks assigned to a specific actor (directly or via role). */\n listForActor(actorId: string): UserTaskRecord[] {\n return this.listOpen().filter((t) => t.assignedTo.includes(actorId))\n }\n\n /** Look up the open task owned by a specific run/node pair. */\n findByRunNode(runId: string, nodeId: string): UserTaskRecord | null {\n return this.listOpen().find((t) => t.runId === runId && t.nodeId === nodeId) ?? null\n }\n\n /** Return every completed/canceled task record in the archive. Used by\n * KPI aggregation. Walks the archive directory once. */\n listArchived(): UserTaskRecord[] {\n if (!existsSync(this.archiveDir)) return []\n const out: UserTaskRecord[] = []\n for (const entry of readdirSync(this.archiveDir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue\n try {\n const raw = JSON.parse(readFileSync(resolve(this.archiveDir, entry.name), \"utf-8\"))\n const parsed = userTaskRecordSchema.safeParse(raw)\n if (parsed.success) out.push(parsed.data)\n } catch { /* skip */ }\n }\n return out.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))\n }\n}\n\n// --- KPI aggregation ---\n//\n// Cheap on-demand stats. For v1 we re-read the fs on every call; cache\n// lands later if/when the dashboard polls aggressively. KPIs compute\n// over open + archived tasks combined (open contribute to pending count;\n// archived contribute to durations + breach rate).\n\nexport interface ActorKpi {\n actorId: string\n openTasks: number\n completedTasks: number\n /** Average milliseconds from createdAt → submittedAt (completed only). */\n avgDurationMs: number | null\n /** Fraction 0..1 of completed tasks submitted after dueAt. Null when\n * no completed tasks had a dueAt to measure against. */\n slaBreachRate: number | null\n /** Count of completed tasks where submittedAt > dueAt. */\n breachedCount: number\n}\n\nexport interface WorkflowKpis {\n byActor: ActorKpi[]\n totals: ActorKpi\n generatedAt: string\n}\n\nexport function computeKpis(store: TaskStore): WorkflowKpis {\n const open = store.listOpen()\n const archived = store.listArchived()\n const byActor = new Map<string, {\n open: number\n completed: number\n durations: number[]\n dueCount: number\n breached: number\n }>()\n\n const bucket = (id: string) => {\n let b = byActor.get(id)\n if (!b) { b = { open: 0, completed: 0, durations: [], dueCount: 0, breached: 0 }; byActor.set(id, b) }\n return b\n }\n\n for (const t of open) {\n for (const actor of t.assignedTo) bucket(actor).open++\n }\n for (const t of archived) {\n if (t.status !== \"completed\" || !t.submittedAt) continue\n const createdMs = Date.parse(t.createdAt)\n const submittedMs = Date.parse(t.submittedAt)\n if (Number.isNaN(createdMs) || Number.isNaN(submittedMs)) continue\n const dur = Math.max(0, submittedMs - createdMs)\n const submitter = t.submittedBy ?? t.assignedTo[0] ?? \"unknown\"\n const b = bucket(submitter)\n b.completed++\n b.durations.push(dur)\n if (t.dueAt) {\n b.dueCount++\n if (submittedMs > Date.parse(t.dueAt)) b.breached++\n }\n }\n\n const perActor: ActorKpi[] = Array.from(byActor.entries()).map(([actorId, b]) => ({\n actorId,\n openTasks: b.open,\n completedTasks: b.completed,\n avgDurationMs: b.durations.length ? Math.round(b.durations.reduce((a, n) => a + n, 0) / b.durations.length) : null,\n slaBreachRate: b.dueCount ? b.breached / b.dueCount : null,\n breachedCount: b.breached,\n })).sort((a, b) => b.completedTasks - a.completedTasks || a.actorId.localeCompare(b.actorId))\n\n const totals = aggregateTotals(byActor)\n return {\n byActor: perActor,\n totals,\n generatedAt: new Date().toISOString(),\n }\n}\n\nfunction aggregateTotals(byActor: Map<string, { open: number; completed: number; durations: number[]; dueCount: number; breached: number }>): ActorKpi {\n let open = 0, completed = 0, durations: number[] = [], dueCount = 0, breached = 0\n for (const b of byActor.values()) {\n open += b.open; completed += b.completed\n durations.push(...b.durations)\n dueCount += b.dueCount; breached += b.breached\n }\n return {\n actorId: \"__total__\",\n openTasks: open,\n completedTasks: completed,\n avgDurationMs: durations.length ? Math.round(durations.reduce((a, n) => a + n, 0) / durations.length) : null,\n slaBreachRate: dueCount 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eC,CACjB,CACF","names":["existsSync","mkdirSync","readdirSync","readFileSync","unlinkSync","writeFileSync","resolve","randomUUID","z","taskStatusSchema","z","userTaskRecordSchema","formSchemaSchema","TaskStore","opts","root","resolve","mkdirSync","id","args","now","record","randomUUID","writeFileSync","live","existsSync","raw","readFileSync","parsed","archived","updated","dest","unlinkSync","out","entry","readdirSync","a","b","actorId","t","runId","nodeId","computeKpis","store","open","byActor","bucket","actor","createdMs","submittedMs","dur","submitter","perActor","n","totals","aggregateTotals","completed","durations","dueCount","breached"]}
@@ -1,7 +1,7 @@
1
- import{a as v,b}from"./chunk-HLRVDCNH.js";import{a as M}from"./chunk-FIOB3MEX.js";import{writeFileSync as R,mkdirSync as m,existsSync as f}from"fs";import{resolve as h}from"path";function $(a,e){if(!e)return a;let s=e*4;return`${a}
1
+ import{a as v,b}from"./chunk-MBEQASP3.js";import{a as M}from"./chunk-FIOB3MEX.js";import{writeFileSync as R,mkdirSync as m,existsSync as f}from"fs";import{resolve as h}from"path";function $(a,e){if(!e)return a;let s=e*4;return`${a}
2
2
 
3
3
  [Response budget]
4
4
  Keep your response under ~${e} tokens (~${s} chars). Be concise \u2014 this is automated batch work, not a conversation.`}function d(a,e,s){let t=[];for(let r of a.split(","))if(r==="*")for(let i=e;i<=s;i++)t.push(i);else if(r.includes("/")){let[i,n]=r.split("/"),o=parseInt(n,10),c=i==="*"?e:parseInt(i,10);for(let l=c;l<=s;l+=o)t.push(l)}else if(r.includes("-")){let[i,n]=r.split("-").map(Number);for(let o=i;o<=n;o++)t.push(o)}else t.push(parseInt(r,10));return[...new Set(t)].sort((r,i)=>r-i)}function w(a,e,s){let t=a.trim().split(/\s+/);if(t.length!==5)throw new Error(`Invalid cron: ${a}`);let r=d(t[0],0,59),i=d(t[1],0,23),n=d(t[2],1,31),o=d(t[3],1,12),c=d(t[4],0,6),l=new Intl.DateTimeFormat("en-US",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),u=new Date(e.getTime()+6e4);u.setSeconds(0,0);let D=new Date(u.getTime()+366*24*60*60*1e3);for(;u<D;){let S=l.formatToParts(u),g=T=>parseInt(S.find(F=>F.type===T)?.value||"0",10),k=g("minute"),x=g("hour"),C=g("day"),A=g("month"),J=u.getDay();if(r.includes(k)&&i.includes(x)&&n.includes(C)&&o.includes(A)&&c.includes(J))return u;u.setTime(u.getTime()+6e4)}throw new Error(`No next run found for cron "${a}" within 1 year`)}var p=5,y=[3e4,6e4,3e5,9e5,36e5],E=class{jobs=new Map;timers=new Map;registry;hooks;runsDir;lastRunFile;running=!1;notifyCallback;log;constructor(e,s,t,r=console.error.bind(console,"[cron]")){this.registry=s,this.hooks=t,this.log=r,this.runsDir=h(process.cwd(),".agentx/cron/runs"),this.lastRunFile=h(process.cwd(),".agentx/cron/last-runs.json");for(let[i,n]of Object.entries(e.crons))this.jobs.set(i,{id:i,enabled:n.enabled,schedule:n.schedule,timezone:n.timezone,agent:n.agent,prompt:n.prompt,timeout:n.timeout,model:n.model,maxOutputTokens:n.maxOutputTokens,onError:n.onError,consecutiveErrors:0,totalRuns:0,totalFailures:0})}setNotifyCallback(e){this.notifyCallback=e}async start(){this.running=!0,f(this.runsDir)||m(this.runsDir,{recursive:!0});let e=this.detectMissedRuns();if(e.length>0){this.log(`Detected ${e.length} missed cron run(s) while daemon was down:`);for(let{jobId:s,missedAt:t}of e)this.log(` "${s}" should have run at ${t.toISOString()}`);this.executeMissedRuns(e).catch(s=>{this.log(`Error executing missed runs: ${s.message}`)})}for(let[s,t]of this.jobs){if(!t.enabled){this.log(`Job "${s}" is disabled, skipping`);continue}this.scheduleNext(s)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(s=>s.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.saveLastRuns()}scheduleNext(e){let s=this.jobs.get(e);if(!s||!s.enabled||!this.running)return;let t=this.timers.get(e);t&&clearTimeout(t);try{let r=w(s.schedule,new Date,s.timezone);s.nextRun=r,s.retryPending=!1;let i=r.getTime()-Date.now();this.log(`Job "${e}" next run: ${r.toISOString()} (in ${Math.round(i/1e3)}s)`);let n=setTimeout(()=>this.executeJob(e),i);this.timers.set(e,n)}catch(r){this.log(`Failed to schedule "${e}": ${r.message}`)}}scheduleRetry(e,s){let t=this.jobs.get(e);if(!t||!t.enabled||!this.running)return;if(s>=p){this.log(`Job "${e}" exhausted all ${p} retries, scheduling next regular run`),this.scheduleNext(e);return}let r=y[s]||y[y.length-1];t.retryPending=!0,this.log(`Job "${e}" retry ${s+1}/${p} in ${Math.round(r/1e3)}s`);let i=setTimeout(()=>this.executeJob(e,s+1),r);this.timers.set(e,i)}async executeJob(e,s=0){let t=this.jobs.get(e);if(!t||!this.running)return;let r=s>0;if(this.hooks?.has("pre:cron-run")){let n=await this.hooks.execute("pre:cron-run",{event:"pre:cron-run",jobId:e,agent:t.agent,prompt:t.prompt});if(n.blocked){this.log(`Job "${e}" blocked by hook: ${n.message}`),this.scheduleNext(e);return}}this.log(`${r?`[retry ${s}] `:""}Executing job "${e}" -> agent "${t.agent}"`);let i=new Date;t.lastRun=i,t.totalRuns++;try{let n=await this.registry.execute({message:$(t.prompt,t.maxOutputTokens),agentId:t.agent,model:t.model,context:{channel:"cron"}}),o={jobId:e,startedAt:i,completedAt:new Date,success:!n.error,response:n.content,error:n.error,duration:n.duration||Date.now()-i.getTime(),isRetry:r,retryAttempt:s};if(n.error){if(t.consecutiveErrors++,t.totalFailures++,t.lastError=n.error,this.log(`Job "${e}" failed (${t.consecutiveErrors} consecutive): ${n.error}`),await this.notifyFailure(t,n.error),t.onError.includes("disable")&&t.consecutiveErrors>=3){t.enabled=!1,this.log(`Job "${e}" disabled after ${t.consecutiveErrors} consecutive errors`);try{let c=await v(l=>b(l,`crons.${e}.enabled`,!1),{reload:!1});c.success||this.log(`Failed to persist disable for "${e}": ${c.error}`)}catch(c){this.log(`Failed to persist disable for "${e}": ${c.message}`)}await this.notifyDisabled(t)}this.logRun(o),this.scheduleRetry(e,s);return}else t.consecutiveErrors>0&&this.log(`Job "${e}" recovered after ${t.consecutiveErrors} failure(s)`),t.consecutiveErrors=0,t.lastSuccess=new Date,t.lastError=void 0,t.retryPending=!1,this.log(`Job "${e}" completed in ${o.duration}ms`);this.logRun(o),this.hooks?.has("post:cron-run")&&await this.hooks.execute("post:cron-run",{event:"post:cron-run",jobId:e,success:o.success,duration:o.duration,error:o.error?new Error(o.error):void 0})}catch(n){t.consecutiveErrors++,t.totalFailures++,t.lastError=n.message,this.log(`Job "${e}" threw: ${n.message}`),await this.notifyFailure(t,n.message),this.scheduleRetry(e,s);return}this.saveLastRuns(),this.scheduleNext(e)}detectMissedRuns(){let e=[],s=this.loadLastRuns();if(!s)return e;for(let[t,r]of this.jobs){if(!r.enabled)continue;let i=s[t];if(!i)continue;let n=new Date(i);try{let o=w(r.schedule,n,r.timezone);o.getTime()<Date.now()&&e.push({jobId:t,missedAt:o})}catch{}}return e}async executeMissedRuns(e){for(let{jobId:s,missedAt:t}of e){let r=this.jobs.get(s);if(!(!r||!r.enabled)){this.log(`Running missed job "${s}" (was due at ${t.toISOString()})`);try{let i=await this.registry.execute({message:$(`[MISSED RUN \u2014 was scheduled for ${t.toISOString()}]
5
5
 
6
6
  ${r.prompt}`,r.maxOutputTokens),agentId:r.agent,context:{channel:"cron"}}),n={jobId:s,startedAt:new Date,completedAt:new Date,success:!i.error,response:i.content,error:i.error,duration:i.duration||0,isRetry:!1};this.logRun(n),i.error?this.log(`Missed job "${s}" failed: ${i.error}`):(this.log(`Missed job "${s}" completed`),r.lastSuccess=new Date),r.lastRun=new Date,r.totalRuns++}catch(i){this.log(`Missed job "${s}" threw: ${i.message}`)}}}this.saveLastRuns()}async notifyFailure(e,s){if(!(!e.onError.includes("notify")&&e.consecutiveErrors<2)){if(!this.notifyCallback){this.log(`[ALERT] Cron "${e.id}" failed (${e.consecutiveErrors}x): ${s.slice(0,200)}`);return}try{await this.notifyCallback(e.id,e.agent,s,e.consecutiveErrors)}catch{}}}async notifyDisabled(e){if(!this.notifyCallback){this.log(`[ALERT] Cron "${e.id}" has been DISABLED after ${e.consecutiveErrors} consecutive failures`);return}try{await this.notifyCallback(e.id,e.agent,`AUTO-DISABLED after ${e.consecutiveErrors} consecutive failures. Last error: ${e.lastError||"unknown"}`,e.consecutiveErrors)}catch{}}saveLastRuns(){try{let e={};for(let[t,r]of this.jobs)r.lastRun&&(e[t]=r.lastRun.toISOString());let s=h(process.cwd(),".agentx/cron");f(s)||m(s,{recursive:!0}),R(this.lastRunFile,JSON.stringify(e,null,2))}catch{}}loadLastRuns(){try{if(!f(this.lastRunFile))return null;let{readFileSync:e}=M("fs");return JSON.parse(e(this.lastRunFile,"utf-8"))}catch{return null}}logRun(e){try{let s=h(this.runsDir,e.jobId);f(s)||m(s,{recursive:!0});let t=`${e.startedAt.toISOString().replace(/[:.]/g,"-")}.json`;R(h(s,t),JSON.stringify(e,null,2))}catch{}}list(){return Array.from(this.jobs.values())}health(){let e=Array.from(this.jobs.values()),s=this.detectMissedRuns();return{healthy:e.filter(t=>t.enabled&&t.consecutiveErrors===0).length,failing:e.filter(t=>t.enabled&&t.consecutiveErrors>0).length,disabled:e.filter(t=>!t.enabled).length,missed:s.length,jobs:e.map(t=>({id:t.id,status:t.enabled?t.retryPending?"retrying":t.consecutiveErrors>0?"failing":"healthy":"disabled",consecutiveErrors:t.consecutiveErrors,lastError:t.lastError}))}}};export{w as a,E as b};
7
- //# sourceMappingURL=chunk-RGUYBH77.js.map
7
+ //# sourceMappingURL=chunk-SRHLXZRF.js.map