agentix-cli 0.136.0 → 0.136.1

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 (46) hide show
  1. package/dist/{agent-VCGAUBER.js → agent-TMTYLAOV.js} +2 -2
  2. package/dist/{board-dashboard-JZM3FQNV.js → board-dashboard-OSI4X5ZJ.js} +2 -2
  3. package/dist/{chunk-C43E3YFT.js → chunk-4AFA6LQZ.js} +2 -2
  4. package/dist/{chunk-M5B4QG6J.js → chunk-63LV77EG.js} +2 -2
  5. package/dist/{chunk-HH7OFAEM.js → chunk-EGDY762K.js} +2 -2
  6. package/dist/{chunk-ZPJVDX2U.js → chunk-FRTELYZ4.js} +2 -2
  7. package/dist/chunk-G26UHWS4.js +105 -0
  8. package/dist/chunk-G26UHWS4.js.map +1 -0
  9. package/dist/{chunk-QCUJTAAZ.js → chunk-NVZ66ITP.js} +3 -3
  10. package/dist/{chunk-H2N7DOPT.js → chunk-QHZFMO6M.js} +2 -2
  11. package/dist/{chunk-K75LFQE3.js → chunk-QW3L5IIC.js} +2 -2
  12. package/dist/{chunk-QTDKNJXD.js → chunk-XXIZGNLT.js} +213 -213
  13. package/dist/{chunk-QTDKNJXD.js.map → chunk-XXIZGNLT.js.map} +1 -1
  14. package/dist/cli.js +1 -1
  15. package/dist/{hub-IIW2GBO5.js → hub-7AMS6ADP.js} +2 -2
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.js +1 -1
  18. package/dist/{program-WROQ55F5.js → program-IUUHETTV.js} +154 -154
  19. package/dist/program-IUUHETTV.js.map +1 -0
  20. package/dist/{promote-HDLU44MX.js → promote-VCNVE5JD.js} +2 -2
  21. package/dist/{registry-3RE5SG22.js → registry-MMNG5VZ6.js} +2 -2
  22. package/dist/rules-UVUJTVOE.js +24 -0
  23. package/dist/rules-UVUJTVOE.js.map +1 -0
  24. package/dist/{wiki-ZS6OHOWQ.js → wiki-ZQMDUXTE.js} +2 -2
  25. package/dist/wiki-enrich-NPNOSTRM.js +2 -0
  26. package/package.json +1 -1
  27. package/dist/chunk-OISCRNMW.js +0 -105
  28. package/dist/chunk-OISCRNMW.js.map +0 -1
  29. package/dist/program-WROQ55F5.js.map +0 -1
  30. package/dist/rules-HUUFXQD6.js +0 -24
  31. package/dist/rules-HUUFXQD6.js.map +0 -1
  32. package/dist/wiki-enrich-NGPFWTVA.js +0 -2
  33. /package/dist/{agent-VCGAUBER.js.map → agent-TMTYLAOV.js.map} +0 -0
  34. /package/dist/{board-dashboard-JZM3FQNV.js.map → board-dashboard-OSI4X5ZJ.js.map} +0 -0
  35. /package/dist/{chunk-C43E3YFT.js.map → chunk-4AFA6LQZ.js.map} +0 -0
  36. /package/dist/{chunk-M5B4QG6J.js.map → chunk-63LV77EG.js.map} +0 -0
  37. /package/dist/{chunk-HH7OFAEM.js.map → chunk-EGDY762K.js.map} +0 -0
  38. /package/dist/{chunk-ZPJVDX2U.js.map → chunk-FRTELYZ4.js.map} +0 -0
  39. /package/dist/{chunk-QCUJTAAZ.js.map → chunk-NVZ66ITP.js.map} +0 -0
  40. /package/dist/{chunk-H2N7DOPT.js.map → chunk-QHZFMO6M.js.map} +0 -0
  41. /package/dist/{chunk-K75LFQE3.js.map → chunk-QW3L5IIC.js.map} +0 -0
  42. /package/dist/{hub-IIW2GBO5.js.map → hub-7AMS6ADP.js.map} +0 -0
  43. /package/dist/{promote-HDLU44MX.js.map → promote-VCNVE5JD.js.map} +0 -0
  44. /package/dist/{registry-3RE5SG22.js.map → registry-MMNG5VZ6.js.map} +0 -0
  45. /package/dist/{wiki-ZS6OHOWQ.js.map → wiki-ZQMDUXTE.js.map} +0 -0
  46. /package/dist/{wiki-enrich-NGPFWTVA.js.map → wiki-enrich-NPNOSTRM.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-M5B4QG6J.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-MEFPXHQJ.js";import"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
2
- //# sourceMappingURL=promote-HDLU44MX.js.map
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-63LV77EG.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-MEFPXHQJ.js";import"./chunk-G26UHWS4.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
2
+ //# sourceMappingURL=promote-VCNVE5JD.js.map
@@ -1,2 +1,2 @@
1
- import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-QCUJTAAZ.js";import"./chunk-HZZW35FY.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-C43E3YFT.js";import"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-FQLSV2C4.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
2
- //# sourceMappingURL=registry-3RE5SG22.js.map
1
+ import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-NVZ66ITP.js";import"./chunk-HZZW35FY.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-4AFA6LQZ.js";import"./chunk-G26UHWS4.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-FQLSV2C4.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
2
+ //# sourceMappingURL=registry-MMNG5VZ6.js.map
@@ -0,0 +1,24 @@
1
+ import{d as x,i as ie,k as ae,m as G}from"./chunk-U6EJ53DA.js";import{k as T}from"./chunk-H4NSB54D.js";import"./chunk-MTX4UPNB.js";import{f,g as O}from"./chunk-QAWKN2N4.js";import"./chunk-IMLAPB7G.js";import{c as re}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";import{createHash as $e}from"crypto";import{existsSync as be,mkdirSync as Re,readFileSync as Se,writeFileSync as We}from"fs";import{resolve as q}from"path";var C="wiki-rules",E="wiki-rules",_e=["deadline","due date","due by","penalt","late fee","fine of","fined","must file","must pay","must declare","must submit","filing","obligation","compliance","tax return","\xE9ch\xE9ance","date limite","d\xE9lai","p\xE9nalit","amende","majoration","d\xE9claration","obligation","\u063A\u0631\u0627\u0645\u0629","\u0623\u062C\u0644","\u0622\u062C\u0627\u0644","\u062A\u0635\u0631\u064A\u062D","\u062E\u0637\u064A\u0629"],xe=new Set(["event","agent","device","server","app","domain","account","penalty","relief","due_date","person"]),ve=new Set(["person","organization"]),Ae=6e3,Ee=900,W=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e,S=e=>typeof e=="string"?e.replace(/\s+/g," ").trim():"",j=e=>S(e).replace(/["\[\]]/g,"").slice(0,120).trim();function Xe(e=_e){let t=e.map(s=>s.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).filter(Boolean);return new RegExp(`(^|[^\\p{L}\\p{N}])(${t.join("|")})`,"iu")}function Ie(e,t){return t.test(`${e.article.meta.title}
2
+ ${T(e.article.content)}`)}function Pe(e,t,s=[]){let n=new Set(s.map(f)),i=r=>r.pages.every(u=>(u.article.meta.tags??[]).includes(E)),a=r=>r.type==="legal_source"?0:r.type==="obligation"?1:2;return[...e.entities.values()].filter(r=>!i(r)).filter(r=>n.size?n.has(f(r.id))||n.has(f(r.title)):r.type==="legal_source"||r.type==="obligation"||!xe.has(r.type)&&r.pages.some(u=>Ie(u,t))).sort((r,u)=>a(r)-a(u)||u.sources.length-r.sources.length||r.title.localeCompare(u.title))}function se(e,t,s,n){let i=` ${f(s)} `,a=new Set([...(e.outgoing.get(t.id)??[]).map(r=>r.to),...(e.incoming.get(t.id)??[]).map(r=>r.from)]);return[...e.entities.values()].filter(r=>n.has(r.type)&&r.id!==t.id).filter(r=>a.has(r.id)||f(r.title).length>=3&&i.includes(` ${f(r.title)} `)).slice(0,40)}function Ue(e,t,s,n){let i=`${s.article.meta.title}
3
+ ${T(s.article.content)}`,a=n(s.article.meta.sources??[]).sort((l,g)=>g.date.localeCompare(l.date)).slice(0,10),r=`${i}
4
+ ${a.map(l=>l.content).join(`
5
+ `)}`,u=l=>l.pages.some(g=>x(g.article.meta,s.article.meta)),o=l=>[...e.entities.values()].filter(g=>g.type===l&&g.id!==t.id&&u(g));return{source:t,page:s,entries:a,known:o("obligation").slice(0,60),laws:o("legal_source").slice(0,40),parties:se(e,t,r,ve).filter(u),authorities:se(e,t,r,new Set(["organization"])).filter(u)}}function oe(e){let t=[`${e.agentId}/${e.article.path}`,T(e.article.content),...(e.article.meta.sources??[]).slice().sort()];return $e("sha1").update(t.join(`
6
+ `)).digest("hex").slice(0,16)}function Te(e,t){let s=t.statements.filter(n=>["action","due_rule"].includes(n.property)).map(n=>`${n.property}: ${n.value}`);return`- ${t.title}${s.length?` (${s.join("; ")})`:""}`}function Ce(e,t,s){let n=t.page,i=[`You are writing the rules one wiki page states, so nobody has to research them again. Today is ${s}.`,"",`## The page: ${n.agentId}/${n.article.path}: "${n.article.meta.title}"`,W(T(n.article.content),Ae),"","## Source entries behind the page (newest first)"];for(let a of t.entries)i.push(`### entry ${a.id} (${a.date}, ${a.agentId})`,W(a.content.trim(),Ee),"");return i.push("## Rule pages that already exist",...t.known.map(a=>Te(e,a)),""),i.push("## Legal source pages",...t.laws.map(a=>`- ${a.title}`),""),i.push("## People and organizations it names",...t.parties.map(a=>`- ${a.title} (${a.type})`),""),i.push("## Task","List each rule the page or the entries state: something a person or organization must do, by a deadline or on a schedule, often with a penalty when they do not.","Return one JSON object and nothing else:",'{"rules": [{"title": "\u2026", "action": "\u2026", "bearer": ["\u2026"], "deadline": "\u2026", "amount": "\u2026", "authority": "\u2026", "penalty": "\u2026", "basis": "\u2026", "procedure": "\u2026", "source": "\u2026"}]}',"","Rules:",'- title: a short name for the rule, such as "Monthly payroll tax filing". When it is one of the rule pages that already exist, use that title exactly.',"- action: what must be done, in one sentence. A rule without one is dropped.",'- bearer: who must do it. Use a listed person or organization title when it is one, else a short description such as "every employer".','- deadline: when, as the rule says it ("by the 15th of the following month"), not a computed date.',"- amount: what is paid or declared, if the rule says. authority: who it is filed with or paid to.","- penalty: what happens when it is late or missing, as stated.","- basis: the law, article or document it comes from. Use a listed legal source title when it is one.","- procedure: how it is done, in one sentence, if stated.","- source: the entry id or the page (agent/path) the rule comes from. A rule without one is dropped.","- Leave a field empty when the page and entries do not state it. Never guess a deadline, an amount or a penalty.","- Do not list one-time tasks, reminders or plans; only standing rules.","- Write in the language the page is written in.",'- No rules on the page: return {"rules": []}.'),i.join(`
7
+ `)}function De(e,t,s){let n=[],i=t.page,a=[...t.entries.map(l=>l.id),`${i.agentId}/${i.article.path}`,i.article.path],r=new Map(t.known.map(l=>[f(l.title),l])),u=[],o=new Set;for(let l of Array.isArray(e.rules)?e.rules:[]){let g=l??{},c=j(S(g.title)),p=W(S(g.action),400),$=S(g.source);if(!c){n.push("a rule with no title");continue}if(!p){n.push(`${c}: no action`);continue}if(!$||!a.some(R=>$.includes(R))){n.push(`${c}: source not among those given`);continue}if(o.has(f(c)))continue;o.add(f(c));let m=r.get(f(c)),h=s.names.get(f(c)),w=!m&&h?s.entities.get(h):void 0;if(w&&w.type!=="obligation"){n.push(`${c}: a page of type ${w.type} already has this title`);continue}let v=(Array.isArray(g.bearer)?g.bearer:[g.bearer]).map(R=>W(S(R),120)).filter(Boolean);u.push({title:m?.title??w?.title??c,existing:m??w,action:p,bearers:[...new Set(v)].slice(0,5),deadline:W(S(g.deadline),200),amount:W(S(g.amount),200),authority:W(S(g.authority),120),penalty:W(S(g.penalty),300),basis:W(S(g.basis),200),procedure:W(S(g.procedure),400),source:W($,200)})}return{rules:u,dropped:n}}function M(e,t){return t.find(n=>f(n.title)===f(e))?.title??e}function L(e,t){let s=i=>i&&/^\d{4}-\d{2}-\d{2}/.test(i)?i.slice(0,10):void 0;return t.entries.filter(i=>e.source.includes(i.id)).map(i=>s(i.date)).filter(Boolean).sort().at(-1)??s(t.entries[0]?.date)??s(t.page.article.meta.created)}function Oe(e,t){let s=L(e,t),n=(a,r)=>({property:a,value:r,source:e.source,...s?{checked_at:s}:{},status:"proposed",by:C}),i=[n("action",e.action)];for(let a of e.bearers)i.push(n("bearer",M(a,t.parties)));return e.deadline&&i.push(n("due_rule",e.deadline)),e.amount&&i.push(n("amount_rule",e.amount)),e.authority&&i.push(n("authority",M(e.authority,t.authorities))),i.push(n("created_by",e.basis?M(e.basis,t.laws):t.page.article.meta.title)),e.procedure&&i.push(n("procedure",e.procedure)),i}var pe=new Set(["action","due_rule","amount_rule","authority","created_by","procedure"]);function Ge(e,t,s){let n=e.filter(r=>r.by===C),i=new Set(t.filter(r=>r.property!=="created_by"||s.basis||!n.some(u=>u.property==="created_by")).map(r=>r.property)),a=t.filter(r=>i.has(r.property));for(let r of n)(pe.has(r.property)?!i.has(r.property):!a.some(u=>u.property===r.property&&f(u.value)===f(r.value)))&&a.push(r);return a}function ce(e,t,s){let n=(e.statements??[]).filter(o=>o.by!==C||o.status==="confirmed"),i=new Set(n.filter(o=>o.status==="confirmed"&&pe.has(o.property)).map(o=>o.property)),a=o=>`${o.property}
8
+ ${f(o.value)}`,r=new Set(n.map(a)),u=[...n,...t.filter(o=>!i.has(o.property)&&!r.has(a(o)))];return{...e,statements:u.length?u:void 0,lastUpdated:s}}var J="not found in the sources yet";function Me(e,t,s){let n=c=>e.filter(p=>p.property===c),i=c=>e.find(p=>p.property===c),a=i("action"),r=c=>c&&c.source&&c.source!==a?.source?` (from ${c.source}${c.checked_at?`, ${c.checked_at}`:""})`:"",u=(c,p)=>`- **${c}:** ${p?`${p.value}${r(p)}`:J}`,o=[...new Set([...e,...t?[t]:[]].map(c=>c.source).filter(c=>!!c))],l=[...e.filter(c=>["action","due_rule"].includes(c.property)),...t?[t]:[]].map(c=>c.checked_at).filter(c=>!!c).sort(),g=i("created_by")?.value;return[u("What to do",a),`- **Who:** ${n("bearer").length?n("bearer").map(c=>c.value).join(", "):J}`,u("Deadline",i("due_rule")),...i("amount_rule")?[u("Amount",i("amount_rule"))]:[],...i("authority")?[u("Filed with",i("authority"))]:[],`- **Penalty:** ${t?`${t.value}${r(t)}`:J}`,`- **Source:** ${g?`${g}, `:""}last read from [[${s}]]${o.length?` (sources: ${o.join(", ")})`:""}`,`- **Source date:** ${l[0]??"not known"}. Not yet checked with the law or the authority.`].join(`
9
+ `)}var le="## Rule summary",K="<!-- /rule-summary -->";function je(e,t){let s=`${le}
10
+
11
+ ${t.trim()}
12
+
13
+ ${K}
14
+ `,n=e.indexOf(`${le}
15
+ `),i=n<0?-1:e.indexOf(K,n);return n>=0&&i>=0?`${e.slice(0,n)}${s}${e.slice(i+K.length).replace(/^\n/,"")}`:`${s}
16
+ ${e.trim()}
17
+ `}function Ze(e){let t=q(e,"_rules","state.json");if(!be(t))return{sources:{}};try{let s=JSON.parse(Se(t,"utf-8"));return s&&typeof s.sources=="object"?s:{sources:{}}}catch{return{sources:{}}}}function et(e,t){Re(q(e,"_rules"),{recursive:!0}),We(q(e,"_rules","state.json"),JSON.stringify(t,null,2))}function Le(e,t,s,n,i){let a=s.page,r=n.get(f(t.title));if(r)return x(a.article.meta,r.meta)?r:"the rule page is readable by agents who cannot read the source";if(t.existing){let c=G(e,t.existing);return c?x(a.article.meta,c.article.meta)?{agentId:c.agentId,path:c.article.path,meta:c.article.meta,content:c.article.content,created:!1}:"the rule page is readable by agents who cannot read the source":"the rule page was copied from another machine"}let u=a.article.meta.owner||a.agentId,o=e.getAgentWiki(a.agentId),l=`obligations/${O(t.title)}.md`;for(let c=2;o.readArticle(l);c++)l=`obligations/${O(t.title)}-${c}.md`;let g={title:t.title,class:"obligation",tags:[E],owner:u,access:a.article.meta.access,sharedWith:a.article.meta.sharedWith,created:i,lastUpdated:i,sources:[]};return{agentId:a.agentId,path:l,meta:g,content:`${t.title}.
18
+ `,created:!0}}function ue(e,t,s){let n=e.getAgentWiki(t.agentId).readArticle(t.path);return t.created?n?"a page was created at the rule's path during the run":t:n?x(s,n.meta)?{...t,meta:n.meta,content:n.content}:"the rule page is readable by agents who cannot read the source":"the rule page was moved or removed during the run"}function Q(e,t,s,n){try{return e.getAgentWiki(t).withArticleLock(s,n)}catch(i){if(!(i instanceof re))throw i;return"the page was busy; run again"}}var Ne=e=>(e.statements??[]).some(t=>t.property==="amount_rule"&&t.status==="confirmed"),ge=e=>`penalties/${O(j(`${e} penalty`))}.md`;function He(e,t,s,n){let i=r=>{let u=(r??[]).filter(l=>l.property==="amount_rule"&&l.value),o=u.find(l=>l.status==="confirmed")??u[0];return o?{value:o.value,source:o.source,checked_at:o.checked_at,...o.status==="confirmed"?{confirmed:!0}:{}}:void 0},a=e.getAgentWiki(n.agentId).readArticle(ge(s));if(a&&(a.meta.tags??[]).includes(E))return i(a.meta.statements);for(let r of t.entities.values()){if(r.type!=="penalty"||!r.statements.some(l=>l.property==="penalty_for"&&f(l.value)===f(s)))continue;let u=r.pages.find(l=>x(n.meta,l.article.meta)),o=u&&i(u.article.meta.statements);if(o)return o}}function Fe(e,t,s,n){let i=j(`${e.title} penalty`),a=L(e,s),r=(o,l)=>({property:o,value:l,source:e.source,...a?{checked_at:a}:{},status:"proposed",by:C}),u=[r("penalty_for",e.title),r("amount_rule",e.penalty),r("created_by",e.basis?M(e.basis,s.laws):s.page.article.meta.title)];return{path:ge(e.title),meta:{title:i,class:"penalty",tags:[E],owner:t.meta.owner,access:t.meta.access,sharedWith:t.meta.sharedWith,created:n,lastUpdated:n,sources:t.meta.sources,statements:u,related:[e.title]},content:`## Overview
19
+
20
+ ${e.penalty}
21
+
22
+ For [[${e.title}]]. Source: ${e.source}${a?`, dated ${a}`:""}. Not yet checked with the law or the authority.
23
+ `}}function de(e,t,s,n,i,a){let r=[];for(let u of t.bearers){let o=s.parties.find(m=>f(m.title)===f(u));if(!o)continue;let l=G(e,o);if(!l){a.push(`${t.title} \u2192 ${o.title}: page copied from another machine`);continue}if(!x(n.meta,l.article.meta)){a.push(`${t.title} \u2192 ${o.title}: page readable by agents who cannot read the rule`);continue}let g=m=>(m.statements??[]).some(h=>h.property==="subject_to"&&f(h.value)===f(t.title));if(g(l.article.meta))continue;if(i){r.push(o.title);continue}let c=e.getAgentWiki(l.agentId),p=!1,$=Q(e,l.agentId,l.article.path,()=>{let m=c.readArticle(l.article.path);if(!m)return"page moved or removed during the run";if(!x(n.meta,m.meta))return"page readable by agents who cannot read the rule";if(g(m.meta))return;let h=L(t,s),w=[...m.meta.statements??[],{property:"subject_to",value:t.title,source:t.source,...h?{checked_at:h}:{},status:"proposed",by:C}],v={...m.meta,statements:w};if(!c.writeArticle(l.article.path,v,m.content,m.meta.owner||l.agentId))return"write refused";l.article.meta=v,p=!0});$?a.push(`${t.title} \u2192 ${o.title}: ${$}`):p&&r.push(o.title)}return r}async function tt(e,t,s,n,i){let a=p=>i.sources[p.id]?.failures??0,r=Pe(t,n.words,n.only).sort((p,$)=>a(p)-a($)),u=p=>e.getSharedStore().readEntries(p),o={outcomes:[],costUsd:0,capped:!1},l=new Map,g=0,c=(p,$,m,h=!1)=>{if(n.dryRun)return;let w=i.sources[p];i.sources[p]=h?{fingerprint:w?.fingerprint??"",at:new Date().toISOString(),costUsd:m,failures:(w?.failures??0)+1}:{fingerprint:$,at:new Date().toISOString(),costUsd:m},n.save?.(i)};for(let p of r){if(g>=n.max)break;let $={source:p.id,title:p.title,rules:[],costUsd:0,dropped:[]},m=G(e,p);if(!m){n.only.length&&o.outcomes.push({...$,status:"no-page"});continue}let h=Ue(t,p,m,u),w=oe(m);if(!n.force&&i.sources[p.id]?.fingerprint===w){n.only.length&&o.outcomes.push({...$,status:"unchanged"});continue}if(o.costUsd>=n.maxCostUsd){o.capped=!0;break}g++;let v=`${m.agentId}/${m.article.path}`,R;try{R=await s(Ce(t,h,n.today))}catch(y){o.outcomes.push({...$,page:v,status:"failed",dropped:[y.message.slice(0,200)]}),c(p.id,w,0,!0);continue}o.costUsd+=R.costUsd;let k={...$,page:v,status:"no-reply",costUsd:R.costUsd},V=ie(R.text);if(!V){o.outcomes.push(k),c(p.id,w,R.costUsd);continue}let N=De(V,h,t);if(k.dropped=N.dropped,N.rules.length===0){k.status="no-rules",o.outcomes.push(k),c(p.id,w,R.costUsd);continue}let H=!1;for(let y of N.rules){let A=Le(e,y,h,l,n.today);if(typeof A=="string"){k.dropped.push(`${y.title}: ${A}`);continue}let Z=d=>{let b=Ge(d.meta.statements??[],Oe(y,h),y),_=ce(d.meta,b,n.today),P=He(e,t,y.title,d),Y=P?.confirmed||!y.penalty?P:{value:y.penalty,source:y.source,checked_at:L(y,h)},z=Me(_.statements??[],Y,m.article.meta.title),he=(d.meta.tags??[]).includes(E)?ae(d.content,z):je(d.content,z),ye=[...new Set([...d.meta.related??[],m.article.meta.title,...Y?[j(`${y.title} penalty`)]:[]])],we=[...new Set([...d.meta.sources??[],...h.entries.filter(U=>y.source.includes(U.id)).map(U=>U.id)])],ne={..._,related:ye,sources:we},ke={title:y.title,page:`${d.agentId}/${d.path}`,created:d.created,deadline:(ne.statements??[]).some(U=>U.property==="due_rule"),penalty:!!Y,linked:[]};return{t:d,meta:ne,content:he,summary:z,known:P,write:ke}};if(n.dryRun){let d=ue(e,A,h.page.article.meta);if(typeof d=="string"){k.dropped.push(`${y.title}: ${d}`);continue}let b=Z(d);b.write.preview=b.summary,b.write.linked=de(e,y,h,d,!0,k.dropped),k.rules.push(b.write);continue}let F,ee=Q(e,A.agentId,A.path,()=>{let d=ue(e,A,h.page.article.meta);if(typeof d=="string")return d;let b=Z(d);if(!e.getAgentWiki(d.agentId).writeArticle(d.path,b.meta,b.content,d.meta.owner||d.agentId))return"write refused";F=b});if(ee||!F){k.dropped.push(`${y.title}: ${ee??"write refused"}`),H=!0;continue}let{t:I,meta:B,content:me,known:fe,write:te}=F,D=e.getAgentWiki(I.agentId);if(l.set(f(y.title),{...I,meta:B,content:me,created:!1}),y.penalty&&!fe?.confirmed){let d=Fe(y,{...I,meta:B},h,n.today),b=Q(e,I.agentId,d.path,()=>{let _=D.readArticle(d.path);if(!_)return D.writeArticle(d.path,d.meta,d.content,d.meta.owner)?void 0:"write refused";if(!(_.meta.tags??[]).includes(E))return"already exists";if(Ne(_.meta))return;let P=ce({...d.meta,created:_.meta.created,statements:_.meta.statements},d.meta.statements??[],n.today);return D.writeArticle(d.path,P,d.content,d.meta.owner)?void 0:"write refused"});b&&k.dropped.push(`${y.title}: ${d.path} ${b}`)}te.linked=de(e,y,h,{...I,meta:B},!1,k.dropped),D.rebuildIndex(),k.rules.push(te)}k.status=n.dryRun?"dry-run":k.rules.length?"written":H?"failed":"no-rules",o.outcomes.push(k);let X=n.dryRun?null:e.getAgentWiki(m.agentId).readArticle(m.article.path);X&&(w=oe({agentId:m.agentId,article:X})),c(p.id,w,R.costUsd,H&&k.rules.length===0)}return o}export{_e as DEFAULT_RULE_WORDS,C as RULES_BY,E as RULES_TAG,Ce as buildRulesPrompt,De as checkRules,He as knownPenalty,Ze as loadRulesState,Ge as mergeRuleStatements,Me as ruleOverview,Pe as ruleSources,Oe as ruleStatements,Xe as ruleWordsPattern,Ue as rulesContext,oe as rulesFingerprint,tt as runRules,et as saveRulesState,L as sourceDate,Ie as statesRules,ce as withRuleStatements,je as withRuleSummary};
24
+ //# sourceMappingURL=rules-UVUJTVOE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/rules.ts"],"sourcesContent":["// --- Rule pages: one page per obligation, with deadline, penalty, source and check date (#811) ---\n//\n// Agents research the same rule again and again (a filing deadline, a\n// late fee) because the answer stays inside the page or chat where it\n// came up. This job reads the pages that state rules: legal sources,\n// obligation pages agents wrote, and any other page whose text speaks of\n// deadlines, penalties or filings. One model call per source page\n// returns the rules it states. Each rule is checked against what the\n// call was shown, then written once as an obligation page:\n// - statements for the obligation lens (action, bearer, due, amount,\n// authority, created by, procedure), each with its source and the\n// date of that source, marked proposed until the owner confirms them;\n// - a penalty page linked to it with `penalty_for`;\n// - `subject_to` on the page of each person or organization that must\n// follow it, so their Obligations panel lists it.\n// A later source that states less keeps what an earlier one stated: a\n// field is replaced only when the new source gives it. The model gets no\n// tools and every write goes through the store, which keeps the old version.\n\nimport { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { WikiHub } from \"./hub\"\nimport type { WikiArticleMeta, WikiEntry } from \"./types\"\nimport { normName, slugify, type Entity, type GraphPage, type WikiGraph } from \"./ontology/graph\"\nimport type { WikiStatement } from \"./ontology/types\"\nimport { bodyOf } from \"./ontology/view-entity\"\nimport { LockBusyError } from \"./facts/ledger-file\"\nimport { parseEnrichReply, readableAlongside, targetPage, withOverview, type EnrichCall } from \"./enrich\"\n\nexport const RULES_BY = \"wiki-rules\"\n/** Tag on the pages this job creates; they are never read as a source. */\nexport const RULES_TAG = \"wiki-rules\"\n\n/** Words that mark a page as stating a rule. Stems, matched at a word start. */\nexport const DEFAULT_RULE_WORDS = [\n \"deadline\", \"due date\", \"due by\", \"penalt\", \"late fee\", \"fine of\", \"fined\", \"must file\", \"must pay\", \"must declare\",\n \"must submit\", \"filing\", \"obligation\", \"compliance\", \"tax return\",\n \"échéance\", \"date limite\", \"délai\", \"pénalit\", \"amende\", \"majoration\", \"déclaration\", \"obligation\",\n \"غرامة\", \"أجل\", \"آجال\", \"تصريح\", \"خطية\",\n]\n\n/** Types never read as a rule source: things that happen or run, not rules. */\nconst SKIP_TYPES = new Set([\"event\", \"agent\", \"device\", \"server\", \"app\", \"domain\", \"account\", \"penalty\", \"relief\", \"due_date\", \"person\"])\n/** Types a rule's bearer may link to; anything else stays text. */\nconst BEARER_TYPES = new Set([\"person\", \"organization\"])\n\nconst PAGE_CHARS = 6000\nconst ENTRY_CHARS = 900\nconst clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s)\nconst str = (v: unknown): string => (typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\")\n/** Frontmatter keeps a title on one quoted line. */\nconst cleanTitle = (s: string) => str(s).replace(/[\"\\[\\]]/g, \"\").slice(0, 120).trim()\n\nexport function ruleWordsPattern(words: string[] = DEFAULT_RULE_WORDS): RegExp {\n const escaped = words.map(w => w.trim().replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).filter(Boolean)\n return new RegExp(`(^|[^\\\\p{L}\\\\p{N}])(${escaped.join(\"|\")})`, \"iu\")\n}\n\nexport interface RulesContext {\n /** The entity whose page is read. */\n source: Entity\n page: GraphPage\n entries: WikiEntry[]\n /** Obligation pages that already exist, so a known rule is updated, not doubled. */\n known: Entity[]\n /** Legal source pages a rule may cite as its basis. */\n laws: Entity[]\n /** People and organizations the page links or names. */\n parties: Entity[]\n /** Organizations a rule may name as its authority. */\n authorities: Entity[]\n}\n\nexport interface RuleDraft {\n title: string\n /** Set when the rule matches an existing obligation page. */\n existing?: Entity\n action: string\n bearers: string[]\n deadline: string\n amount: string\n authority: string\n penalty: string\n basis: string\n procedure: string\n source: string\n}\n\nexport interface RulesResult {\n rules: RuleDraft[]\n dropped: string[]\n}\n\n/** True when the page reads like it states a rule. */\nexport function statesRules(page: GraphPage, words: RegExp): boolean {\n return words.test(`${page.article.meta.title}\\n${bodyOf(page.article.content)}`)\n}\n\n/**\n * Entities whose page this job reads: legal sources and obligation pages\n * first, then any other page whose text matches the rule words. Pages\n * this job created are skipped.\n */\nexport function ruleSources(g: WikiGraph, words: RegExp, only: string[] = []): Entity[] {\n const wanted = new Set(only.map(normName))\n const ours = (e: Entity) => e.pages.every(p => (p.article.meta.tags ?? []).includes(RULES_TAG))\n const rank = (e: Entity) => (e.type === \"legal_source\" ? 0 : e.type === \"obligation\" ? 1 : 2)\n return [...g.entities.values()]\n .filter(e => !ours(e))\n .filter(e => wanted.size\n ? wanted.has(normName(e.id)) || wanted.has(normName(e.title))\n : e.type === \"legal_source\" || e.type === \"obligation\" || (!SKIP_TYPES.has(e.type) && e.pages.some(p => statesRules(p, words))))\n .sort((a, b) => rank(a) - rank(b) || b.sources.length - a.sources.length || a.title.localeCompare(b.title))\n}\n\n/** Entities of a type whose title appears in the text, or linked to `e`. */\nfunction partiesOf(g: WikiGraph, e: Entity, text: string, types: Set<string>): Entity[] {\n const hay = ` ${normName(text)} `\n const linked = new Set([...(g.outgoing.get(e.id) ?? []).map(x => x.to), ...(g.incoming.get(e.id) ?? []).map(x => x.from)])\n return [...g.entities.values()]\n .filter(x => types.has(x.type) && x.id !== e.id)\n .filter(x => linked.has(x.id) || (normName(x.title).length >= 3 && hay.includes(` ${normName(x.title)} `)))\n .slice(0, 40)\n}\n\n/** What one call for `source` may read: its page and the entries behind it. */\nexport function rulesContext(g: WikiGraph, source: Entity, page: GraphPage, readEntries: (ids: string[]) => WikiEntry[]): RulesContext {\n const text = `${page.article.meta.title}\\n${bodyOf(page.article.content)}`\n const entries = readEntries(page.article.meta.sources ?? []).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 10)\n const all = `${text}\\n${entries.map(x => x.content).join(\"\\n\")}`\n const visible = (x: Entity) => x.pages.some(p => readableAlongside(p.article.meta, page.article.meta))\n const of = (type: string) => [...g.entities.values()].filter(x => x.type === type && x.id !== source.id && visible(x))\n return {\n source,\n page,\n entries,\n known: of(\"obligation\").slice(0, 60),\n laws: of(\"legal_source\").slice(0, 40),\n parties: partiesOf(g, source, all, BEARER_TYPES).filter(visible),\n authorities: partiesOf(g, source, all, new Set([\"organization\"])).filter(visible),\n }\n}\n\n/** Changes when the source page's text or the entries behind it change.\n * A `subject_to` link this job adds to the page does not change it. */\nexport function rulesFingerprint(page: GraphPage): string {\n const parts = [`${page.agentId}/${page.article.path}`, bodyOf(page.article.content), ...(page.article.meta.sources ?? []).slice().sort()]\n return createHash(\"sha1\").update(parts.join(\"\\n\")).digest(\"hex\").slice(0, 16)\n}\n\nfunction knownLine(g: WikiGraph, e: Entity): string {\n const facts = e.statements.filter(s => [\"action\", \"due_rule\"].includes(s.property)).map(s => `${s.property}: ${s.value}`)\n return `- ${e.title}${facts.length ? ` (${facts.join(\"; \")})` : \"\"}`\n}\n\nexport function buildRulesPrompt(g: WikiGraph, ctx: RulesContext, today: string): string {\n const p = ctx.page\n const lines = [\n `You are writing the rules one wiki page states, so nobody has to research them again. Today is ${today}.`,\n \"\",\n `## The page: ${p.agentId}/${p.article.path}: \"${p.article.meta.title}\"`,\n clip(bodyOf(p.article.content), PAGE_CHARS),\n \"\",\n \"## Source entries behind the page (newest first)\",\n ]\n for (const en of ctx.entries) lines.push(`### entry ${en.id} (${en.date}, ${en.agentId})`, clip(en.content.trim(), ENTRY_CHARS), \"\")\n lines.push(\"## Rule pages that already exist\", ...ctx.known.map(e => knownLine(g, e)), \"\")\n lines.push(\"## Legal source pages\", ...ctx.laws.map(e => `- ${e.title}`), \"\")\n lines.push(\"## People and organizations it names\", ...ctx.parties.map(e => `- ${e.title} (${e.type})`), \"\")\n lines.push(\n \"## Task\",\n \"List each rule the page or the entries state: something a person or organization must do, by a deadline or on a schedule, often with a penalty when they do not.\",\n \"Return one JSON object and nothing else:\",\n `{\"rules\": [{\"title\": \"…\", \"action\": \"…\", \"bearer\": [\"…\"], \"deadline\": \"…\", \"amount\": \"…\", \"authority\": \"…\", \"penalty\": \"…\", \"basis\": \"…\", \"procedure\": \"…\", \"source\": \"…\"}]}`,\n \"\",\n \"Rules:\",\n \"- title: a short name for the rule, such as \\\"Monthly payroll tax filing\\\". When it is one of the rule pages that already exist, use that title exactly.\",\n \"- action: what must be done, in one sentence. A rule without one is dropped.\",\n \"- bearer: who must do it. Use a listed person or organization title when it is one, else a short description such as \\\"every employer\\\".\",\n \"- deadline: when, as the rule says it (\\\"by the 15th of the following month\\\"), not a computed date.\",\n \"- amount: what is paid or declared, if the rule says. authority: who it is filed with or paid to.\",\n \"- penalty: what happens when it is late or missing, as stated.\",\n \"- basis: the law, article or document it comes from. Use a listed legal source title when it is one.\",\n \"- procedure: how it is done, in one sentence, if stated.\",\n \"- source: the entry id or the page (agent/path) the rule comes from. A rule without one is dropped.\",\n \"- Leave a field empty when the page and entries do not state it. Never guess a deadline, an amount or a penalty.\",\n \"- Do not list one-time tasks, reminders or plans; only standing rules.\",\n \"- Write in the language the page is written in.\",\n \"- No rules on the page: return {\\\"rules\\\": []}.\",\n )\n return lines.join(\"\\n\")\n}\n\n/** Keep only rules with an action and a source the call was shown. */\nexport function checkRules(raw: Record<string, unknown>, ctx: RulesContext, g: WikiGraph): RulesResult {\n const dropped: string[] = []\n const p = ctx.page\n const sourceIds = [...ctx.entries.map(x => x.id), `${p.agentId}/${p.article.path}`, p.article.path]\n const known = new Map(ctx.known.map(e => [normName(e.title), e]))\n const rules: RuleDraft[] = []\n const seen = new Set<string>()\n for (const item of Array.isArray(raw.rules) ? raw.rules : []) {\n const r = (item ?? {}) as Record<string, unknown>\n const title = cleanTitle(str(r.title))\n const action = clip(str(r.action), 400)\n const source = str(r.source)\n if (!title) { dropped.push(\"a rule with no title\"); continue }\n if (!action) { dropped.push(`${title}: no action`); continue }\n if (!source || !sourceIds.some(id => source.includes(id))) { dropped.push(`${title}: source not among those given`); continue }\n if (seen.has(normName(title))) continue\n seen.add(normName(title))\n const existing = known.get(normName(title))\n const taken = g.names.get(normName(title))\n const clash = !existing && taken ? g.entities.get(taken) : undefined\n if (clash && clash.type !== \"obligation\") { dropped.push(`${title}: a page of type ${clash.type} already has this title`); continue }\n const bearers = (Array.isArray(r.bearer) ? r.bearer : [r.bearer]).map(b => clip(str(b), 120)).filter(Boolean)\n rules.push({\n title: existing?.title ?? clash?.title ?? title,\n existing: existing ?? clash,\n action,\n bearers: [...new Set(bearers)].slice(0, 5),\n deadline: clip(str(r.deadline), 200),\n amount: clip(str(r.amount), 200),\n authority: clip(str(r.authority), 120),\n penalty: clip(str(r.penalty), 300),\n basis: clip(str(r.basis), 200),\n procedure: clip(str(r.procedure), 400),\n source: clip(source, 200),\n })\n }\n return { rules, dropped }\n}\n\n/** The title of a listed page when `value` names one, else the value. */\nfunction asPage(value: string, list: Entity[]): string {\n const hit = list.find(e => normName(e.title) === normName(value))\n return hit?.title ?? value\n}\n\n/**\n * The date of what the rule was read from: the entry it cites, else the\n * newest entry behind the page, else the day the page was created. Never\n * the run date: nothing was checked at the law or the authority.\n */\nexport function sourceDate(r: Pick<RuleDraft, \"source\">, ctx: RulesContext): string | undefined {\n const day = (d?: string) => (d && /^\\d{4}-\\d{2}-\\d{2}/.test(d) ? d.slice(0, 10) : undefined)\n const cited = ctx.entries.filter(x => r.source.includes(x.id)).map(x => day(x.date)).filter(Boolean).sort()\n return cited.at(-1) ?? day(ctx.entries[0]?.date) ?? day(ctx.page.article.meta.created)\n}\n\n/** Statements an obligation page gets for one rule, proposed until the owner confirms them. */\nexport function ruleStatements(r: RuleDraft, ctx: RulesContext): WikiStatement[] {\n const checked = sourceDate(r, ctx)\n const st = (property: string, value: string): WikiStatement => ({\n property, value, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\", by: RULES_BY,\n })\n const out = [st(\"action\", r.action)]\n for (const b of r.bearers) out.push(st(\"bearer\", asPage(b, ctx.parties)))\n if (r.deadline) out.push(st(\"due_rule\", r.deadline))\n if (r.amount) out.push(st(\"amount_rule\", r.amount))\n if (r.authority) out.push(st(\"authority\", asPage(r.authority, ctx.authorities)))\n out.push(st(\"created_by\", r.basis ? asPage(r.basis, ctx.laws) : ctx.page.article.meta.title))\n if (r.procedure) out.push(st(\"procedure\", r.procedure))\n return out\n}\n\n/** Properties a rule holds one value of; `bearer` may hold several. */\nconst SINGLE = new Set([\"action\", \"due_rule\", \"amount_rule\", \"authority\", \"created_by\", \"procedure\"])\n\n/**\n * This job's statements for a rule after reading one more source: a\n * field the new source states replaces the earlier one; a field it leaves\n * empty keeps the earlier value with its own source and date. A basis the\n * new source does not name (`created_by` set to the page read) does not\n * replace a law an earlier source named. Bearers add up.\n */\nexport function mergeRuleStatements(earlier: WikiStatement[], fresh: WikiStatement[], r: Pick<RuleDraft, \"basis\">): WikiStatement[] {\n const prev = earlier.filter(s => s.by === RULES_BY)\n const stated = new Set(fresh.filter(s => s.property !== \"created_by\" || r.basis || !prev.some(p => p.property === \"created_by\")).map(s => s.property))\n const out = fresh.filter(s => stated.has(s.property))\n for (const s of prev) {\n if (SINGLE.has(s.property) ? !stated.has(s.property) : !out.some(o => o.property === s.property && normName(o.value) === normName(s.value))) out.push(s)\n }\n return out\n}\n\n/** Statements merged in: this job's earlier ones replaced, others kept. A\n * statement the owner confirmed stays, and wins over a new value. */\nexport function withRuleStatements(meta: WikiArticleMeta, statements: WikiStatement[], today: string): WikiArticleMeta {\n const kept = (meta.statements ?? []).filter(s => s.by !== RULES_BY || s.status === \"confirmed\")\n const confirmed = new Set(kept.filter(s => s.status === \"confirmed\" && SINGLE.has(s.property)).map(s => s.property))\n const key = (s: WikiStatement) => `${s.property}\\n${normName(s.value)}`\n const taken = new Set(kept.map(key))\n const all = [...kept, ...statements.filter(s => !confirmed.has(s.property) && !taken.has(key(s)))]\n return { ...meta, statements: all.length ? all : undefined, lastUpdated: today }\n}\n\n/** A penalty as stated, with where it was read and that source's date. */\nexport interface PenaltyFact {\n value: string\n source?: string\n checked_at?: string\n /** The owner confirmed it: it wins over what a new source states. */\n confirmed?: boolean\n}\n\nconst missing = \"not found in the sources yet\"\n\n/** The plain-words summary at the top of an obligation page, built from\n * the statements the page holds after the merge. */\nexport function ruleOverview(statements: WikiStatement[], penalty: PenaltyFact | undefined, readFrom: string): string {\n const all = (p: string) => statements.filter(s => s.property === p)\n const one = (p: string) => statements.find(s => s.property === p)\n const action = one(\"action\")\n // A field read from another source than the action says which.\n const from = (s?: { source?: string; checked_at?: string }) =>\n s && s.source && s.source !== action?.source ? ` (from ${s.source}${s.checked_at ? `, ${s.checked_at}` : \"\"})` : \"\"\n const line = (label: string, s?: WikiStatement) => `- **${label}:** ${s ? `${s.value}${from(s)}` : missing}`\n const sources = [...new Set([...statements, ...(penalty ? [penalty] : [])].map(s => s.source).filter((x): x is string => !!x))]\n const dates = [...statements.filter(s => [\"action\", \"due_rule\"].includes(s.property)), ...(penalty ? [penalty] : [])]\n .map(s => s.checked_at).filter((x): x is string => !!x).sort()\n const basis = one(\"created_by\")?.value\n return [\n line(\"What to do\", action),\n `- **Who:** ${all(\"bearer\").length ? all(\"bearer\").map(s => s.value).join(\", \") : missing}`,\n line(\"Deadline\", one(\"due_rule\")),\n ...(one(\"amount_rule\") ? [line(\"Amount\", one(\"amount_rule\"))] : []),\n ...(one(\"authority\") ? [line(\"Filed with\", one(\"authority\"))] : []),\n `- **Penalty:** ${penalty ? `${penalty.value}${from(penalty)}` : missing}`,\n `- **Source:** ${basis ? `${basis}, ` : \"\"}last read from [[${readFrom}]]${sources.length ? ` (sources: ${sources.join(\", \")})` : \"\"}`,\n `- **Source date:** ${dates[0] ?? \"not known\"}. Not yet checked with the law or the authority.`,\n ].join(\"\\n\")\n}\n\nconst SUMMARY_HEAD = \"## Rule summary\"\nconst SUMMARY_END = \"<!-- /rule-summary -->\"\n\n/**\n * The summary on a page this job did not create. It goes in its own\n * section, which only this job rewrites, so the page's own Overview is\n * never replaced.\n */\nexport function withRuleSummary(content: string, summary: string): string {\n const section = `${SUMMARY_HEAD}\\n\\n${summary.trim()}\\n\\n${SUMMARY_END}\\n`\n const start = content.indexOf(`${SUMMARY_HEAD}\\n`)\n const end = start < 0 ? -1 : content.indexOf(SUMMARY_END, start)\n if (start >= 0 && end >= 0) return `${content.slice(0, start)}${section}${content.slice(end + SUMMARY_END.length).replace(/^\\n/, \"\")}`\n return `${section}\\n${content.trim()}\\n`\n}\n\nexport interface RulesState {\n sources: Record<string, { fingerprint: string; at: string; costUsd?: number; failures?: number }>\n}\n\nexport function loadRulesState(wikiDir: string): RulesState {\n const file = resolve(wikiDir, \"_rules\", \"state.json\")\n if (!existsSync(file)) return { sources: {} }\n try {\n const v = JSON.parse(readFileSync(file, \"utf-8\"))\n return v && typeof v.sources === \"object\" ? v : { sources: {} }\n } catch {\n return { sources: {} }\n }\n}\n\nexport function saveRulesState(wikiDir: string, state: RulesState): void {\n mkdirSync(resolve(wikiDir, \"_rules\"), { recursive: true })\n writeFileSync(resolve(wikiDir, \"_rules\", \"state.json\"), JSON.stringify(state, null, 2))\n}\n\nexport interface RulesOptions {\n /** Entity ids or titles; empty means every page that states rules. */\n only: string[]\n words: RegExp\n max: number\n maxCostUsd: number\n dryRun: boolean\n force: boolean\n today: string\n save?: (state: RulesState) => void\n}\n\nexport interface RuleWrite {\n title: string\n /** agent/path of the obligation page. */\n page: string\n created: boolean\n deadline: boolean\n penalty: boolean\n /** Bearer pages that got a `subject_to` link. */\n linked: string[]\n /** Dry runs: the summary that would be written. */\n preview?: string\n}\n\nexport interface RulesOutcome {\n source: string\n title: string\n page?: string\n status: \"written\" | \"dry-run\" | \"unchanged\" | \"no-page\" | \"no-reply\" | \"no-rules\" | \"failed\"\n rules: RuleWrite[]\n costUsd: number\n dropped: string[]\n}\n\nexport interface RulesRun {\n outcomes: RulesOutcome[]\n costUsd: number\n capped: boolean\n}\n\ninterface Target {\n agentId: string\n path: string\n meta: WikiArticleMeta\n content: string\n created: boolean\n}\n\n/**\n * Where a rule is written: the existing obligation page when one is\n * owned here and no wider audience than the source can read it, else a\n * new page in the source page's wiki with the source page's access.\n */\nfunction ruleTarget(hub: WikiHub, r: RuleDraft, ctx: RulesContext, made: Map<string, Target>, today: string): Target | string {\n const src = ctx.page\n const again = made.get(normName(r.title))\n if (again) return readableAlongside(src.article.meta, again.meta) ? again : \"the rule page is readable by agents who cannot read the source\"\n if (r.existing) {\n const page = targetPage(hub, r.existing)\n if (!page) return \"the rule page was copied from another machine\"\n if (!readableAlongside(src.article.meta, page.article.meta)) return \"the rule page is readable by agents who cannot read the source\"\n return { agentId: page.agentId, path: page.article.path, meta: page.article.meta, content: page.article.content, created: false }\n }\n const owner = src.article.meta.owner || src.agentId\n const store = hub.getAgentWiki(src.agentId)\n let path = `obligations/${slugify(r.title)}.md`\n for (let n = 2; store.readArticle(path); n++) path = `obligations/${slugify(r.title)}-${n}.md`\n const meta: WikiArticleMeta = {\n title: r.title, class: \"obligation\", tags: [RULES_TAG], owner, access: src.article.meta.access,\n sharedWith: src.article.meta.sharedWith, created: today, lastUpdated: today, sources: [],\n }\n return { agentId: src.agentId, path, meta, content: `${r.title}.\\n`, created: true }\n}\n\n/**\n * The target as it is on disk now. The run waited for the model, so the\n * write merges onto this, not the copy read at the start. Called holding\n * the page's lock when writing.\n */\nfunction onDisk(hub: WikiHub, t: Target, src: WikiArticleMeta): Target | string {\n const now = hub.getAgentWiki(t.agentId).readArticle(t.path)\n if (t.created) return now ? \"a page was created at the rule's path during the run\" : t\n if (!now) return \"the rule page was moved or removed during the run\"\n if (!readableAlongside(src, now.meta)) return \"the rule page is readable by agents who cannot read the source\"\n return { ...t, meta: now.meta, content: now.content }\n}\n\n/**\n * Run `fn` holding the page's lock, so no other write lands between its\n * re-read and its write. Returns why nothing was written, if so; a busy\n * lock is one such reason.\n */\nfunction locked(hub: WikiHub, agentId: string, path: string, fn: () => string | undefined): string | undefined {\n try {\n return hub.getAgentWiki(agentId).withArticleLock(path, fn)\n } catch (err) {\n if (!(err instanceof LockBusyError)) throw err\n return \"the page was busy; run again\"\n }\n}\n\nconst confirmedPenalty = (m: WikiArticleMeta) => (m.statements ?? []).some(s => s.property === \"amount_rule\" && s.status === \"confirmed\")\n\nconst penaltyPath = (title: string) => `penalties/${slugify(cleanTitle(`${title} penalty`))}.md`\n\n/**\n * The penalty a rule already has: on the page this job wrote for it, else\n * on any penalty page linked to it with `penalty_for`. A confirmed\n * statement is preferred over a proposed one on the same page.\n */\nexport function knownPenalty(hub: WikiHub, g: WikiGraph, title: string, t: Pick<Target, \"agentId\" | \"meta\">): PenaltyFact | undefined {\n const fact = (statements?: WikiStatement[]): PenaltyFact | undefined => {\n const all = (statements ?? []).filter(x => x.property === \"amount_rule\" && x.value)\n const s = all.find(x => x.status === \"confirmed\") ?? all[0]\n return s ? { value: s.value, source: s.source, checked_at: s.checked_at, ...(s.status === \"confirmed\" ? { confirmed: true } : {}) } : undefined\n }\n const own = hub.getAgentWiki(t.agentId).readArticle(penaltyPath(title))\n if (own && (own.meta.tags ?? []).includes(RULES_TAG)) return fact(own.meta.statements)\n for (const e of g.entities.values()) {\n if (e.type !== \"penalty\" || !e.statements.some(s => s.property === \"penalty_for\" && normName(s.value) === normName(title))) continue\n const page = e.pages.find(p => readableAlongside(t.meta, p.article.meta))\n const f = page && fact(page.article.meta.statements)\n if (f) return f\n }\n return undefined\n}\n\nfunction penaltyPage(r: RuleDraft, t: Target, ctx: RulesContext, today: string): { path: string; meta: WikiArticleMeta; content: string } {\n const title = cleanTitle(`${r.title} penalty`)\n const checked = sourceDate(r, ctx)\n const st = (property: string, value: string): WikiStatement => ({\n property, value, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\", by: RULES_BY,\n })\n const statements = [st(\"penalty_for\", r.title), st(\"amount_rule\", r.penalty), st(\"created_by\", r.basis ? asPage(r.basis, ctx.laws) : ctx.page.article.meta.title)]\n return {\n path: penaltyPath(r.title),\n meta: {\n title, class: \"penalty\", tags: [RULES_TAG], owner: t.meta.owner, access: t.meta.access, sharedWith: t.meta.sharedWith,\n created: today, lastUpdated: today, sources: t.meta.sources, statements, related: [r.title],\n },\n content: `## Overview\\n\\n${r.penalty}\\n\\nFor [[${r.title}]]. Source: ${r.source}${checked ? `, dated ${checked}` : \"\"}. Not yet checked with the law or the authority.\\n`,\n }\n}\n\n/** Add `subject_to` to each bearer's page that may show the rule. */\nfunction linkBearers(hub: WikiHub, r: RuleDraft, ctx: RulesContext, t: Target, dryRun: boolean, dropped: string[]): string[] {\n const linked: string[] = []\n for (const b of r.bearers) {\n const e = ctx.parties.find(x => normName(x.title) === normName(b))\n if (!e) continue\n const page = targetPage(hub, e)\n if (!page) { dropped.push(`${r.title} → ${e.title}: page copied from another machine`); continue }\n // The link shows the rule's title on the bearer's page.\n if (!readableAlongside(t.meta, page.article.meta)) { dropped.push(`${r.title} → ${e.title}: page readable by agents who cannot read the rule`); continue }\n const linkedTo = (m: WikiArticleMeta) => (m.statements ?? []).some(s => s.property === \"subject_to\" && normName(s.value) === normName(r.title))\n if (linkedTo(page.article.meta)) continue\n if (dryRun) { linked.push(e.title); continue }\n // Write onto the page as it is now, not the copy read at the start,\n // holding its lock from the re-read to the write.\n const store = hub.getAgentWiki(page.agentId)\n let wrote = false\n const why = locked(hub, page.agentId, page.article.path, () => {\n const now = store.readArticle(page.article.path)\n if (!now) return \"page moved or removed during the run\"\n if (!readableAlongside(t.meta, now.meta)) return \"page readable by agents who cannot read the rule\"\n if (linkedTo(now.meta)) return undefined\n const checked = sourceDate(r, ctx)\n const statements = [...(now.meta.statements ?? []), { property: \"subject_to\", value: r.title, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\" as const, by: RULES_BY }]\n // A link added is not an edit of the page: `lastUpdated` stays.\n const meta = { ...now.meta, statements }\n if (!store.writeArticle(page.article.path, meta, now.content, now.meta.owner || page.agentId)) return \"write refused\"\n page.article.meta = meta\n wrote = true\n return undefined\n })\n if (why) dropped.push(`${r.title} → ${e.title}: ${why}`)\n else if (wrote) linked.push(e.title)\n }\n return linked\n}\n\nexport async function runRules(hub: WikiHub, g: WikiGraph, call: EnrichCall, opts: RulesOptions, state: RulesState): Promise<RulesRun> {\n const failures = (e: Entity) => state.sources[e.id]?.failures ?? 0\n const candidates = ruleSources(g, opts.words, opts.only).sort((a, b) => failures(a) - failures(b))\n const readEntries = (ids: string[]) => hub.getSharedStore().readEntries(ids)\n const run: RulesRun = { outcomes: [], costUsd: 0, capped: false }\n const made = new Map<string, Target>()\n let calls = 0\n const remember = (id: string, fp: string, costUsd: number, failed = false) => {\n if (opts.dryRun) return\n const prev = state.sources[id]\n state.sources[id] = failed\n ? { fingerprint: prev?.fingerprint ?? \"\", at: new Date().toISOString(), costUsd, failures: (prev?.failures ?? 0) + 1 }\n : { fingerprint: fp, at: new Date().toISOString(), costUsd }\n opts.save?.(state)\n }\n\n for (const e of candidates) {\n if (calls >= opts.max) break\n const base = { source: e.id, title: e.title, rules: [] as RuleWrite[], costUsd: 0, dropped: [] as string[] }\n const page = targetPage(hub, e)\n if (!page) { if (opts.only.length) run.outcomes.push({ ...base, status: \"no-page\" }); continue }\n const ctx = rulesContext(g, e, page, readEntries)\n let fp = rulesFingerprint(page)\n if (!opts.force && state.sources[e.id]?.fingerprint === fp) {\n if (opts.only.length) run.outcomes.push({ ...base, status: \"unchanged\" })\n continue\n }\n if (run.costUsd >= opts.maxCostUsd) { run.capped = true; break }\n\n calls++\n const where = `${page.agentId}/${page.article.path}`\n let reply: { text: string; costUsd: number }\n try {\n reply = await call(buildRulesPrompt(g, ctx, opts.today))\n } catch (err) {\n run.outcomes.push({ ...base, page: where, status: \"failed\", dropped: [(err as Error).message.slice(0, 200)] })\n remember(e.id, fp, 0, true)\n continue\n }\n run.costUsd += reply.costUsd\n const outcome: RulesOutcome = { ...base, page: where, status: \"no-reply\", costUsd: reply.costUsd }\n const parsed = parseEnrichReply(reply.text)\n if (!parsed) { run.outcomes.push(outcome); remember(e.id, fp, reply.costUsd); continue }\n const checked = checkRules(parsed, ctx, g)\n outcome.dropped = checked.dropped\n if (checked.rules.length === 0) {\n outcome.status = \"no-rules\"\n run.outcomes.push(outcome)\n remember(e.id, fp, reply.costUsd)\n continue\n }\n\n let failed = false\n for (const r of checked.rules) {\n const t0 = ruleTarget(hub, r, ctx, made, opts.today)\n if (typeof t0 === \"string\") { outcome.dropped.push(`${r.title}: ${t0}`); continue }\n const compose = (t: Target) => {\n // What an earlier source stated stays when this one leaves it out.\n const statements = mergeRuleStatements(t.meta.statements ?? [], ruleStatements(r, ctx), r)\n const meta0 = withRuleStatements(t.meta, statements, opts.today)\n // A penalty the owner confirmed wins, as on the rule page itself.\n const known = knownPenalty(hub, g, r.title, t)\n const penalty = known?.confirmed || !r.penalty ? known : { value: r.penalty, source: r.source, checked_at: sourceDate(r, ctx) }\n const summary = ruleOverview(meta0.statements ?? [], penalty, page.article.meta.title)\n // A page this job did not create keeps its own Overview.\n const ours = (t.meta.tags ?? []).includes(RULES_TAG)\n const content = ours ? withOverview(t.content, summary) : withRuleSummary(t.content, summary)\n const related = [...new Set([...(t.meta.related ?? []), page.article.meta.title, ...(penalty ? [cleanTitle(`${r.title} penalty`)] : [])])]\n const sources = [...new Set([...(t.meta.sources ?? []), ...ctx.entries.filter(x => r.source.includes(x.id)).map(x => x.id)])]\n const meta = { ...meta0, related, sources }\n const write: RuleWrite = {\n title: r.title, page: `${t.agentId}/${t.path}`, created: t.created,\n deadline: (meta.statements ?? []).some(s => s.property === \"due_rule\"), penalty: !!penalty, linked: [],\n }\n return { t, meta, content, summary, known, write }\n }\n if (opts.dryRun) {\n const t = onDisk(hub, t0, ctx.page.article.meta)\n if (typeof t === \"string\") { outcome.dropped.push(`${r.title}: ${t}`); continue }\n const c = compose(t)\n c.write.preview = c.summary\n c.write.linked = linkBearers(hub, r, ctx, t, true, outcome.dropped)\n outcome.rules.push(c.write)\n continue\n }\n // Re-read, merge and write the rule page holding its lock.\n let c: ReturnType<typeof compose> | undefined\n const why = locked(hub, t0.agentId, t0.path, () => {\n const t = onDisk(hub, t0, ctx.page.article.meta)\n if (typeof t === \"string\") return t\n const next = compose(t)\n if (!hub.getAgentWiki(t.agentId).writeArticle(t.path, next.meta, next.content, t.meta.owner || t.agentId)) return \"write refused\"\n c = next\n return undefined\n })\n if (why || !c) {\n outcome.dropped.push(`${r.title}: ${why ?? \"write refused\"}`)\n failed = true\n continue\n }\n const { t, meta, content, known, write } = c\n const store = hub.getAgentWiki(t.agentId)\n made.set(normName(r.title), { ...t, meta, content, created: false })\n if (r.penalty && !known?.confirmed) {\n const pen = penaltyPage(r, { ...t, meta }, ctx, opts.today)\n const penWhy = locked(hub, t.agentId, pen.path, () => {\n const old = store.readArticle(pen.path)\n // A penalty page someone else wrote at that path is left alone; on\n // ours, statements the owner confirmed stay, and a penalty\n // confirmed during the run is kept as it is.\n if (!old) return store.writeArticle(pen.path, pen.meta, pen.content, pen.meta.owner) ? undefined : \"write refused\"\n if (!(old.meta.tags ?? []).includes(RULES_TAG)) return \"already exists\"\n if (confirmedPenalty(old.meta)) return undefined\n const merged = withRuleStatements({ ...pen.meta, created: old.meta.created, statements: old.meta.statements }, pen.meta.statements ?? [], opts.today)\n return store.writeArticle(pen.path, merged, pen.content, pen.meta.owner) ? undefined : \"write refused\"\n })\n if (penWhy) outcome.dropped.push(`${r.title}: ${pen.path} ${penWhy}`)\n }\n write.linked = linkBearers(hub, r, ctx, { ...t, meta }, false, outcome.dropped)\n store.rebuildIndex()\n outcome.rules.push(write)\n }\n outcome.status = opts.dryRun ? \"dry-run\" : outcome.rules.length ? \"written\" : failed ? \"failed\" : \"no-rules\"\n run.outcomes.push(outcome)\n // A rule written onto the source page itself changes its text; the\n // next run must not pay to read back what this one wrote.\n const now = opts.dryRun ? null : hub.getAgentWiki(page.agentId).readArticle(page.article.path)\n if (now) fp = rulesFingerprint({ agentId: page.agentId, article: now })\n remember(e.id, fp, reply.costUsd, failed && outcome.rules.length === 0)\n }\n return run\n}\n"],"mappings":"sUAmBA,OAAS,cAAAA,OAAkB,SAC3B,OAAS,cAAAC,GAAY,aAAAC,GAAW,gBAAAC,GAAc,iBAAAC,OAAqB,KACnE,OAAS,WAAAC,MAAe,OASjB,IAAMC,EAAW,aAEXC,EAAY,aAGZC,GAAqB,CAChC,WAAY,WAAY,SAAU,SAAU,WAAY,UAAW,QAAS,YAAa,WAAY,eACrG,cAAe,SAAU,aAAc,aAAc,aACrD,iBAAY,cAAe,WAAS,aAAW,SAAU,aAAc,iBAAe,aACtF,iCAAS,qBAAO,2BAAQ,iCAAS,0BACnC,EAGMC,GAAa,IAAI,IAAI,CAAC,QAAS,QAAS,SAAU,SAAU,MAAO,SAAU,UAAW,UAAW,SAAU,WAAY,QAAQ,CAAC,EAElIC,GAAe,IAAI,IAAI,CAAC,SAAU,cAAc,CAAC,EAEjDC,GAAa,IACbC,GAAc,IACdC,EAAO,CAACC,EAAWC,IAAeD,EAAE,OAASC,EAAI,GAAGD,EAAE,MAAM,EAAGC,C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AAE,YAAYA,EAAK,QAAQ,IAAI,EACzFsH,IAAK6B,EAAKvH,GAAiB,CAAE,QAAS5B,EAAK,QAAS,QAASsH,CAAI,CAAC,GACtE4B,EAAS1I,EAAE,GAAI2I,EAAIK,EAAM,QAASH,GAAUI,EAAQ,MAAM,SAAW,CAAC,EAExE,OAAOT,CACT","names":["createHash","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","RULES_BY","RULES_TAG","DEFAULT_RULE_WORDS","SKIP_TYPES","BEARER_TYPES","PAGE_CHARS","ENTRY_CHARS","clip","s","n","str","v","cleanTitle","ruleWordsPattern","words","escaped","w","statesRules","page","bodyOf","ruleSources","g","only","wanted","normName","ours","e","p","rank","a","b","partiesOf","text","types","hay","linked","x","rulesContext","source","readEntries","entries","all","visible","readableAlongside","of","type","rulesFingerprint","parts","createHash","knownLine","facts","buildRulesPrompt","ctx","today","lines","en","checkRules","raw","dropped","sourceIds","known","rules","seen","item","r","title","action","id","existing","taken","clash","bearers","asPage","value","list","sourceDate","day","d","ruleStatements","checked","st","property","out","SINGLE","mergeRuleStatements","earlier","fresh","prev","stated","o","withRuleStatements","meta","statements","kept","confirmed","key","missing","ruleOverview","penalty","readFrom","one","from","line","label","sources","dates","basis","SUMMARY_HEAD","SUMMARY_END","withRuleSummary","content","summary","section","start","end","loadRulesState","wikiDir","file","resolve","existsSync","readFileSync","saveRulesState","state","mkdirSync","writeFileSync","ruleTarget","hub","made","src","again","targetPage","owner","store","path","slugify","onDisk","now","locked","agentId","fn","err","LockBusyError","confirmedPenalty","m","penaltyPath","knownPenalty","t","fact","own","f","penaltyPage","linkBearers","dryRun","linkedTo","wrote","why","runRules","call","opts","failures","candidates","ids","run","calls","remember","fp","costUsd","failed","base","where","reply","outcome","parsed","parseEnrichReply","t0","compose","meta0","withOverview","related","write","c","next","pen","penWhy","old","merged"]}
@@ -1,2 +1,2 @@
1
- import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-C43E3YFT.js";import{a}from"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import{d as c}from"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
2
- //# sourceMappingURL=wiki-ZS6OHOWQ.js.map
1
+ import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-4AFA6LQZ.js";import{a}from"./chunk-G26UHWS4.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import{d as c}from"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
2
+ //# sourceMappingURL=wiki-ZQMDUXTE.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b}from"./chunk-QW3L5IIC.js";import"./chunk-QIJLFPWE.js";export{a as claudeCall,b as registerWikiEnrich};
2
+ //# sourceMappingURL=wiki-enrich-NPNOSTRM.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.136.0",
3
+ "version": "0.136.1",
4
4
  "description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -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 }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,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"]}