agentix-cli 0.136.0 → 0.137.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 (136) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +11 -1
  2. package/apps/mac-voice/Sources/AgentXVoice/Character.swift +18 -5
  3. package/apps/mac-voice/Sources/AgentXVoice/Floor.swift +46 -0
  4. package/apps/mac-voice/Sources/AgentXVoice/FloorWatcher.swift +78 -0
  5. package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +12 -1
  6. package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +8 -0
  7. package/apps/mac-voice/Sources/AgentXVoice/main.swift +89 -10
  8. package/dist/{App-D6W6IV2L.js → App-MCYZBCMQ.js} +2 -2
  9. package/dist/{ChatApp-X7TNCFGW.js → ChatApp-7YXDEW3H.js} +2 -2
  10. package/dist/{absorb-eval-COPVH2M2.js → absorb-eval-L72I7PKM.js} +2 -2
  11. package/dist/{agent-VCGAUBER.js → agent-TPREVZGH.js} +2 -2
  12. package/dist/{board-dashboard-JZM3FQNV.js → board-dashboard-3VBZAKYM.js} +4 -4
  13. package/dist/{board-dashboard-JZM3FQNV.js.map → board-dashboard-3VBZAKYM.js.map} +1 -1
  14. package/dist/{chunk-ZPJVDX2U.js → chunk-264762O7.js} +2 -2
  15. package/dist/{chunk-C43E3YFT.js → chunk-44N5HXYE.js} +2 -2
  16. package/dist/{chunk-EVTTAM7S.js → chunk-5CEBOUBG.js} +2 -2
  17. package/dist/{chunk-HZZW35FY.js → chunk-5EIO6S3S.js} +2 -2
  18. package/dist/{chunk-QTDKNJXD.js → chunk-64ZACYOF.js} +245 -245
  19. package/dist/chunk-64ZACYOF.js.map +1 -0
  20. package/dist/chunk-6BWVJ7UJ.js +54 -0
  21. package/dist/chunk-6BWVJ7UJ.js.map +1 -0
  22. package/dist/{chunk-5X37CXJF.js → chunk-APIANBXV.js} +2 -2
  23. package/dist/{chunk-5J5USW2O.js → chunk-AYYEY5UJ.js} +2 -2
  24. package/dist/{chunk-WRJFKA43.js → chunk-DX6RYYGP.js} +2 -2
  25. package/dist/{chunk-FQLSV2C4.js → chunk-EFUPLTQ3.js} +2 -2
  26. package/dist/{chunk-HEJTE7OC.js → chunk-ETOOT5KD.js} +2 -2
  27. package/dist/{chunk-PV623BLN.js → chunk-GW4LKNQT.js} +3 -3
  28. package/dist/{chunk-OW5EXDVY.js → chunk-HSX5LMXD.js} +2 -2
  29. package/dist/{chunk-KZXQD6ZK.js → chunk-I5QKJH7V.js} +2 -2
  30. package/dist/{chunk-M5B4QG6J.js → chunk-JXIMGK7Z.js} +2 -2
  31. package/dist/chunk-KEJGWFGS.js +105 -0
  32. package/dist/chunk-KEJGWFGS.js.map +1 -0
  33. package/dist/{chunk-66DPMVUC.js → chunk-KOKPK3OL.js} +2 -2
  34. package/dist/{chunk-K75LFQE3.js → chunk-LGM22AOB.js} +2 -2
  35. package/dist/{chunk-VA24JS2S.js → chunk-OLZL32KG.js} +2 -2
  36. package/dist/{chunk-H2N7DOPT.js → chunk-P6PTY2NP.js} +2 -2
  37. package/dist/{chunk-H2N7DOPT.js.map → chunk-P6PTY2NP.js.map} +1 -1
  38. package/dist/{chunk-M5AHI2PZ.js → chunk-PLCK4ZAG.js} +2 -2
  39. package/dist/{chunk-QCUJTAAZ.js → chunk-PYR7GKK7.js} +5 -5
  40. package/dist/{chunk-QCUJTAAZ.js.map → chunk-PYR7GKK7.js.map} +1 -1
  41. package/dist/{chunk-GL3H7XMI.js → chunk-QKILE72V.js} +2 -2
  42. package/dist/{chunk-AK3XOA5N.js → chunk-QQ67J76O.js} +2 -2
  43. package/dist/{chunk-IPMXIPTS.js → chunk-RX2ISTNT.js} +2 -2
  44. package/dist/{chunk-HH7OFAEM.js → chunk-ZX2NJGIU.js} +2 -2
  45. package/dist/{chunk-HH7OFAEM.js.map → chunk-ZX2NJGIU.js.map} +1 -1
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-SMOWSRJY.js → client-G2QA4TCG.js} +2 -2
  48. package/dist/{config-OGUDWYAA.js → config-OD5W6IQE.js} +2 -2
  49. package/dist/{config-mutate-BH27TMWK.js → config-mutate-JEXLMR2L.js} +2 -2
  50. package/dist/config-mutator-4FKROX3O.js +2 -0
  51. package/dist/{contributions-H6T65TCY.js → contributions-UXLHUMF2.js} +2 -2
  52. package/dist/{doctor-ZOXHT7ZQ.js → doctor-DO2WN4TS.js} +2 -2
  53. package/dist/{follow-up-tool-GUBBXNEZ.js → follow-up-tool-QPNJD3HR.js} +2 -2
  54. package/dist/{hub-IIW2GBO5.js → hub-RFE766AM.js} +2 -2
  55. package/dist/index.d.ts +69 -36
  56. package/dist/index.js +1 -1
  57. package/dist/{program-WROQ55F5.js → program-QENG5KI7.js} +208 -208
  58. package/dist/program-QENG5KI7.js.map +1 -0
  59. package/dist/{promote-HDLU44MX.js → promote-FJ3EK2J6.js} +2 -2
  60. package/dist/{query-6G27CBZQ.js → query-KYA6YYUU.js} +2 -2
  61. package/dist/{query-settings-G4M75LVQ.js → query-settings-P3UOGMAQ.js} +2 -2
  62. package/dist/{registry-3RE5SG22.js → registry-U4S4XXUZ.js} +2 -2
  63. package/dist/{request-planner-T3VCZVVQ.js → request-planner-SYVDD4PZ.js} +2 -2
  64. package/dist/{review-candidates-C3O3CENL.js → review-candidates-QUIX4AK7.js} +2 -2
  65. package/dist/{routing-LD35TJM5.js → routing-MDZOHYYH.js} +2 -2
  66. package/dist/rules-UVUJTVOE.js +24 -0
  67. package/dist/rules-UVUJTVOE.js.map +1 -0
  68. package/dist/schedule-tool-DKBPBQ3F.js +2 -0
  69. package/dist/{scheduler-I3QB4GI3.js → scheduler-76IIRAP7.js} +2 -2
  70. package/dist/{seat-4Y3EW3KU.js → seat-TV5SK2E7.js} +2 -2
  71. package/dist/{select-LZKN3FER.js → select-HKRDVQNW.js} +2 -2
  72. package/dist/{set-enabled-WSTOHJDE.js → set-enabled-I2V3PXOA.js} +2 -2
  73. package/dist/{tool-AKXO2EJU.js → tool-5ZFM6NSO.js} +2 -2
  74. package/dist/{tool-NLMIUOHR.js → tool-J7PYS4NF.js} +2 -2
  75. package/dist/{wiki-ZS6OHOWQ.js → wiki-3VG33ZZB.js} +2 -2
  76. package/dist/wiki-enrich-2FNORKEQ.js +2 -0
  77. package/package.json +1 -1
  78. package/dist/chunk-54OORW5I.js +0 -54
  79. package/dist/chunk-54OORW5I.js.map +0 -1
  80. package/dist/chunk-OISCRNMW.js +0 -105
  81. package/dist/chunk-OISCRNMW.js.map +0 -1
  82. package/dist/chunk-QTDKNJXD.js.map +0 -1
  83. package/dist/config-mutator-Q62AS2TR.js +0 -2
  84. package/dist/program-WROQ55F5.js.map +0 -1
  85. package/dist/rules-HUUFXQD6.js +0 -24
  86. package/dist/rules-HUUFXQD6.js.map +0 -1
  87. package/dist/schedule-tool-46TVGEYU.js +0 -2
  88. package/dist/wiki-enrich-NGPFWTVA.js +0 -2
  89. /package/dist/{App-D6W6IV2L.js.map → App-MCYZBCMQ.js.map} +0 -0
  90. /package/dist/{ChatApp-X7TNCFGW.js.map → ChatApp-7YXDEW3H.js.map} +0 -0
  91. /package/dist/{absorb-eval-COPVH2M2.js.map → absorb-eval-L72I7PKM.js.map} +0 -0
  92. /package/dist/{agent-VCGAUBER.js.map → agent-TPREVZGH.js.map} +0 -0
  93. /package/dist/{chunk-ZPJVDX2U.js.map → chunk-264762O7.js.map} +0 -0
  94. /package/dist/{chunk-C43E3YFT.js.map → chunk-44N5HXYE.js.map} +0 -0
  95. /package/dist/{chunk-EVTTAM7S.js.map → chunk-5CEBOUBG.js.map} +0 -0
  96. /package/dist/{chunk-HZZW35FY.js.map → chunk-5EIO6S3S.js.map} +0 -0
  97. /package/dist/{chunk-5X37CXJF.js.map → chunk-APIANBXV.js.map} +0 -0
  98. /package/dist/{chunk-5J5USW2O.js.map → chunk-AYYEY5UJ.js.map} +0 -0
  99. /package/dist/{chunk-WRJFKA43.js.map → chunk-DX6RYYGP.js.map} +0 -0
  100. /package/dist/{chunk-FQLSV2C4.js.map → chunk-EFUPLTQ3.js.map} +0 -0
  101. /package/dist/{chunk-HEJTE7OC.js.map → chunk-ETOOT5KD.js.map} +0 -0
  102. /package/dist/{chunk-PV623BLN.js.map → chunk-GW4LKNQT.js.map} +0 -0
  103. /package/dist/{chunk-OW5EXDVY.js.map → chunk-HSX5LMXD.js.map} +0 -0
  104. /package/dist/{chunk-KZXQD6ZK.js.map → chunk-I5QKJH7V.js.map} +0 -0
  105. /package/dist/{chunk-M5B4QG6J.js.map → chunk-JXIMGK7Z.js.map} +0 -0
  106. /package/dist/{chunk-66DPMVUC.js.map → chunk-KOKPK3OL.js.map} +0 -0
  107. /package/dist/{chunk-K75LFQE3.js.map → chunk-LGM22AOB.js.map} +0 -0
  108. /package/dist/{chunk-VA24JS2S.js.map → chunk-OLZL32KG.js.map} +0 -0
  109. /package/dist/{chunk-M5AHI2PZ.js.map → chunk-PLCK4ZAG.js.map} +0 -0
  110. /package/dist/{chunk-GL3H7XMI.js.map → chunk-QKILE72V.js.map} +0 -0
  111. /package/dist/{chunk-AK3XOA5N.js.map → chunk-QQ67J76O.js.map} +0 -0
  112. /package/dist/{chunk-IPMXIPTS.js.map → chunk-RX2ISTNT.js.map} +0 -0
  113. /package/dist/{client-SMOWSRJY.js.map → client-G2QA4TCG.js.map} +0 -0
  114. /package/dist/{config-OGUDWYAA.js.map → config-OD5W6IQE.js.map} +0 -0
  115. /package/dist/{config-mutate-BH27TMWK.js.map → config-mutate-JEXLMR2L.js.map} +0 -0
  116. /package/dist/{config-mutator-Q62AS2TR.js.map → config-mutator-4FKROX3O.js.map} +0 -0
  117. /package/dist/{contributions-H6T65TCY.js.map → contributions-UXLHUMF2.js.map} +0 -0
  118. /package/dist/{doctor-ZOXHT7ZQ.js.map → doctor-DO2WN4TS.js.map} +0 -0
  119. /package/dist/{follow-up-tool-GUBBXNEZ.js.map → follow-up-tool-QPNJD3HR.js.map} +0 -0
  120. /package/dist/{hub-IIW2GBO5.js.map → hub-RFE766AM.js.map} +0 -0
  121. /package/dist/{promote-HDLU44MX.js.map → promote-FJ3EK2J6.js.map} +0 -0
  122. /package/dist/{query-6G27CBZQ.js.map → query-KYA6YYUU.js.map} +0 -0
  123. /package/dist/{query-settings-G4M75LVQ.js.map → query-settings-P3UOGMAQ.js.map} +0 -0
  124. /package/dist/{registry-3RE5SG22.js.map → registry-U4S4XXUZ.js.map} +0 -0
  125. /package/dist/{request-planner-T3VCZVVQ.js.map → request-planner-SYVDD4PZ.js.map} +0 -0
  126. /package/dist/{review-candidates-C3O3CENL.js.map → review-candidates-QUIX4AK7.js.map} +0 -0
  127. /package/dist/{routing-LD35TJM5.js.map → routing-MDZOHYYH.js.map} +0 -0
  128. /package/dist/{schedule-tool-46TVGEYU.js.map → schedule-tool-DKBPBQ3F.js.map} +0 -0
  129. /package/dist/{scheduler-I3QB4GI3.js.map → scheduler-76IIRAP7.js.map} +0 -0
  130. /package/dist/{seat-4Y3EW3KU.js.map → seat-TV5SK2E7.js.map} +0 -0
  131. /package/dist/{select-LZKN3FER.js.map → select-HKRDVQNW.js.map} +0 -0
  132. /package/dist/{set-enabled-WSTOHJDE.js.map → set-enabled-I2V3PXOA.js.map} +0 -0
  133. /package/dist/{tool-AKXO2EJU.js.map → tool-5ZFM6NSO.js.map} +0 -0
  134. /package/dist/{tool-NLMIUOHR.js.map → tool-J7PYS4NF.js.map} +0 -0
  135. /package/dist/{wiki-ZS6OHOWQ.js.map → wiki-3VG33ZZB.js.map} +0 -0
  136. /package/dist/{wiki-enrich-NGPFWTVA.js.map → wiki-enrich-2FNORKEQ.js.map} +0 -0
@@ -1,105 +0,0 @@
1
- import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-OW5EXDVY.js";import{y as C,z as K}from"./chunk-66DPMVUC.js";import{c as x,d as L}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as _,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=n=>{let a=/^(.*Z)(?:-(\d+))?\.md$/.exec(n);return a?[a[1],a[2]?Number(a[2]):0]:[n,0]},[s,o]=e(A),[i,r]=e(t);return s<i?-1:s>i?1:o-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;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,_(this.rawDir,{recursive:!0}),_(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`,s=h(this.rawDir,e),o=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&o.push(`context: ${t.sourceContext}`),t.meta)for(let[i,r]of Object.entries(t.meta))o.push(`${i}: ${JSON.stringify(r)}`);return o.push("---","",t.content),b(s,o.join(`
2
- `)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let o of D(this.rawDir)){let i=o.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(i))continue;let r=this.parseEntry($(h(this.rawDir,o),"utf-8"),o);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(o=>o.endsWith(".md")).sort(),s=[];for(let o of e){let i=$(h(this.rawDir,o),"utf-8"),r=this.parseEntry(i,o);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let o=s[1],i=s[2].trim(),r=c=>o.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",n=new Set(["id","date","agent","source","context"]),a={};for(let c of o.split(`
3
- `)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||n.has(l[1])))try{a[l[1]]=JSON.parse(l[2])}catch{a[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:i,meta:Object.keys(a).length>0?a:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,o){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,o))}catch(i){if(!(i instanceof P))throw i;return this.log(i.message),!1}}writeArticleLocked(t,e,s,o){let i=this.readArticle(t);if(i&&!this.canWrite(i.meta,o))return this.log(`Permission denied: "${o}" cannot write "${t}" (owner: ${i.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);i&&this.saveVersion(t,r),_(z(r),{recursive:!0});let n=["---",`title: "${e.title}"`];e.type&&n.push(`type: ${e.type}`),e.related?.length&&n.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),n.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&n.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),n.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&n.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&n.push(`class: ${e.class}`),e.importance&&n.push(`importance: ${e.importance}`),e.importanceProposed&&n.push(`importance_proposed: ${e.importanceProposed}`),e.date&&n.push(`date: ${e.date}`),e.rolledUpInto&&n.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&n.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&n.push(`statements: ${JSON.stringify(e.statements)}`),n.push("---","",s),b(r,n.join(`
4
- `));let a=i?"update":"create";return this.appendLog(a,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${o} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),o=new Date().toISOString().replace(/[:.]/g,"-"),i=h(this.baseDir,"_versions",t.replace(/\.md$/,""));_(i,{recursive:!0});for(let r=0;;r++)try{b(h(i,`${r?`${o}-${r}`:o}.md`),s,{flag:"wx"});return}catch(n){if(n.code!=="EEXIST")throw n}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(o,i)=>i<19?i===10?"T":i===13||i===16?":":"-":o),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),o=s.find(i=>i.timestamp===e)??s.find(i=>i.timestamp.startsWith(e));if(!o)return!1;try{let i=$(o.path,"utf-8"),r=h(this.baseDir,t);return this.saveVersion(t,r),b(r,i),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let o=s[1],i=s[2].trim(),r=W=>o.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",n=W=>{let v=o.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},a=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(a)?a:void 0,g=n("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=n("related"),p=n("graph_path"),m=n("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:n("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:n("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:i,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(a,c)=>{if(!a.endsWith(".md"))return;let l=k(this.baseDir,a);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let o=s.join("|"),i=t??"\0all",r=this.listCache.get(i);if(r&&r.signature===o)return r.articles.slice();let n=[];for(let a of e){let c=this.readArticle(a);c&&(t===null||this.canRead(c.meta,t))&&n.push(c)}return this.listCache.set(i,{signature:o,articles:n}),n.slice()}search(t,e,s=10){let o=t.toLowerCase(),i=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||i.push(m)}),i.length===0)return[];let r=i.map(d=>d.content),n=h(this.baseDir,"_bm25_cache.json"),a=L(r,n),c=x(t,a),l=new Map(c.map(d=>[d.docIndex,d.score]));return i.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(o)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(o))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,o={}){let i=Math.max(s,o.shortlist??E),r=this.findRelevant(t,e,i);if(r.length<2)return r.slice(0,s);let n=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),a=await C(M,R({query:t,candidates:n,excerptChars:o.excerptChars}),T(n),{incumbent:{best:n[0].id},features:{agent:e??"unknown"}});return!a||a.mode!=="active"?r.slice(0,s):j(a.answers,n).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,o,i={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let n=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),a=h(this.baseDir,"_bm25_relevance_cache.json"),c=L(n,a),l=x(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(o&&o.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(o,u.meta.graphPath));let v=p?i.graph*W+i.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],o=0;for(let i of t){let r=`
5
- ## ${i.meta.title} [${(i.meta.tags||[]).slice(0,3).join(", ")}]`,n=i.content.length>600?i.content.slice(0,600)+"...":i.content,a=r+`
6
- `+n;if(o+a.length>e)break;s.push(a),o+=a.length}return s.push(`
7
- [End Wiki Knowledge]`),s.join(`
8
- `)}rebuildIndex(){let t=[],e=new Map;this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let n=k(this.baseDir,r);if(n.startsWith("raw/")||n.startsWith("_"))return;let a=this.readArticle(n);if(!a)return;let c=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let g of c){let d=g.replace(/\[\[|\]\]/g,"");e.set(d,(e.get(d)||0)+1)}let l=[a.meta.title.toLowerCase()];a.meta.tags&&l.push(...a.meta.tags.map(g=>g.toLowerCase())),t.push({path:n,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:l,backlinks:e.get(a.meta.title)||0,sources:a.meta.sources,lastUpdated:a.meta.lastUpdated,graphPath:a.meta.graphPath})});let s={articles:t,lastRebuilt:new Date().toISOString()};b(h(this.baseDir,"_index.json"),JSON.stringify(s,null,2)),this.writeCatalog(t,s.lastRebuilt);let o=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],i=new Map;for(let r of t){let n=r.access||"public",a=i.get(n)||[];a.push(r),i.set(n,a)}for(let[r,n]of Array.from(i.entries()).sort()){o.push(`## ${r}`,"");for(let a of n.sort((c,l)=>c.title.localeCompare(l.title))){let c=a.type?` [${a.type}]`:"";o.push(`- [${a.title}](${a.path})${c} \u2014 owner: ${a.owner}`)}o.push("")}return b(h(this.baseDir,"WIKI.md"),o.join(`
9
- `)),this.log(`Index rebuilt: ${t.length} articles`),this.appendLog("rebuild-index",`${t.length} articles indexed`),s}writeCatalog(t,e){let s=["person","project","place","concept","event","decision","pattern","untyped"],o={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},i=new Map;for(let n of t){let a=n.type||"untyped",c=i.get(a)||[];c.push(n),i.set(a,c)}let r=["# Wiki Content Catalog","",`_Last rebuilt: ${e}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let n of s){let a=i.get(n);if(!(!a||a.length===0)){r.push(o[n]||`## ${n}`,"");for(let c of a.sort((l,g)=>l.title.localeCompare(g.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",g=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";r.push(`- [${c.title}](${c.path})${l}${g}`)}r.push("")}}b(h(this.baseDir,"_index.md"),r.join(`
10
- `))}stats(){let t=0,e={},s={},o={};this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let n=k(this.baseDir,r);if(n.startsWith("raw/")||n.startsWith("_")||n==="WIKI.md")return;let a=this.readArticle(n);if(a){t++;for(let c of a.meta.tags||[])e[c]=(e[c]||0)+1;s[a.meta.access]=(s[a.meta.access]||0)+1,o[a.meta.owner]=(o[a.meta.owner]||0)+1}});let i=w(this.rawDir)?D(this.rawDir).filter(r=>r.endsWith(".md")).length:0;return{totalArticles:t,totalEntries:i,articlesByType:e,articlesByAccess:s,articlesByOwner:o}}appendLog(t,e){let s=h(this.baseDir,"log.md"),i=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${t} | ${e}
11
-
12
- `;w(s)||b(s,`# Wiki Log
13
-
14
- Chronological record of all wiki operations.
15
-
16
- `),V(s,i)}getLog(t=20){let e=h(this.baseDir,"log.md");return w(e)?$(e,"utf-8").split(/^## /m).filter(i=>i.startsWith("[")).slice(-t).map(i=>i.trim()):[]}ensureSchema(){let t=h(this.baseDir,"_schema.md");if(w(t))return;b(t,`# Wiki Schema
17
-
18
- A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
19
- structure emerges from data. The wiki is a compounding artifact.
20
-
21
- ## Structure
22
-
23
- \`\`\`
24
- wiki/
25
- _schema.md # This file
26
- worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
27
- raw/entries/ # Immutable raw sources (conversations, imports, anything)
28
- [LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
29
- \`\`\`
30
-
31
- The LLM decides how to organize articles. You describe YOUR world in worldview.md.
32
-
33
- ## Article Format
34
-
35
- \`\`\`yaml
36
- ---
37
- title: "Staging Deployment Process"
38
- tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
39
- owner: devops-agent
40
- access: public
41
- created: 2026-04-06
42
- last_updated: 2026-04-06
43
- sources: ["entry-id-1", "entry-id-2"]
44
- ---
45
-
46
- Article content with [[wikilinks]] and section tags.
47
-
48
- ## Deploy Steps
49
- <!-- tags: process, runbook, staging -->
50
- Content specific to this section...
51
- \`\`\`
52
-
53
- ## Tags
54
-
55
- Tags are the primary context-narrowing mechanism. The more tags, the better.
56
-
57
- Tag aggressively:
58
- - **Who**: people, agents, teams involved
59
- - **What**: project, client, topic, technology
60
- - **When**: dates, periods, milestones
61
- - **Where**: server, environment, channel
62
- - **How**: process, decision, pattern
63
- - **Your terms**: whatever vocabulary makes sense in YOUR world
64
-
65
- Section tags (\`<!-- tags: ... -->\`) let different parts of an article
66
- match different queries. A deploy article might have sections tagged
67
- "runbook" and "incident" separately.
68
-
69
- ## Operations
70
-
71
- ### Absorb
72
- Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
73
- Also identify GAPS: "We mention X but have no article for it."
74
-
75
- ### Query
76
- Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
77
- If agent is working on a specific project, only send content tagged for that project.
78
-
79
- ### Lint
80
- Check for: orphan articles, broken [[wikilinks]], untagged articles,
81
- articles over 100 lines that should split, mentioned-but-missing topics.
82
-
83
- ## Worldview
84
-
85
- Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
86
- mental model. The LLM reads it during absorb to understand where things go.
87
-
88
- Example worldview.md:
89
- \`\`\`
90
- I'm the founder of Acme Corp.
91
- We build software products.
92
- Our agents: Marketing Bot, DevOps Bot, Coordinator.
93
- Clients: ClientA (enterprise), ClientB (startup).
94
- Infrastructure: local dev machine, cloud server.
95
- We use GitLab for version control.
96
- \`\`\`
97
- `),this.log("Created _schema.md")}extractWikilinks(t){return(t.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let t={};return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let s=k(this.baseDir,e);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let o=$(e,"utf-8"),i=this.extractWikilinks(o);for(let r of i)t[r]||(t[r]=[]),t[r].push(s)}),b(h(this.baseDir,"_backlinks.json"),JSON.stringify(t,null,2)),t}getBacklinks(t){let e=h(this.baseDir,"_backlinks.json");if(!w(e))return[];try{return JSON.parse($(e,"utf-8"))[t]||[]}catch{return[]}}findByTags(t,e,s=10){let o=t.map(r=>r.toLowerCase()),i=[];return this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let n=k(this.baseDir,r);if(n.startsWith("raw/")||n.startsWith("_"))return;let a=this.readArticle(n);if(!a||e&&!this.canRead(a.meta,e))return;let c=(a.meta.tags||[]).map(p=>p.toLowerCase()),l=(a.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(p=>p.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(m=>m.trim().toLowerCase())),g=[...c,...l],d=o.filter(p=>g.includes(p)).length;d>0&&i.push({article:a,score:d})}),i.sort((r,n)=>n.score-r.score).slice(0,s).map(r=>r.article)}getAllTags(){let t=new Map;return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let s=k(this.baseDir,e);if(s.startsWith("raw/")||s.startsWith("_"))return;let o=this.readArticle(s);if(o?.meta.tags)for(let i of o.meta.tags)t.set(i,(t.get(i)||0)+1)}),t}getWorldview(){let t=h(this.baseDir,"worldview.md");return w(t)?$(t,"utf-8"):null}setWorldview(t){b(h(this.baseDir,"worldview.md"),t),this.appendLog("worldview","Updated worldview")}lint(){let t=[],e=new Set,s=new Map,o=new Map;this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let n=k(this.baseDir,r);if(n.startsWith("raw/")||n.startsWith("_")||n==="WIKI.md"||n==="log.md")return;let a=this.readArticle(n);if(!a)return;e.add(a.meta.title),o.set(a.meta.title,n);let c=this.extractWikilinks(a.content);s.set(n,c);let l=a.content.split(`
98
- `).length;l>100&&t.push({type:"bloated",article:n,message:`${l} lines \u2014 consider splitting`}),a.meta.sources?.length||t.push({type:"unsourced",article:n,message:"No sources listed in frontmatter"}),l<10&&a.content.trim().length<100&&t.push({type:"stub",article:n,message:"Very short article \u2014 needs enrichment"})});for(let[r,n]of s)for(let a of n)e.has(a)||t.push({type:"broken-link",article:r,message:`[[${a}]] \u2014 target article not found`});let i=this.buildBacklinks();for(let[r,n]of o)(!i[r]||i[r].length===0)&&t.push({type:"orphan",article:n,message:`No other articles link to "${r}"`});return this.appendLog("lint",`Found ${t.length} issues`),t}getUnabsorbedEntries(){let t=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let o=k(this.baseDir,s);if(o.startsWith("raw/")||o.startsWith("_"))return;let i=this.readArticle(o);if(i?.meta.sources)for(let r of i.meta.sources)t.add(r)}),this.listEntries().filter(s=>!t.has(s.id))}buildAbsorbPrompt(t=20){let e=this.getUnabsorbedEntries().slice(0,t);if(e.length===0)return null;let s=e.map(o=>`[${o.date} ${o.agentId} via ${o.source}] ${o.content.slice(0,200)}`).join(`
99
-
100
- `);return`/wiki absorb
101
-
102
- There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
103
-
104
- ${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let o=Y(t,s),i=F(o);i.isDirectory()?this.walkDir(o,e):e(o,i)}}};export{J as a};
105
- //# sourceMappingURL=chunk-OISCRNMW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/store.ts"],"sourcesContent":["import { readFileSync, writeFileSync, appendFileSync, existsSync, mkdirSync, readdirSync, statSync, type Stats } from \"fs\"\nimport { resolve, join, relative, dirname } from \"path\"\nimport { isWikiArticleType } from \"./types\"\nimport type { WikiArticle, WikiArticleMeta, WikiEntry, WikiIndex, WikiAccess } from \"./types\"\nimport { buildIndex, buildIndexCached, scoreAll } from \"../memory/bm25\"\nimport { askSeat } from \"../decisions/seat\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"../decisions/seats/wiki-rerank\"\nimport { ancestryScore as ancestryOf } from \"@/graph\"\nimport { LockBusyError, withLock } from \"./facts/ledger-file\"\nimport { IMPORTANCE_LEVELS, type Importance, type WikiStatement } from \"./ontology/types\"\n\nfunction isImportance(s: string): s is Importance {\n return (IMPORTANCE_LEVELS as readonly string[]).includes(s)\n}\n\n/** Read the one-line JSON `statements:` value. A statement without a\n * property or value is dropped; a line that is not JSON drops them all,\n * since a half-read list would show wrong facts as complete. */\nexport function parseStatements(line: string): WikiStatement[] | undefined {\n if (!line) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n return undefined // not JSON: treat the page as having no statements\n }\n if (!Array.isArray(parsed)) return undefined\n const out = parsed.filter((s): s is WikiStatement =>\n typeof s === \"object\" && s !== null\n && typeof (s as WikiStatement).property === \"string\" && (s as WikiStatement).property !== \"\"\n && typeof (s as WikiStatement).value === \"string\" && (s as WikiStatement).value !== \"\")\n return out.length ? out : undefined\n}\n\n// --- Wiki Store: filesystem-based knowledge base with permissions ---\n//\n// Structure:\n// .agentx/wiki/\n// _index.md # Master index with aliases\n// _backlinks.json # Reverse link index\n// raw/entries/ # One .md per ingested entry\n// {directories}/ # Articles organized by type\n//\n// Permission model:\n// - private: only owner agent reads/writes\n// - shared: owner writes, listed agents read\n// - public: owner writes, all agents read\n\n/**\n * Order version file names oldest first: by timestamp, then by the counter\n * suffix that saveVersion adds when two writes share a millisecond\n * (`<ts>.md` < `<ts>-1.md` < `<ts>-2.md` < ... < `<ts>-10.md`).\n */\nfunction compareVersionNames(a: string, b: string): number {\n const split = (f: string): [string, number] => {\n const m = /^(.*Z)(?:-(\\d+))?\\.md$/.exec(f)\n return m ? [m[1], m[2] ? Number(m[2]) : 0] : [f, 0]\n }\n const [ta, na] = split(a)\n const [tb, nb] = split(b)\n return ta < tb ? -1 : ta > tb ? 1 : na - nb\n}\n\nexport class WikiStore {\n readonly baseDir: string\n private rawDir: string\n private log: (...args: unknown[]) => void\n /** How long a write waits for another process holding the page's lock. */\n lockWaitMs = 5000\n\n constructor(\n baseDir: string = resolve(process.cwd(), \".agentx/wiki\"),\n log: (...args: unknown[]) => void = console.error.bind(console, \"[wiki]\"),\n ) {\n this.baseDir = baseDir\n this.rawDir = resolve(baseDir, \"raw/entries\")\n this.log = log\n\n mkdirSync(this.rawDir, { recursive: true })\n mkdirSync(resolve(baseDir, \"raw\"), { recursive: true })\n\n // Initialize schema if missing\n this.ensureSchema()\n }\n\n // --- Permission checks ---\n\n /**\n * Check if an agent can read an article.\n */\n canRead(article: WikiArticleMeta, agentId?: string): boolean {\n if (article.access === \"public\") return true\n if (!agentId) return false\n if (article.owner === agentId) return true\n if (article.access === \"shared\" && article.sharedWith?.includes(agentId)) return true\n return false\n }\n\n /**\n * Check if an agent can write an article.\n */\n canWrite(article: WikiArticleMeta, agentId: string): boolean {\n return article.owner === agentId\n }\n\n // --- Raw entries (ingestion) ---\n\n /**\n * Add a raw entry (from a conversation, cron result, etc.)\n */\n addEntry(entry: WikiEntry): string {\n const filename = `${entry.date}_${entry.id}.md`\n const filepath = resolve(this.rawDir, filename)\n\n const frontmatter = [\n \"---\",\n `id: ${entry.id}`,\n `date: ${entry.date}`,\n `agent: ${entry.agentId}`,\n `source: ${entry.source}`,\n ]\n if (entry.sourceContext) frontmatter.push(`context: ${entry.sourceContext}`)\n if (entry.meta) {\n for (const [k, v] of Object.entries(entry.meta)) {\n frontmatter.push(`${k}: ${JSON.stringify(v)}`)\n }\n }\n frontmatter.push(\"---\", \"\", entry.content)\n\n writeFileSync(filepath, frontmatter.join(\"\\n\"))\n this.appendLog(\"ingest\", `${entry.id} from ${entry.agentId} via ${entry.source}`)\n return filename\n }\n\n /** Read only the named entries. Files are `<date>_<id>.md`, so one\n * directory listing finds them without parsing the rest. */\n readEntries(ids: string[]): WikiEntry[] {\n if (ids.length === 0 || !existsSync(this.rawDir)) return []\n const wanted = new Set(ids)\n const out: WikiEntry[] = []\n for (const file of readdirSync(this.rawDir)) {\n const id = file.replace(/\\.md$/, \"\").replace(/^\\d{4}-\\d{2}-\\d{2}_/, \"\")\n if (!wanted.has(id)) continue\n const entry = this.parseEntry(readFileSync(resolve(this.rawDir, file), \"utf-8\"), file)\n if (entry) out.push(entry)\n }\n return out\n }\n\n /**\n * List raw entries, optionally filtered by agent or date range.\n */\n listEntries(filter?: { agentId?: string; after?: string; before?: string }): WikiEntry[] {\n if (!existsSync(this.rawDir)) return []\n\n const files = readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).sort()\n const entries: WikiEntry[] = []\n\n for (const file of files) {\n const content = readFileSync(resolve(this.rawDir, file), \"utf-8\")\n const entry = this.parseEntry(content, file)\n if (!entry) continue\n\n if (filter?.agentId && entry.agentId !== filter.agentId) continue\n if (filter?.after && entry.date < filter.after) continue\n if (filter?.before && entry.date > filter.before) continue\n\n entries.push(entry)\n }\n\n return entries\n }\n\n private parseEntry(content: string, filename: string): WikiEntry | null {\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const body = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim() || \"\"\n }\n\n // Everything addEntry wrote that is not one of the five named keys is\n // `meta`, JSON-encoded one key per line. Dropping it here is what made\n // graphPath 0%: the capture path stamps intentPath onto every entry,\n // `wiki absorb` reads entry.meta.intentPath to propagate it onto the\n // article, and this parser never returned a meta at all — so absorb\n // always fell through to a fingerprint lookup its own comment calls\n // unreliable, and the retrieval scorer multiplied the graph weight\n // (0.6 of the hybrid score) by zero for every article ever compiled.\n const KNOWN = new Set([\"id\", \"date\", \"agent\", \"source\", \"context\"])\n const meta: Record<string, unknown> = {}\n for (const line of fm.split(\"\\n\")) {\n const m = line.match(/^(\\w+):\\s*(.+)$/)\n if (!m || KNOWN.has(m[1])) continue\n try {\n meta[m[1]] = JSON.parse(m[2])\n } catch {\n meta[m[1]] = m[2].trim()\n }\n }\n\n return {\n id: get(\"id\") || filename.replace(\".md\", \"\"),\n date: get(\"date\"),\n agentId: get(\"agent\"),\n source: get(\"source\"),\n sourceContext: get(\"context\") || undefined,\n content: body,\n meta: Object.keys(meta).length > 0 ? meta : undefined,\n }\n }\n\n // --- Articles (compiled knowledge) ---\n\n /**\n * Run `fn` holding the page's lock, so a read → change → write inside it\n * can't lose a write from another process. Every `writeArticle` takes\n * the same lock; re-entrant within one process. Locks live under\n * `_locks/`, which page listings skip. Throws LockBusyError when another\n * holder keeps it past the wait.\n */\n withArticleLock<T>(path: string, fn: () => T): T {\n const lock = `${resolve(this.baseDir, \"_locks\", path)}.lock`\n return withLock(resolve(this.baseDir, path), fn, { lock, what: `wiki page ${path}`, timeoutMs: this.lockWaitMs, staleMs: 10_000 })\n }\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 try {\n return this.withArticleLock(path, () => this.writeArticleLocked(path, meta, content, agentId))\n } catch (e) {\n if (!(e instanceof LockBusyError)) throw e\n this.log(e.message)\n return false\n }\n }\n\n private writeArticleLocked(path: string, meta: WikiArticleMeta, content: string, agentId: string): boolean {\n // LLM picks the path. We just write the file.\n const existing = this.readArticle(path)\n if (existing && !this.canWrite(existing.meta, agentId)) {\n this.log(`Permission denied: \"${agentId}\" cannot write \"${path}\" (owner: ${existing.meta.owner})`)\n return false\n }\n\n // Drop invalid `type` at write time. The parser already rejects invalid\n // values on read (returns type=undefined), so silently serialising a\n // stray value would cause the round-trip to look fine but the article\n // to render as \"untyped\" in the catalog. Log + drop beats surprise.\n if (meta.type && !isWikiArticleType(meta.type)) {\n this.log(`Dropping invalid article type \"${meta.type}\" for \"${path}\" — enum is [person, project, place, concept, event, decision, pattern]`)\n meta = { ...meta, type: undefined }\n }\n\n const fullPath = resolve(this.baseDir, path)\n\n // Version the previous content before overwriting (immutable history)\n if (existing) {\n this.saveVersion(path, fullPath)\n }\n\n mkdirSync(dirname(fullPath), { recursive: true })\n\n const frontmatter = [\n \"---\",\n `title: \"${meta.title}\"`,\n ]\n if (meta.type) frontmatter.push(`type: ${meta.type}`)\n if (meta.related?.length) {\n frontmatter.push(`related: [${meta.related.map(t => `\"${t}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `tags: [${(meta.tags || []).map(t => `\"${t}\"`).join(\", \")}]`,\n `owner: ${meta.owner}`,\n `access: ${meta.access}`,\n )\n if (meta.sharedWith?.length) {\n frontmatter.push(`shared_with: [${meta.sharedWith.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `created: ${meta.created}`,\n `last_updated: ${meta.lastUpdated}`,\n `sources: [${meta.sources.map(s => `\"${s}\"`).join(\", \")}]`,\n )\n if (meta.graphPath?.length) {\n frontmatter.push(`graph_path: [${meta.graphPath.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n // Ontology fields (#811). Statements go on one line as JSON, which\n // is also valid YAML, so the line-based reader below stays simple.\n if (meta.class) frontmatter.push(`class: ${meta.class}`)\n if (meta.importance) frontmatter.push(`importance: ${meta.importance}`)\n if (meta.importanceProposed) frontmatter.push(`importance_proposed: ${meta.importanceProposed}`)\n if (meta.date) frontmatter.push(`date: ${meta.date}`)\n if (meta.rolledUpInto) frontmatter.push(`rolled_up_into: ${JSON.stringify(meta.rolledUpInto)}`)\n if (meta.aliases?.length) frontmatter.push(`aliases: ${JSON.stringify(meta.aliases)}`)\n if (meta.statements?.length) frontmatter.push(`statements: ${JSON.stringify(meta.statements)}`)\n frontmatter.push(\"---\", \"\", content)\n\n writeFileSync(fullPath, frontmatter.join(\"\\n\"))\n const action = existing ? \"update\" : \"create\"\n this.appendLog(action, `${meta.title} [${(meta.tags || []).slice(0, 5).join(\", \")}] by ${agentId} at ${path}`)\n return true\n }\n\n // --- Article Versioning ---\n\n /**\n * Save current article content as an immutable version before overwriting.\n * Versions stored in _versions/{article-path}/{timestamp}.md\n */\n private saveVersion(articlePath: string, fullPath: string): void {\n try {\n if (!existsSync(fullPath)) return\n const content = readFileSync(fullPath, \"utf-8\")\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\")\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n mkdirSync(versionDir, { recursive: true })\n // Two writes inside one millisecond share a timestamp: the later one\n // gets a counter suffix (`<ts>-1.md`, ...) instead of overwriting.\n for (let n = 0; ; n++) {\n try {\n writeFileSync(resolve(versionDir, `${n ? `${ts}-${n}` : ts}.md`), content, { flag: \"wx\" })\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err\n }\n }\n } catch {\n // Version save is best-effort\n }\n }\n\n /**\n * List all versions of an article (newest first).\n */\n getVersions(articlePath: string): Array<{ timestamp: string; path: string }> {\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n if (!existsSync(versionDir)) return []\n\n try {\n return readdirSync(versionDir)\n .filter(f => f.endsWith(\".md\"))\n .sort(compareVersionNames)\n .reverse()\n .map(f => ({\n timestamp: f.replace(/\\.md$/, \"\").replace(/-/g, (m, i) => i < 19 ? (i === 10 ? \"T\" : i === 13 || i === 16 ? \":\" : \"-\") : m),\n path: resolve(versionDir, f),\n }))\n } catch {\n return []\n }\n }\n\n /**\n * Restore a specific version of an article.\n */\n restoreVersion(articlePath: string, versionTimestamp: string): boolean {\n const versions = this.getVersions(articlePath)\n const version = versions.find(v => v.timestamp === versionTimestamp)\n ?? versions.find(v => v.timestamp.startsWith(versionTimestamp))\n if (!version) return false\n\n try {\n const content = readFileSync(version.path, \"utf-8\")\n const fullPath = resolve(this.baseDir, articlePath)\n // Save current as a version too before restoring\n this.saveVersion(articlePath, fullPath)\n writeFileSync(fullPath, content)\n this.appendLog(\"restore\", `${articlePath} restored to ${versionTimestamp}`)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Read an article. Returns null if not found.\n */\n readArticle(path: string): WikiArticle | null {\n const fullPath = resolve(this.baseDir, path)\n if (!existsSync(fullPath)) return null\n\n const raw = readFileSync(fullPath, \"utf-8\")\n return this.parseArticle(raw, path)\n }\n\n /**\n * Read an article with permission check.\n */\n readArticleAs(path: string, agentId: string): WikiArticle | null {\n const article = this.readArticle(path)\n if (!article) return null\n if (!this.canRead(article.meta, agentId)) return null\n return article\n }\n\n private parseArticle(raw: string, path: string): WikiArticle | null {\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const content = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim().replace(/^\"(.*)\"$/, \"$1\") || \"\"\n }\n\n const getArray = (key: string): string[] => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*\\\\[(.*)\\\\]$`, \"m\"))\n if (!m) return []\n // Quoted items may hold commas — related titles often do, e.g.\n // \"Reviewed: NOT READY, Then READY\". Unquoted legacy items may not.\n // Items are written unescaped, so a quoted item may also hold quotes\n // (\"Carbon \"12 M\" Fix\"): it ends only at a quote before a comma or the end.\n return [...m[1].matchAll(/\\s*(?:\"(.*?)\"(?=\\s*(?:,|$))|([^,]+))/g)]\n .map(x => (x[1] ?? x[2]).trim())\n .filter(Boolean)\n }\n\n // `type` and `kind` are the new structural spine; no longer stuffed into tags.\n // Legacy articles may have a `kind:` field; we promote it to `type` on read so\n // the migration (Phase 2) can patch it in place.\n const rawType = get(\"type\") || get(\"kind\")\n const validTypes = new Set([\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\",\n ])\n const type = validTypes.has(rawType) ? (rawType as WikiArticleMeta[\"type\"]) : undefined\n\n const tags = getArray(\"tags\").filter((v, i, a) => v && a.indexOf(v) === i)\n const related = getArray(\"related\")\n const graphPath = getArray(\"graph_path\")\n const aliases = getArray(\"aliases\")\n const importance = get(\"importance\")\n const importanceProposed = get(\"importance_proposed\")\n const date = get(\"date\")\n return {\n meta: {\n title: get(\"title\"),\n type,\n related: related.length ? related : undefined,\n tags,\n owner: get(\"owner\"),\n access: (get(\"access\") as WikiAccess) || \"public\",\n sharedWith: getArray(\"shared_with\"),\n created: get(\"created\"),\n lastUpdated: get(\"last_updated\"),\n sources: getArray(\"sources\"),\n graphPath: graphPath.length ? graphPath : undefined,\n class: /^[a-z][a-z0-9_]*$/.test(get(\"class\")) ? get(\"class\") : undefined,\n importance: isImportance(importance) ? importance : undefined,\n importanceProposed: isImportance(importanceProposed) ? importanceProposed : undefined,\n date: /^\\d{4}-\\d{2}-\\d{2}/.test(date) ? date.slice(0, 10) : undefined,\n rolledUpInto: get(\"rolled_up_into\") || undefined,\n aliases: aliases.length ? aliases : undefined,\n statements: parseStatements(get(\"statements\")),\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n /** Catalog per agent, valid while no article file changed. The walk is\n * repeated (names, mtimes, sizes) but the frontmatter parse of every\n * article is not; on a wiki of ten thousand files that parse was the\n * cost of every fresh session. */\n private listCache = new Map<string, { signature: string; articles: WikiArticle[] }>()\n\n listArticles(agentId: string): WikiArticle[] {\n return this.listCached(agentId)\n }\n\n /** Every article whatever its access, for the owner's own views. */\n listAllArticles(): WikiArticle[] {\n return this.listCached(null)\n }\n\n private listCached(agentId: string | null): WikiArticle[] {\n const relPaths: string[] = []\n const sig: string[] = []\n this.walkDir(this.baseDir, (filePath, stat) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n relPaths.push(relPath)\n sig.push(`${relPath}:${stat?.mtimeMs ?? \"?\"}:${stat?.size ?? \"?\"}`)\n })\n const signature = sig.join(\"|\")\n const key = agentId ?? \"\\u0000all\"\n const hit = this.listCache.get(key)\n if (hit && hit.signature === signature) return hit.articles.slice()\n\n const articles: WikiArticle[] = []\n for (const relPath of relPaths) {\n const article = this.readArticle(relPath)\n if (article && (agentId === null || this.canRead(article.meta, agentId))) {\n articles.push(article)\n }\n }\n this.listCache.set(key, { signature, articles })\n return articles.slice()\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * findRelevant, then re-ranked by the wiki-rerank seat.\n *\n * Recall comes from findRelevant rather than search() because\n * findRelevant is the function everything actually calls — search()\n * turned out to have no callers at all. Additive on purpose: the\n * synchronous findRelevant is untouched and its existing callers stay\n * as they are. Measured on the 12-query eval against this\n * wiki, re-ranking moves R@1 from 33.3% to 50.0% and R@3 from 41.7% to\n * 66.7%, for about $0.0005 and 550ms a query.\n *\n * Fail-open in every direction. Seat off, backend down, no key, fewer\n * than two candidates — all return BM25's own order, which is what the\n * caller would have got anyway.\n *\n * Note what this cannot do: it only reorders what BM25 shortlisted. In\n * the eval R@3 sat exactly on that ceiling, so every remaining miss was\n * an article BM25 never returned. Widening the shortlist does not fix\n * that — past 30 the extra candidates measurably diluted the ranking.\n */\n async findRelevantReranked(\n query: string,\n agentId?: string,\n maxResults = 10,\n opts: { shortlist?: number; excerptChars?: number } = {},\n ): Promise<WikiArticle[]> {\n const shortlist = Math.max(maxResults, opts.shortlist ?? DEFAULT_SHORTLIST)\n const pool = this.findRelevant(query, agentId, shortlist)\n if (pool.length < 2) return pool.slice(0, maxResults)\n\n const candidates: RerankCandidate[] = pool.map((article, i) => ({\n // Index, not title: titles are not unique across a wiki and a\n // Choice needs distinct keys.\n id: `c${i}`,\n title: article.meta.title || `(untitled ${i})`,\n tags: article.meta.tags,\n excerpt: article.content,\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query, candidates, excerptChars: opts.excerptChars }),\n rerankQuestions(candidates),\n { incumbent: { best: candidates[0].id }, features: { agent: agentId ?? \"unknown\" } },\n )\n if (!result || result.mode !== \"active\") return pool.slice(0, maxResults)\n\n const ranking = toRanking(result.answers as never, candidates)\n return ranking.ranked\n .map((id) => pool[Number(id.slice(1))])\n .filter((a): a is WikiArticle => Boolean(a))\n .slice(0, maxResults)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n graphPath: article.meta.graphPath,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string, stat?: Stats) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full, stat)\n }\n }\n }\n}\n"],"mappings":"wSAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,EAAW,eAAAC,EAAa,YAAAC,MAA4B,KACtH,OAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,WAAAC,MAAe,OAIjDC,IAaA,SAASC,EAAaC,EAA4B,CAChD,OAAQC,EAAwC,SAASD,CAAC,CAC5D,CAKO,SAASE,EAAgBC,EAA2C,CACzE,GAAI,CAACA,EAAM,OACX,IAAIC,EACJ,GAAI,CACFA,EAAS,KAAK,MAAMD,CAAI,CAC1B,MAAE,CACA,MACF,CACA,GAAI,CAAC,MAAM,QAAQC,CAAM,EAAG,OAC5B,IAAMC,EAAMD,EAAO,OAAQ,GACzB,OAAO,GAAM,UAAY,IAAM,MAC5B,OAAQ,EAAoB,UAAa,UAAa,EAAoB,WAAa,IACvF,OAAQ,EAAoB,OAAU,UAAa,EAAoB,QAAU,EAAE,EACxF,OAAOC,EAAI,OAASA,EAAM,MAC5B,CAqBA,SAASC,EAAoBC,EAAWC,EAAmB,CAC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EAAW,IAAI/G,EAAE,EAAE,CAAC,CAClD,CAMA,kBAAkBgH,EAAqB,GAAmB,CACxD,IAAMC,EAAa,KAAK,qBAAqB,EAAE,MAAM,EAAGD,CAAU,EAClE,GAAIC,EAAW,SAAW,EAAG,OAAO,KAEpC,IAAMC,EAAiBD,EAAW,IAAIjH,GACpC,IAAIA,EAAE,QAAQA,EAAE,eAAeA,EAAE,WAAWA,EAAE,QAAQ,MAAM,EAAG,GAAG,GACpE,EAAE,KAAK;AAAA;AAAA,CAAM,EAEb,MAAO;AAAA;AAAA,YAA6BiH,EAAW;AAAA;AAAA,EAA2GC,GAC5J,CAEQ,QAAQC,EAAaC,EAA0D,CACrF,GAAKzI,EAAWwI,CAAG,EACnB,QAAWhJ,KAASW,EAAYqI,CAAG,EAAG,CACpC,IAAME,EAAOC,EAAKH,EAAKhJ,CAAK,EACtB6D,EAAOuF,EAASF,CAAI,EACtBrF,EAAK,YAAY,EACnB,KAAK,QAAQqF,EAAMD,CAAQ,EAE3BA,EAASC,EAAMrF,CAAI,EAGzB,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","readdirSync","statSync","resolve","join","relative","dirname","init_seat","isImportance","s","IMPORTANCE_LEVELS","parseStatements","line","parsed","out","compareVersionNames","a","b","split","f","m","ta","na","tb","nb","WikiStore","baseDir","resolve","log","mkdirSync","article","agentId","entry","filename","filepath","frontmatter","k","v","writeFileSync","ids","existsSync","wanted","file","readdirSync","id","readFileSync","filter","files","entries","content","fmMatch","fm","body","get","key","KNOWN","meta","path","fn","lock","withLock","e","LockBusyError","existing","isWikiArticleType","fullPath","dirname","t","action","articlePath","ts","versionDir","n","err","versionTimestamp","versions","version","raw","getArray","x","rawType","type","tags","i","related","graphPath","aliases","importance","importanceProposed","date","relPaths","sig","filePath","stat","relPath","relative","signature","hit","articles","query","maxResults","queryLower","docs","cachePath","index","buildIndexCached","bm25Scores","scoreAll","scoreMap","r","score","opts","shortlist","DEFAULT_SHORTLIST","pool","candidates","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","toRanking","message","maxArticles","messagePath","weights","maxBm25","bm25Map","hasGraph","bm25","ancestry","ancestryScore","combined","maxChars","lines","totalChars","header","chunk","backlinks","links","link","target","md","byAccess","bucket","list","y","lastRebuilt","typeOrder","typeHeaders","byType","access","totalArticles","byOwner","tag","entryFiles","details","logPath","appendFileSync","limit","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync"]}