agentix-cli 0.132.0 → 0.134.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-VPYWOTTH.js → App-4UVAI5C5.js} +2 -2
- package/dist/{ChatApp-SNED4KJB.js → ChatApp-COO67WIR.js} +2 -2
- package/dist/absorb-eval-WU7JR3BT.js +2 -0
- package/dist/{agent-HXQYYLWZ.js → agent-2GPJGHHG.js} +2 -2
- package/dist/{board-dashboard-44JPXA7J.js → board-dashboard-PUQPL4AX.js} +376 -257
- package/dist/board-dashboard-PUQPL4AX.js.map +1 -0
- package/dist/{chunk-RYGVTAP4.js → chunk-3XVST5XX.js} +2 -2
- package/dist/{note-reader-LPPIYYLT.js → chunk-4LWFJ4MZ.js} +3 -3
- package/dist/{note-reader-LPPIYYLT.js.map → chunk-4LWFJ4MZ.js.map} +1 -1
- package/dist/{chunk-724IBN5Y.js → chunk-4XMALK7X.js} +2 -2
- package/dist/{chunk-3WYLK3SX.js → chunk-AHO4CQRK.js} +2 -2
- package/dist/chunk-DDEDSYLF.js +105 -0
- package/dist/chunk-DDEDSYLF.js.map +1 -0
- package/dist/chunk-DYGQF3MI.js +54 -0
- package/dist/chunk-DYGQF3MI.js.map +1 -0
- package/dist/{chunk-ZG4G6BFP.js → chunk-ERULJ2ZL.js} +2 -2
- package/dist/chunk-FEEXOWK5.js +41 -0
- package/dist/chunk-FEEXOWK5.js.map +1 -0
- package/dist/{chunk-QNKSRROH.js → chunk-FWDRBUMS.js} +2 -2
- package/dist/chunk-G4HDRJVN.js +87 -0
- package/dist/chunk-G4HDRJVN.js.map +1 -0
- package/dist/{chunk-KQH4LPYC.js → chunk-K445URSN.js} +2 -2
- package/dist/{chunk-KDQI5S7F.js → chunk-LUYN6RAC.js} +2 -2
- package/dist/{chunk-JRVJXAVC.js → chunk-MM3F74K4.js} +31 -31
- package/dist/chunk-MM3F74K4.js.map +1 -0
- package/dist/{chunk-3K35L73A.js → chunk-NXRSIWQA.js} +3 -3
- package/dist/chunk-NXRSIWQA.js.map +1 -0
- package/dist/chunk-NZQBS7GN.js +2 -0
- package/dist/{chunk-KBJNJGBP.js.map → chunk-NZQBS7GN.js.map} +1 -1
- package/dist/{chunk-Z7RJ3K3J.js → chunk-P3I7AATX.js} +2 -2
- package/dist/{chunk-A6QJ4VFT.js → chunk-RDEFA6Y6.js} +2 -2
- package/dist/{chunk-VCQVF44A.js → chunk-RJOA7QBB.js} +2 -2
- package/dist/{chunk-JNKATLF7.js → chunk-RRGITX5B.js} +2 -2
- package/dist/chunk-SFVDQNTY.js +156 -0
- package/dist/chunk-SFVDQNTY.js.map +1 -0
- package/dist/{chunk-KKQPV6SO.js → chunk-SMAI7U6H.js} +2 -2
- package/dist/{chunk-MDGYSHO5.js → chunk-SSQMFHSM.js} +2 -2
- package/dist/{chunk-CM74OUXW.js → chunk-TDGDH4RA.js} +2 -2
- package/dist/chunk-URN74FTP.js +55 -0
- package/dist/chunk-URN74FTP.js.map +1 -0
- package/dist/{chunk-XWVBLISN.js → chunk-VQYVL72V.js} +2 -2
- package/dist/{chunk-UDMI4TYM.js → chunk-XOUO4XNA.js} +2 -2
- package/dist/{chunk-WWNZL7XB.js → chunk-XWO6ALJQ.js} +2 -2
- package/dist/{chunk-62NXS7PT.js → chunk-YSXE65O7.js} +246 -246
- package/dist/chunk-YSXE65O7.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-TXZF32NO.js → client-NFPBE6L4.js} +2 -2
- package/dist/config-GHMRBRDL.js +2 -0
- package/dist/{config-mutate-KDBXIN7R.js → config-mutate-2XV27EFV.js} +2 -2
- package/dist/config-mutator-6ITNU5DT.js +2 -0
- package/dist/{contributions-FBVULRR4.js → contributions-74M6YOCZ.js} +2 -2
- package/dist/{contributions-FBVULRR4.js.map → contributions-74M6YOCZ.js.map} +1 -1
- package/dist/{doctor-NBWYG743.js → doctor-UBXVMGJG.js} +2 -2
- package/dist/follow-up-tool-EARVITTS.js +7 -0
- package/dist/follow-up-tool-EARVITTS.js.map +1 -0
- package/dist/{hub-3QTJ7E3O.js → hub-VTDFUAEH.js} +2 -2
- package/dist/index.d.ts +1534 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/note-reader-IDE6RI34.js +2 -0
- package/dist/notes-settings-VPXI5IIS.js +2 -0
- package/dist/{program-SA5O6IQ3.js → program-3URNCVEZ.js} +253 -253
- package/dist/program-3URNCVEZ.js.map +1 -0
- package/dist/{promote-4XHYWHLA.js → promote-B2BADAEP.js} +2 -2
- package/dist/push-bridge-325SXDGN.js +1 -1
- package/dist/query-2VIIGGDS.js +2 -0
- package/dist/query-settings-VJ3POZS3.js +3 -0
- package/dist/query-settings-VJ3POZS3.js.map +1 -0
- package/dist/registry-PRCISYBO.js +2 -0
- package/dist/{request-planner-4BAAOUBH.js → request-planner-MFAIVLUQ.js} +2 -2
- package/dist/{review-candidates-TM53WR7G.js → review-candidates-6WMDVVIZ.js} +2 -2
- package/dist/{routing-QLS6UMLM.js → routing-OPCLHIYW.js} +2 -2
- package/dist/schedule-tool-KPVTMYL3.js +2 -0
- package/dist/{scheduler-PVXLF2VJ.js → scheduler-G3WWYETY.js} +2 -2
- package/dist/{seat-OUUN3F45.js → seat-3HM4J7IX.js} +2 -2
- package/dist/{select-D7UUSODY.js → select-VEFE2ESF.js} +2 -2
- package/dist/{set-enabled-FDNS6KW6.js → set-enabled-US5BYKFZ.js} +2 -2
- package/dist/{tool-J5FM3OPM.js → tool-HUSCHORN.js} +2 -2
- package/dist/{tool-SCBQYDI3.js → tool-XLWLXGB5.js} +2 -2
- package/dist/wiki-SXWJ5NJQ.js +2 -0
- package/dist/wiki-SXWJ5NJQ.js.map +1 -0
- package/package.json +2 -1
- package/dist/absorb-eval-WGO4JWTO.js +0 -2
- package/dist/board-dashboard-44JPXA7J.js.map +0 -1
- package/dist/chunk-2ZDV3DCT.js +0 -52
- package/dist/chunk-2ZDV3DCT.js.map +0 -1
- package/dist/chunk-3K35L73A.js.map +0 -1
- package/dist/chunk-62NXS7PT.js.map +0 -1
- package/dist/chunk-74LPAKQY.js +0 -105
- package/dist/chunk-74LPAKQY.js.map +0 -1
- package/dist/chunk-7D3RJSN4.js +0 -156
- package/dist/chunk-7D3RJSN4.js.map +0 -1
- package/dist/chunk-EQ33PFXP.js +0 -55
- package/dist/chunk-EQ33PFXP.js.map +0 -1
- package/dist/chunk-JRVJXAVC.js.map +0 -1
- package/dist/chunk-KBJNJGBP.js +0 -2
- package/dist/chunk-RH3J4LCP.js +0 -37
- package/dist/chunk-RH3J4LCP.js.map +0 -1
- package/dist/chunk-S2RRPTS3.js +0 -54
- package/dist/chunk-S2RRPTS3.js.map +0 -1
- package/dist/config-ZIXIH23X.js +0 -2
- package/dist/config-mutator-HKFGPJMG.js +0 -2
- package/dist/follow-up-tool-E5XKSPKA.js +0 -6
- package/dist/follow-up-tool-E5XKSPKA.js.map +0 -1
- package/dist/notes-settings-WMOH2V75.js +0 -2
- package/dist/program-SA5O6IQ3.js.map +0 -1
- package/dist/query-ZGD32CE2.js +0 -2
- package/dist/query-settings-BSDXFS3V.js +0 -3
- package/dist/query-settings-BSDXFS3V.js.map +0 -1
- package/dist/registry-LM35AE2P.js +0 -2
- package/dist/schedule-tool-TTCWBAQ4.js +0 -2
- package/dist/wiki-IGRRQL6H.js +0 -2
- /package/dist/{App-VPYWOTTH.js.map → App-4UVAI5C5.js.map} +0 -0
- /package/dist/{ChatApp-SNED4KJB.js.map → ChatApp-COO67WIR.js.map} +0 -0
- /package/dist/{absorb-eval-WGO4JWTO.js.map → absorb-eval-WU7JR3BT.js.map} +0 -0
- /package/dist/{agent-HXQYYLWZ.js.map → agent-2GPJGHHG.js.map} +0 -0
- /package/dist/{chunk-RYGVTAP4.js.map → chunk-3XVST5XX.js.map} +0 -0
- /package/dist/{chunk-724IBN5Y.js.map → chunk-4XMALK7X.js.map} +0 -0
- /package/dist/{chunk-3WYLK3SX.js.map → chunk-AHO4CQRK.js.map} +0 -0
- /package/dist/{chunk-ZG4G6BFP.js.map → chunk-ERULJ2ZL.js.map} +0 -0
- /package/dist/{chunk-QNKSRROH.js.map → chunk-FWDRBUMS.js.map} +0 -0
- /package/dist/{chunk-KQH4LPYC.js.map → chunk-K445URSN.js.map} +0 -0
- /package/dist/{chunk-KDQI5S7F.js.map → chunk-LUYN6RAC.js.map} +0 -0
- /package/dist/{chunk-Z7RJ3K3J.js.map → chunk-P3I7AATX.js.map} +0 -0
- /package/dist/{chunk-A6QJ4VFT.js.map → chunk-RDEFA6Y6.js.map} +0 -0
- /package/dist/{chunk-VCQVF44A.js.map → chunk-RJOA7QBB.js.map} +0 -0
- /package/dist/{chunk-JNKATLF7.js.map → chunk-RRGITX5B.js.map} +0 -0
- /package/dist/{chunk-KKQPV6SO.js.map → chunk-SMAI7U6H.js.map} +0 -0
- /package/dist/{chunk-MDGYSHO5.js.map → chunk-SSQMFHSM.js.map} +0 -0
- /package/dist/{chunk-CM74OUXW.js.map → chunk-TDGDH4RA.js.map} +0 -0
- /package/dist/{chunk-XWVBLISN.js.map → chunk-VQYVL72V.js.map} +0 -0
- /package/dist/{chunk-UDMI4TYM.js.map → chunk-XOUO4XNA.js.map} +0 -0
- /package/dist/{chunk-WWNZL7XB.js.map → chunk-XWO6ALJQ.js.map} +0 -0
- /package/dist/{client-TXZF32NO.js.map → client-NFPBE6L4.js.map} +0 -0
- /package/dist/{config-ZIXIH23X.js.map → config-GHMRBRDL.js.map} +0 -0
- /package/dist/{config-mutate-KDBXIN7R.js.map → config-mutate-2XV27EFV.js.map} +0 -0
- /package/dist/{config-mutator-HKFGPJMG.js.map → config-mutator-6ITNU5DT.js.map} +0 -0
- /package/dist/{doctor-NBWYG743.js.map → doctor-UBXVMGJG.js.map} +0 -0
- /package/dist/{hub-3QTJ7E3O.js.map → hub-VTDFUAEH.js.map} +0 -0
- /package/dist/{notes-settings-WMOH2V75.js.map → note-reader-IDE6RI34.js.map} +0 -0
- /package/dist/{promote-4XHYWHLA.js.map → notes-settings-VPXI5IIS.js.map} +0 -0
- /package/dist/{query-ZGD32CE2.js.map → promote-B2BADAEP.js.map} +0 -0
- /package/dist/{registry-LM35AE2P.js.map → query-2VIIGGDS.js.map} +0 -0
- /package/dist/{routing-QLS6UMLM.js.map → registry-PRCISYBO.js.map} +0 -0
- /package/dist/{request-planner-4BAAOUBH.js.map → request-planner-MFAIVLUQ.js.map} +0 -0
- /package/dist/{review-candidates-TM53WR7G.js.map → review-candidates-6WMDVVIZ.js.map} +0 -0
- /package/dist/{schedule-tool-TTCWBAQ4.js.map → routing-OPCLHIYW.js.map} +0 -0
- /package/dist/{scheduler-PVXLF2VJ.js.map → schedule-tool-KPVTMYL3.js.map} +0 -0
- /package/dist/{seat-OUUN3F45.js.map → scheduler-G3WWYETY.js.map} +0 -0
- /package/dist/{wiki-IGRRQL6H.js.map → seat-3HM4J7IX.js.map} +0 -0
- /package/dist/{select-D7UUSODY.js.map → select-VEFE2ESF.js.map} +0 -0
- /package/dist/{set-enabled-FDNS6KW6.js.map → set-enabled-US5BYKFZ.js.map} +0 -0
- /package/dist/{tool-J5FM3OPM.js.map → tool-HUSCHORN.js.map} +0 -0
- /package/dist/{tool-SCBQYDI3.js.map → tool-XLWLXGB5.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{pa as m,xa as b}from"./chunk-DYGQF3MI.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-3XVST5XX.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{existsSync as y,readdirSync as k,readFileSync as b,statSync as N}from"fs";import{resolve as $}from"path";var R=new Set(["memory.md"]);function D(n){let e={dir:n,notes:[],skipped:[]};if(!y(n))return e;for(let t of k(n).sort()){if(!t.endsWith(".md")||t.startsWith(".")||R.has(t.toLowerCase()))continue;let s=$(n,t),d;try{if(!N(s).isFile())continue;d=b(s,"utf-8")}catch(i){e.skipped.push({file:t,reason:`unreadable: ${i.message}`});continue}let o=S(d,t);o?e.notes.push(o):e.skipped.push({file:t,reason:"empty"})}return e.notes.sort((t,s)=>t.name.localeCompare(s.name)||t.file.localeCompare(s.file)),e}function S(n,e){let t=n.replace(/^/,"").replace(/\r\n/g,`
|
|
2
2
|
`),{fields:s,metadata:d,body:o}=A(t);if(!o.trim()&&Object.keys(s).length===0)return null;let i=p=>{let f=s[p]??d[p];return f&&f.trim()?f.trim():void 0},a=o.split(`
|
|
3
3
|
`).map(p=>p.replace(/^#+\s*/,"").trim()).find(Boolean)??"",r={name:i("name")??e.replace(/\.md$/,""),file:e,description:i("description")??a,body:o.trim(),missing:[],problems:[]},c=i("type");c&&(r.type=c);let g=i("updated")??i("created");g&&(r.updated=g);let l=i("source");l?r.source=l:r.missing.push("source");let u=i("checked"),m=u?w(u):void 0;return m?r.checked=m:(r.missing.push("checked"),u&&r.problems.push(`checked "${u}" is not a date (use YYYY-MM-DD)`)),r}function w(n){let e=n.match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ][\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/);if(!e)return;let t=`${e[1]}-${e[2]}-${e[3]}`,s=Date.parse(`${t}T00:00:00Z`);return Number.isFinite(s)&&new Date(s).toISOString().slice(0,10)===t?t:void 0}function A(n){let e={},t={};if(!n.startsWith(`---
|
|
4
4
|
`))return{fields:e,metadata:t,body:n};let s=n.indexOf(`
|
|
5
5
|
---`,4);if(s<0)return{fields:e,metadata:t,body:n};let d=n.indexOf(`
|
|
6
6
|
`,s+4),o=d<0?"":n.slice(d+1),i;for(let a of n.slice(4,s).split(`
|
|
7
|
-
`)){let r=a.match(/^\s+([A-Za-z_][\w-]*):\s*(.*)$/);if(r){i==="metadata"&&(t[r[1]]=h(r[2]));continue}let c=a.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(c){if(c[2].trim()===""){i=c[1];continue}i=void 0,e[c[1]]=h(c[2])}}return{fields:e,metadata:t,body:o}}function h(n){let e=n.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).replace(/''/g,"'"):e}export{
|
|
8
|
-
//# sourceMappingURL=
|
|
7
|
+
`)){let r=a.match(/^\s+([A-Za-z_][\w-]*):\s*(.*)$/);if(r){i==="metadata"&&(t[r[1]]=h(r[2]));continue}let c=a.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(c){if(c[2].trim()===""){i=c[1];continue}i=void 0,e[c[1]]=h(c[2])}}return{fields:e,metadata:t,body:o}}function h(n){let e=n.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e.length>=2&&e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).replace(/''/g,"'"):e}export{D as a,S as b};
|
|
8
|
+
//# sourceMappingURL=chunk-4LWFJ4MZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/note-reader.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Reading an agent's notes (#850) ---\n//\n// An agent's notes are small markdown files with frontmatter, one fact or\n// one current state each. They live in one of two places:\n//\n// - the AgentX note store, `.agentx/agent-memory/<agent>/<type>_<name>.md`\n// (src/agents/agent-memory.ts), with `name`, `description`, `type`,\n// `created` and `updated`;\n// - a notes folder another tool keeps, such as the one a `claude-code`\n// agent writes outside AgentX: `<name>.md` with `name`, `description`\n// and `type`, sometimes with extra fields under a `metadata:` block.\n//\n// Both are read the same way. Two more fields say whether a note can be\n// trusted as written: `source` (where it was checked) and `checked` (the\n// date it was checked). They are read from the top level or from under\n// `metadata:`, never guessed from the prose. A note without them is still\n// returned, with `missing` naming what it lacks.\n//\n// Read only: nothing here writes a note.\n\nexport type NoteField = \"source\" | \"checked\"\n\nexport interface AgentNote {\n /** Frontmatter `name`, else the file name without `.md`. */\n name: string\n /** File name inside the notes folder. */\n file: string\n /** `user`, `feedback`, `project`, `reference`, or what the file says. */\n type?: string\n /** One line saying what the note holds. */\n description: string\n body: string\n /** Where the note's content was checked. */\n source?: string\n /** When it was checked, YYYY-MM-DD. */\n checked?: string\n /** When the note was last written, as the file says. */\n updated?: string\n /** `source` and `checked`, when absent or unreadable. */\n missing: NoteField[]\n /** Why a field present in the file could not be used. */\n problems: string[]\n}\n\nexport interface NotesRead {\n dir: string\n notes: AgentNote[]\n /** Files that are not notes, with the reason. */\n skipped: Array<{ file: string; reason: string }>\n}\n\n/** The index files tools keep next to the notes; not notes themselves. */\nconst INDEX_FILES = new Set([\"memory.md\"])\n\n/**\n * Every note in `dir`, sorted by name. Only `*.md` files directly in the\n * folder are read; sub-folders (such as `_versions/`) and the `MEMORY.md`\n * index are not notes. A folder that does not exist reads as empty.\n */\nexport function readNotes(dir: string): NotesRead {\n const out: NotesRead = { dir, notes: [], skipped: [] }\n if (!existsSync(dir)) return out\n for (const file of readdirSync(dir).sort()) {\n if (!file.endsWith(\".md\") || file.startsWith(\".\") || INDEX_FILES.has(file.toLowerCase())) continue\n const path = resolve(dir, file)\n let raw: string\n try {\n if (!statSync(path).isFile()) continue\n raw = readFileSync(path, \"utf-8\")\n } catch (err) {\n out.skipped.push({ file, reason: `unreadable: ${(err as Error).message}` })\n continue\n }\n const note = parseNote(raw, file)\n if (note) out.notes.push(note)\n else out.skipped.push({ file, reason: \"empty\" })\n }\n out.notes.sort((a, b) => a.name.localeCompare(b.name) || a.file.localeCompare(b.file))\n return out\n}\n\n/**\n * One note from its file content. A file without frontmatter is still a\n * note: its first line is its description, and it has no source or check\n * date. Returns null for an empty file.\n */\nexport function parseNote(raw: string, file: string): AgentNote | null {\n const text = raw.replace(/^/, \"\").replace(/\\r\\n/g, \"\\n\")\n const { fields, metadata, body } = splitFrontmatter(text)\n if (!body.trim() && Object.keys(fields).length === 0) return null\n\n const pick = (key: string): string | undefined => {\n const v = fields[key] ?? metadata[key]\n return v && v.trim() ? v.trim() : undefined\n }\n const firstLine = body.split(\"\\n\").map((l) => l.replace(/^#+\\s*/, \"\").trim()).find(Boolean) ?? \"\"\n const note: AgentNote = {\n name: pick(\"name\") ?? file.replace(/\\.md$/, \"\"),\n file,\n description: pick(\"description\") ?? firstLine,\n body: body.trim(),\n missing: [],\n problems: [],\n }\n const type = pick(\"type\")\n if (type) note.type = type\n const updated = pick(\"updated\") ?? pick(\"created\")\n if (updated) note.updated = updated\n\n const source = pick(\"source\")\n if (source) note.source = source\n else note.missing.push(\"source\")\n\n const checkedRaw = pick(\"checked\")\n const checked = checkedRaw ? checkDate(checkedRaw) : undefined\n if (checked) note.checked = checked\n else {\n note.missing.push(\"checked\")\n if (checkedRaw) note.problems.push(`checked \"${checkedRaw}\" is not a date (use YYYY-MM-DD)`)\n }\n return note\n}\n\n/** YYYY-MM-DD from a date or an ISO date and time; undefined otherwise. */\nfunction checkDate(v: string): string | undefined {\n const m = v.match(/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ][\\d:.]+(?:Z|[+-]\\d{2}:?\\d{2})?)?$/)\n if (!m) return undefined\n const day = `${m[1]}-${m[2]}-${m[3]}`\n const t = Date.parse(`${day}T00:00:00Z`)\n // Rejects 2026-02-30 and the like, which Date.parse rolls over.\n return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === day ? day : undefined\n}\n\n/**\n * Top-level `key: value` lines, and the indented `key: value` lines of a\n * `metadata:` block. No other YAML: lists, nested blocks other than\n * `metadata:` and multi-line values are ignored, not misread.\n */\nfunction splitFrontmatter(text: string): { fields: Record<string, string>; metadata: Record<string, string>; body: string } {\n const fields: Record<string, string> = {}\n const metadata: Record<string, string> = {}\n if (!text.startsWith(\"---\\n\")) return { fields, metadata, body: text }\n const end = text.indexOf(\"\\n---\", 4)\n if (end < 0) return { fields, metadata, body: text }\n const after = text.indexOf(\"\\n\", end + 4)\n const body = after < 0 ? \"\" : text.slice(after + 1)\n\n let block: string | undefined\n for (const line of text.slice(4, end).split(\"\\n\")) {\n const nested = line.match(/^\\s+([A-Za-z_][\\w-]*):\\s*(.*)$/)\n if (nested) {\n if (block === \"metadata\") metadata[nested[1]] = unquote(nested[2])\n continue\n }\n const top = line.match(/^([A-Za-z_][\\w-]*):\\s*(.*)$/)\n if (!top) continue\n if (top[2].trim() === \"\") { block = top[1]; continue }\n block = undefined\n fields[top[1]] = unquote(top[2])\n }\n return { fields, metadata, body }\n}\n\nfunction unquote(v: string): string {\n const s = v.trim()\n if (s.length >= 2 && s.startsWith(\"\\\"\") && s.endsWith(\"\\\"\")) return s.slice(1, -1).replace(/\\\\\"/g, \"\\\"\")\n if (s.length >= 2 && s.startsWith(\"'\") && s.endsWith(\"'\")) return s.slice(1, -1).replace(/''/g, \"'\")\n return s\n}\n"],"mappings":"4BAAA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,EAAc,YAAAC,MAAgB,KAChE,OAAS,WAAAC,MAAe,OAsDxB,IAAMC,EAAc,IAAI,IAAI,CAAC,WAAW,CAAC,EAOlC,SAASC,EAAUC,EAAwB,CAChD,IAAMC,EAAiB,CAAE,IAAAD,EAAK,MAAO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MnB,EAAK,QAAQ;AAAA,KAAS,CAAC,EACnC,GAAImB,EAAM,EAAG,MAAO,CAAE,OAAAlB,EAAQ,SAAAC,EAAU,KAAMF,CAAK,EACnD,IAAMoB,EAAQpB,EAAK,QAAQ;AAAA,EAAMmB,EAAM,CAAC,EAClChB,EAAOiB,EAAQ,EAAI,GAAKpB,EAAK,MAAMoB,EAAQ,CAAC,EAE9CC,EACJ,QAAWC,KAAQtB,EAAK,MAAM,EAAGmB,CAAG,EAAE,MAAM;AAAA,CAAI,EAAG,CACjD,IAAMI,EAASD,EAAK,MAAM,gCAAgC,EAC1D,GAAIC,EAAQ,CACNF,IAAU,aAAYnB,EAASqB,EAAO,CAAC,CAAC,EAAIC,EAAQD,EAAO,CAAC,CAAC,GACjE,SAEF,IAAME,EAAMH,EAAK,MAAM,6BAA6B,EACpD,GAAKG,EACL,IAAIA,EAAI,CAAC,EAAE,KAAK,IAAM,GAAI,CAAEJ,EAAQI,EAAI,CAAC,EAAG,SAC5CJ,EAAQ,OACRpB,EAAOwB,EAAI,CAAC,CAAC,EAAID,EAAQC,EAAI,CAAC,CAAC,GAEjC,MAAO,CAAE,OAAAxB,EAAQ,SAAAC,EAAU,KAAAC,CAAK,CAClC,CAEA,SAASqB,EAAQjB,EAAmB,CAClC,IAAMmB,EAAInB,EAAE,KAAK,EACjB,OAAImB,EAAE,QAAU,GAAKA,EAAE,WAAW,GAAI,GAAKA,EAAE,SAAS,GAAI,EAAUA,EAAE,MAAM,EAAG,EAAE,EAAE,QAAQ,OAAQ,GAAI,EACnGA,EAAE,QAAU,GAAKA,EAAE,WAAW,GAAG,GAAKA,EAAE,SAAS,GAAG,EAAUA,EAAE,MAAM,EAAG,EAAE,EAAE,QAAQ,MAAO,GAAG,EAC5FA,CACT","names":["existsSync","readdirSync","readFileSync","statSync","resolve","INDEX_FILES","readNotes","dir","out","file","path","raw","err","note","parseNote","a","b","text","fields","metadata","body","splitFrontmatter","pick","key","v","firstLine","l","type","updated","source","checkedRaw","checked","checkDate","m","day","t","end","after","block","line","nested","unquote","top","s"]}
|
|
1
|
+
{"version":3,"sources":["../src/wiki/note-reader.ts"],"sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Reading an agent's notes (#850) ---\n//\n// An agent's notes are small markdown files with frontmatter, one fact or\n// one current state each. They live in one of two places:\n//\n// - the AgentX note store, `.agentx/agent-memory/<agent>/<type>_<name>.md`\n// (src/agents/agent-memory.ts), with `name`, `description`, `type`,\n// `created` and `updated`;\n// - a notes folder another tool keeps, such as the one a `claude-code`\n// agent writes outside AgentX: `<name>.md` with `name`, `description`\n// and `type`, sometimes with extra fields under a `metadata:` block.\n//\n// Both are read the same way. Two more fields say whether a note can be\n// trusted as written: `source` (where it was checked) and `checked` (the\n// date it was checked). They are read from the top level or from under\n// `metadata:`, never guessed from the prose. A note without them is still\n// returned, with `missing` naming what it lacks.\n//\n// Read only: nothing here writes a note.\n\nexport type NoteField = \"source\" | \"checked\"\n\nexport interface AgentNote {\n /** Frontmatter `name`, else the file name without `.md`. */\n name: string\n /** File name inside the notes folder. */\n file: string\n /** `user`, `feedback`, `project`, `reference`, or what the file says. */\n type?: string\n /** One line saying what the note holds. */\n description: string\n body: string\n /** Where the note's content was checked. */\n source?: string\n /** When it was checked, YYYY-MM-DD. */\n checked?: string\n /** When the note was last written, as the file says. */\n updated?: string\n /** `source` and `checked`, when absent or unreadable. */\n missing: NoteField[]\n /** Why a field present in the file could not be used. */\n problems: string[]\n}\n\nexport interface NotesRead {\n dir: string\n notes: AgentNote[]\n /** Files that are not notes, with the reason. */\n skipped: Array<{ file: string; reason: string }>\n}\n\n/** The index files tools keep next to the notes; not notes themselves. */\nconst INDEX_FILES = new Set([\"memory.md\"])\n\n/**\n * Every note in `dir`, sorted by name. Only `*.md` files directly in the\n * folder are read; sub-folders (such as `_versions/`) and the `MEMORY.md`\n * index are not notes. A folder that does not exist reads as empty.\n */\nexport function readNotes(dir: string): NotesRead {\n const out: NotesRead = { dir, notes: [], skipped: [] }\n if (!existsSync(dir)) return out\n for (const file of readdirSync(dir).sort()) {\n if (!file.endsWith(\".md\") || file.startsWith(\".\") || INDEX_FILES.has(file.toLowerCase())) continue\n const path = resolve(dir, file)\n let raw: string\n try {\n if (!statSync(path).isFile()) continue\n raw = readFileSync(path, \"utf-8\")\n } catch (err) {\n out.skipped.push({ file, reason: `unreadable: ${(err as Error).message}` })\n continue\n }\n const note = parseNote(raw, file)\n if (note) out.notes.push(note)\n else out.skipped.push({ file, reason: \"empty\" })\n }\n out.notes.sort((a, b) => a.name.localeCompare(b.name) || a.file.localeCompare(b.file))\n return out\n}\n\n/**\n * One note from its file content. A file without frontmatter is still a\n * note: its first line is its description, and it has no source or check\n * date. Returns null for an empty file.\n */\nexport function parseNote(raw: string, file: string): AgentNote | null {\n const text = raw.replace(/^/, \"\").replace(/\\r\\n/g, \"\\n\")\n const { fields, metadata, body } = splitFrontmatter(text)\n if (!body.trim() && Object.keys(fields).length === 0) return null\n\n const pick = (key: string): string | undefined => {\n const v = fields[key] ?? metadata[key]\n return v && v.trim() ? v.trim() : undefined\n }\n const firstLine = body.split(\"\\n\").map((l) => l.replace(/^#+\\s*/, \"\").trim()).find(Boolean) ?? \"\"\n const note: AgentNote = {\n name: pick(\"name\") ?? file.replace(/\\.md$/, \"\"),\n file,\n description: pick(\"description\") ?? firstLine,\n body: body.trim(),\n missing: [],\n problems: [],\n }\n const type = pick(\"type\")\n if (type) note.type = type\n const updated = pick(\"updated\") ?? pick(\"created\")\n if (updated) note.updated = updated\n\n const source = pick(\"source\")\n if (source) note.source = source\n else note.missing.push(\"source\")\n\n const checkedRaw = pick(\"checked\")\n const checked = checkedRaw ? checkDate(checkedRaw) : undefined\n if (checked) note.checked = checked\n else {\n note.missing.push(\"checked\")\n if (checkedRaw) note.problems.push(`checked \"${checkedRaw}\" is not a date (use YYYY-MM-DD)`)\n }\n return note\n}\n\n/** YYYY-MM-DD from a date or an ISO date and time; undefined otherwise. */\nfunction checkDate(v: string): string | undefined {\n const m = v.match(/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ][\\d:.]+(?:Z|[+-]\\d{2}:?\\d{2})?)?$/)\n if (!m) return undefined\n const day = `${m[1]}-${m[2]}-${m[3]}`\n const t = Date.parse(`${day}T00:00:00Z`)\n // Rejects 2026-02-30 and the like, which Date.parse rolls over.\n return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === day ? day : undefined\n}\n\n/**\n * Top-level `key: value` lines, and the indented `key: value` lines of a\n * `metadata:` block. No other YAML: lists, nested blocks other than\n * `metadata:` and multi-line values are ignored, not misread.\n */\nfunction splitFrontmatter(text: string): { fields: Record<string, string>; metadata: Record<string, string>; body: string } {\n const fields: Record<string, string> = {}\n const metadata: Record<string, string> = {}\n if (!text.startsWith(\"---\\n\")) return { fields, metadata, body: text }\n const end = text.indexOf(\"\\n---\", 4)\n if (end < 0) return { fields, metadata, body: text }\n const after = text.indexOf(\"\\n\", end + 4)\n const body = after < 0 ? \"\" : text.slice(after + 1)\n\n let block: string | undefined\n for (const line of text.slice(4, end).split(\"\\n\")) {\n const nested = line.match(/^\\s+([A-Za-z_][\\w-]*):\\s*(.*)$/)\n if (nested) {\n if (block === \"metadata\") metadata[nested[1]] = unquote(nested[2])\n continue\n }\n const top = line.match(/^([A-Za-z_][\\w-]*):\\s*(.*)$/)\n if (!top) continue\n if (top[2].trim() === \"\") { block = top[1]; continue }\n block = undefined\n fields[top[1]] = unquote(top[2])\n }\n return { fields, metadata, body }\n}\n\nfunction unquote(v: string): string {\n const s = v.trim()\n if (s.length >= 2 && s.startsWith(\"\\\"\") && s.endsWith(\"\\\"\")) return s.slice(1, -1).replace(/\\\\\"/g, \"\\\"\")\n if (s.length >= 2 && s.startsWith(\"'\") && s.endsWith(\"'\")) return s.slice(1, -1).replace(/''/g, \"'\")\n return s\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,EAAc,YAAAC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,GAAG,EAC5FA,CACT","names":["existsSync","readdirSync","readFileSync","statSync","resolve","INDEX_FILES","readNotes","dir","out","file","path","raw","err","note","parseNote","a","b","text","fields","metadata","body","splitFrontmatter","pick","key","v","firstLine","l","type","updated","source","checkedRaw","checked","checkDate","m","day","t","end","after","block","line","nested","unquote","top","s"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{
|
|
1
|
+
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{wa as tt,xa as nt}from"./chunk-DYGQF3MI.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Ot(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-4XMALK7X.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-DDEDSYLF.js";import{b as L}from"./chunk-4VVHGR7H.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-AHO4CQRK.js.map
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import{a as O}from"./chunk-JP5OAMWQ.js";import{b as L}from"./chunk-4VVHGR7H.js";import{a as I,b as E,c as R,d as j,e as M,j as T}from"./chunk-ERULJ2ZL.js";import{y as C,z as N}from"./chunk-4XMALK7X.js";import{c as x,d as _}from"./chunk-QOYAX2FT.js";import{readFileSync as W,writeFileSync as k,appendFileSync as B,existsSync as w,mkdirSync as S,readdirSync as D,statSync as U}from"fs";import{resolve as u,join as J,relative as y,dirname as K}from"path";N();function V(v){return O.includes(v)}function F(v){if(!v)return;let t;try{t=JSON.parse(v)}catch{return}if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="object"&&r!==null&&typeof r.property=="string"&&r.property!==""&&typeof r.value=="string"&&r.value!=="");return e.length?e:void 0}function Y(v,t){let e=n=>{let i=/^(.*Z)(?:-(\d+))?\.md$/.exec(n);return i?[i[1],i[2]?Number(i[2]):0]:[n,0]},[r,a]=e(v),[o,s]=e(t);return r<o?-1:r>o?1:a-s}var P=class{baseDir;rawDir;log;constructor(t=u(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=u(t,"raw/entries"),this.log=e,S(this.rawDir,{recursive:!0}),S(u(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=u(this.rawDir,e),a=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&a.push(`context: ${t.sourceContext}`),t.meta)for(let[o,s]of Object.entries(t.meta))a.push(`${o}: ${JSON.stringify(s)}`);return a.push("---","",t.content),k(r,a.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),r=[];for(let a of D(this.rawDir)){let o=a.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(o))continue;let s=this.parseEntry(W(u(this.rawDir,a),"utf-8"),a);s&&r.push(s)}return r}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(a=>a.endsWith(".md")).sort(),r=[];for(let a of e){let o=W(u(this.rawDir,a),"utf-8"),s=this.parseEntry(o,a);s&&(t?.agentId&&s.agentId!==t.agentId||t?.after&&s.date<t.after||t?.before&&s.date>t.before||r.push(s))}return r}parseEntry(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let a=r[1],o=r[2].trim(),s=c=>a.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",n=new Set(["id","date","agent","source","context"]),i={};for(let c of a.split(`
|
|
3
|
+
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||n.has(l[1])))try{i[l[1]]=JSON.parse(l[2])}catch{i[l[1]]=l[2].trim()}}return{id:s("id")||e.replace(".md",""),date:s("date"),agentId:s("agent"),source:s("source"),sourceContext:s("context")||void 0,content:o,meta:Object.keys(i).length>0?i:void 0}}writeArticle(t,e,r,a){let o=this.readArticle(t);if(o&&!this.canWrite(o.meta,a))return this.log(`Permission denied: "${a}" cannot write "${t}" (owner: ${o.meta.owner})`),!1;e.type&&!L(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=u(this.baseDir,t);o&&this.saveVersion(t,s),S(K(s),{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.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("---","",r),k(s,n.join(`
|
|
4
|
+
`));let i=o?"update":"create";return this.appendLog(i,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${a} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let r=W(e,"utf-8"),a=new Date().toISOString().replace(/[:.]/g,"-"),o=u(this.baseDir,"_versions",t.replace(/\.md$/,""));S(o,{recursive:!0});for(let s=0;;s++)try{k(u(o,`${s?`${a}-${s}`:a}.md`),r,{flag:"wx"});return}catch(n){if(n.code!=="EEXIST")throw n}}catch{}}getVersions(t){let e=u(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(r=>r.endsWith(".md")).sort(Y).reverse().map(r=>({timestamp:r.replace(/\.md$/,"").replace(/-/g,(a,o)=>o<19?o===10?"T":o===13||o===16?":":"-":a),path:u(e,r)}))}catch{return[]}}restoreVersion(t,e){let r=this.getVersions(t),a=r.find(o=>o.timestamp===e)??r.find(o=>o.timestamp.startsWith(e));if(!a)return!1;try{let o=W(a.path,"utf-8"),s=u(this.baseDir,t);return this.saveVersion(t,s),k(s,o),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=u(this.baseDir,t);if(!w(e))return null;let r=W(e,"utf-8");return this.parseArticle(r,t)}readArticleAs(t,e){let r=this.readArticle(t);return!r||!this.canRead(r.meta,e)?null:r}parseArticle(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let a=r[1],o=r[2].trim(),s=f=>a.match(new RegExp(`^${f}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",n=f=>{let $=a.match(new RegExp(`^${f}:\\s*\\[(.*)\\]$`,"m"));return $?[...$[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(A=>(A[1]??A[2]).trim()).filter(Boolean):[]},i=s("type")||s("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(i)?i:void 0,g=n("tags").filter((f,$,A)=>f&&A.indexOf(f)===$),d=n("related"),p=n("graph_path"),m=n("aliases"),h=s("importance"),b=s("date");return{meta:{title:s("title"),type:l,related:d.length?d:void 0,tags:g,owner:s("owner"),access:s("access")||"public",sharedWith:n("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:n("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(s("class"))?s("class"):void 0,importance:V(h)?h:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(b)?b.slice(0,10):void 0,rolledUpInto:s("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:F(s("statements"))},content:o,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],r=[];this.walkDir(this.baseDir,(i,c)=>{if(!i.endsWith(".md"))return;let l=y(this.baseDir,i);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),r.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let a=r.join("|"),o=t??"\0all",s=this.listCache.get(o);if(s&&s.signature===a)return s.articles.slice();let n=[];for(let i of e){let c=this.readArticle(i);c&&(t===null||this.canRead(c.meta,t))&&n.push(c)}return this.listCache.set(o,{signature:a,articles:n}),n.slice()}search(t,e,r=10){let a=t.toLowerCase(),o=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=y(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||o.push(m)}),o.length===0)return[];let s=o.map(d=>d.content),n=u(this.baseDir,"_bm25_cache.json"),i=_(s,n),c=x(t,i),l=new Map(c.map(d=>[d.docIndex,d.score]));return o.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(a)&&(m+=10),d.meta.tags?.some(h=>h.toLowerCase().includes(a))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,r).map(d=>d.article)}async findRelevantReranked(t,e,r=10,a={}){let o=Math.max(r,a.shortlist??E),s=this.findRelevant(t,e,o);if(s.length<2)return s.slice(0,r);let n=s.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),i=await C(I,R({query:t,candidates:n,excerptChars:a.excerptChars}),j(n),{incumbent:{best:n[0].id},features:{agent:e??"unknown"}});return!i||i.mode!=="active"?s.slice(0,r):M(i.answers,n).ranked.map(l=>s[Number(l.slice(1))]).filter(l=>!!l).slice(0,r)}findRelevant(t,e,r=3,a,o={graph:.6,bm25:.4}){let s=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let b=y(this.baseDir,h);if(b.startsWith("raw/")||b.startsWith("_"))return;let f=this.readArticle(b);!f||!this.canRead(f.meta,e)||s.push(f)}),s.length===0)return[];let n=s.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),i=u(this.baseDir,"_bm25_relevance_cache.json"),c=_(n,i),l=x(t,c),g=l.reduce((h,b)=>Math.max(h,b.score),0)||1,d=new Map(l.map(h=>[h.docIndex,h.score/g])),p=!!(a&&a.length>0);return s.map((h,b)=>{let f=d.get(b)??0,$=0;p&&h.meta.graphPath?.length&&($=T(a,h.meta.graphPath));let A=p?o.graph*$+o.bm25*f:f;return{article:h,score:A}}).filter(h=>h.score>0).sort((h,b)=>b.score-h.score).slice(0,r).map(h=>h.article)}buildContext(t,e=4e3){if(t.length===0)return"";let r=["[Wiki Knowledge]"],a=0;for(let o of t){let s=`
|
|
5
|
+
## ${o.meta.title} [${(o.meta.tags||[]).slice(0,3).join(", ")}]`,n=o.content.length>600?o.content.slice(0,600)+"...":o.content,i=s+`
|
|
6
|
+
`+n;if(a+i.length>e)break;r.push(i),a+=i.length}return r.push(`
|
|
7
|
+
[End Wiki Knowledge]`),r.join(`
|
|
8
|
+
`)}rebuildIndex(){let t=[],e=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=y(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_"))return;let i=this.readArticle(n);if(!i)return;let c=i.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let g of c){let d=g.replace(/\[\[|\]\]/g,"");e.set(d,(e.get(d)||0)+1)}let l=[i.meta.title.toLowerCase()];i.meta.tags&&l.push(...i.meta.tags.map(g=>g.toLowerCase())),t.push({path:n,title:i.meta.title,type:i.meta.type,related:i.meta.related,tags:i.meta.tags||[],owner:i.meta.owner,access:i.meta.access,sharedWith:i.meta.sharedWith,aliases:l,backlinks:e.get(i.meta.title)||0,sources:i.meta.sources,lastUpdated:i.meta.lastUpdated,graphPath:i.meta.graphPath})});let r={articles:t,lastRebuilt:new Date().toISOString()};k(u(this.baseDir,"_index.json"),JSON.stringify(r,null,2)),this.writeCatalog(t,r.lastRebuilt);let a=["# Wiki Index","",`Last rebuilt: ${r.lastRebuilt}`,""],o=new Map;for(let s of t){let n=s.access||"public",i=o.get(n)||[];i.push(s),o.set(n,i)}for(let[s,n]of Array.from(o.entries()).sort()){a.push(`## ${s}`,"");for(let i of n.sort((c,l)=>c.title.localeCompare(l.title))){let c=i.type?` [${i.type}]`:"";a.push(`- [${i.title}](${i.path})${c} \u2014 owner: ${i.owner}`)}a.push("")}return k(u(this.baseDir,"WIKI.md"),a.join(`
|
|
9
|
+
`)),this.log(`Index rebuilt: ${t.length} articles`),this.appendLog("rebuild-index",`${t.length} articles indexed`),r}writeCatalog(t,e){let r=["person","project","place","concept","event","decision","pattern","untyped"],a={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},o=new Map;for(let n of t){let i=n.type||"untyped",c=o.get(i)||[];c.push(n),o.set(i,c)}let s=["# Wiki Content Catalog","",`_Last rebuilt: ${e}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let n of r){let i=o.get(n);if(!(!i||i.length===0)){s.push(a[n]||`## ${n}`,"");for(let c of i.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":""}`:"";s.push(`- [${c.title}](${c.path})${l}${g}`)}s.push("")}}k(u(this.baseDir,"_index.md"),s.join(`
|
|
10
|
+
`))}stats(){let t=0,e={},r={},a={};this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=y(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_")||n==="WIKI.md")return;let i=this.readArticle(n);if(i){t++;for(let c of i.meta.tags||[])e[c]=(e[c]||0)+1;r[i.meta.access]=(r[i.meta.access]||0)+1,a[i.meta.owner]=(a[i.meta.owner]||0)+1}});let o=w(this.rawDir)?D(this.rawDir).filter(s=>s.endsWith(".md")).length:0;return{totalArticles:t,totalEntries:o,articlesByType:e,articlesByAccess:r,articlesByOwner:a}}appendLog(t,e){let r=u(this.baseDir,"log.md"),o=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${t} | ${e}
|
|
11
|
+
|
|
12
|
+
`;w(r)||k(r,`# Wiki Log
|
|
13
|
+
|
|
14
|
+
Chronological record of all wiki operations.
|
|
15
|
+
|
|
16
|
+
`),B(r,o)}getLog(t=20){let e=u(this.baseDir,"log.md");return w(e)?W(e,"utf-8").split(/^## /m).filter(o=>o.startsWith("[")).slice(-t).map(o=>o.trim()):[]}ensureSchema(){let t=u(this.baseDir,"_schema.md");if(w(t))return;k(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(r=>r.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let t={};return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=y(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_")||r==="WIKI.md"||r==="log.md")return;let a=W(e,"utf-8"),o=this.extractWikilinks(a);for(let s of o)t[s]||(t[s]=[]),t[s].push(r)}),k(u(this.baseDir,"_backlinks.json"),JSON.stringify(t,null,2)),t}getBacklinks(t){let e=u(this.baseDir,"_backlinks.json");if(!w(e))return[];try{return JSON.parse(W(e,"utf-8"))[t]||[]}catch{return[]}}findByTags(t,e,r=10){let a=t.map(s=>s.toLowerCase()),o=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=y(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_"))return;let i=this.readArticle(n);if(!i||e&&!this.canRead(i.meta,e))return;let c=(i.meta.tags||[]).map(p=>p.toLowerCase()),l=(i.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=a.filter(p=>g.includes(p)).length;d>0&&o.push({article:i,score:d})}),o.sort((s,n)=>n.score-s.score).slice(0,r).map(s=>s.article)}getAllTags(){let t=new Map;return this.walkDir(this.baseDir,e=>{if(!e.endsWith(".md"))return;let r=y(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_"))return;let a=this.readArticle(r);if(a?.meta.tags)for(let o of a.meta.tags)t.set(o,(t.get(o)||0)+1)}),t}getWorldview(){let t=u(this.baseDir,"worldview.md");return w(t)?W(t,"utf-8"):null}setWorldview(t){k(u(this.baseDir,"worldview.md"),t),this.appendLog("worldview","Updated worldview")}lint(){let t=[],e=new Set,r=new Map,a=new Map;this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=y(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_")||n==="WIKI.md"||n==="log.md")return;let i=this.readArticle(n);if(!i)return;e.add(i.meta.title),a.set(i.meta.title,n);let c=this.extractWikilinks(i.content);r.set(n,c);let l=i.content.split(`
|
|
98
|
+
`).length;l>100&&t.push({type:"bloated",article:n,message:`${l} lines \u2014 consider splitting`}),i.meta.sources?.length||t.push({type:"unsourced",article:n,message:"No sources listed in frontmatter"}),l<10&&i.content.trim().length<100&&t.push({type:"stub",article:n,message:"Very short article \u2014 needs enrichment"})});for(let[s,n]of r)for(let i of n)e.has(i)||t.push({type:"broken-link",article:s,message:`[[${i}]] \u2014 target article not found`});let o=this.buildBacklinks();for(let[s,n]of a)(!o[s]||o[s].length===0)&&t.push({type:"orphan",article:n,message:`No other articles link to "${s}"`});return this.appendLog("lint",`Found ${t.length} issues`),t}getUnabsorbedEntries(){let t=new Set;return this.walkDir(this.baseDir,r=>{if(!r.endsWith(".md"))return;let a=y(this.baseDir,r);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(o?.meta.sources)for(let s of o.meta.sources)t.add(s)}),this.listEntries().filter(r=>!t.has(r.id))}buildAbsorbPrompt(t=20){let e=this.getUnabsorbedEntries().slice(0,t);if(e.length===0)return null;let r=e.map(a=>`[${a.date} ${a.agentId} via ${a.source}] ${a.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
|
+
${r}`}walkDir(t,e){if(w(t))for(let r of D(t)){let a=J(t,r),o=U(a);o.isDirectory()?this.walkDir(a,e):e(a,o)}}};export{P as a};
|
|
105
|
+
//# sourceMappingURL=chunk-DDEDSYLF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 { 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\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 * Write or update a wiki article.\n */\n writeArticle(\n path: string,\n meta: WikiArticleMeta,\n content: string,\n agentId: string,\n ): boolean {\n // LLM picks the path. We just write the file.\n const existing = this.readArticle(path)\n if (existing && !this.canWrite(existing.meta, agentId)) {\n this.log(`Permission denied: \"${agentId}\" cannot write \"${path}\" (owner: ${existing.meta.owner})`)\n return false\n }\n\n // Drop invalid `type` at write time. The parser already rejects invalid\n // values on read (returns type=undefined), so silently serialising a\n // stray value would cause the round-trip to look fine but the article\n // to render as \"untyped\" in the catalog. Log + drop beats surprise.\n if (meta.type && !isWikiArticleType(meta.type)) {\n this.log(`Dropping invalid article type \"${meta.type}\" for \"${path}\" — enum is [person, project, place, concept, event, decision, pattern]`)\n meta = { ...meta, type: undefined }\n }\n\n const fullPath = resolve(this.baseDir, path)\n\n // Version the previous content before overwriting (immutable history)\n if (existing) {\n this.saveVersion(path, fullPath)\n }\n\n mkdirSync(dirname(fullPath), { recursive: true })\n\n const frontmatter = [\n \"---\",\n `title: \"${meta.title}\"`,\n ]\n if (meta.type) frontmatter.push(`type: ${meta.type}`)\n if (meta.related?.length) {\n frontmatter.push(`related: [${meta.related.map(t => `\"${t}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `tags: [${(meta.tags || []).map(t => `\"${t}\"`).join(\", \")}]`,\n `owner: ${meta.owner}`,\n `access: ${meta.access}`,\n )\n if (meta.sharedWith?.length) {\n frontmatter.push(`shared_with: [${meta.sharedWith.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n frontmatter.push(\n `created: ${meta.created}`,\n `last_updated: ${meta.lastUpdated}`,\n `sources: [${meta.sources.map(s => `\"${s}\"`).join(\", \")}]`,\n )\n if (meta.graphPath?.length) {\n frontmatter.push(`graph_path: [${meta.graphPath.map(s => `\"${s}\"`).join(\", \")}]`)\n }\n // 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.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 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 date: /^\\d{4}-\\d{2}-\\d{2}/.test(date) ? date.slice(0, 10) : undefined,\n rolledUpInto: get(\"rolled_up_into\") || undefined,\n aliases: aliases.length ? aliases : undefined,\n statements: parseStatements(get(\"statements\")),\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n /** Catalog per agent, valid while no article file changed. The walk is\n * repeated (names, mtimes, sizes) but the frontmatter parse of every\n * article is not; on a wiki of ten thousand files that parse was the\n * cost of every fresh session. */\n private listCache = new Map<string, { signature: string; articles: WikiArticle[] }>()\n\n listArticles(agentId: string): WikiArticle[] {\n return this.listCached(agentId)\n }\n\n /** Every article whatever its access, for the owner's own views. */\n listAllArticles(): WikiArticle[] {\n return this.listCached(null)\n }\n\n private listCached(agentId: string | null): WikiArticle[] {\n const relPaths: string[] = []\n const sig: string[] = []\n this.walkDir(this.baseDir, (filePath, stat) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n relPaths.push(relPath)\n sig.push(`${relPath}:${stat?.mtimeMs ?? \"?\"}:${stat?.size ?? \"?\"}`)\n })\n const signature = sig.join(\"|\")\n const key = agentId ?? \"\\u0000all\"\n const hit = this.listCache.get(key)\n if (hit && hit.signature === signature) return hit.articles.slice()\n\n const articles: WikiArticle[] = []\n for (const relPath of relPaths) {\n const article = this.readArticle(relPath)\n if (article && (agentId === null || this.canRead(article.meta, agentId))) {\n articles.push(article)\n }\n }\n this.listCache.set(key, { signature, articles })\n return articles.slice()\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * findRelevant, then re-ranked by the wiki-rerank seat.\n *\n * Recall comes from findRelevant rather than search() because\n * findRelevant is the function everything actually calls — search()\n * turned out to have no callers at all. Additive on purpose: the\n * synchronous findRelevant is untouched and its existing callers stay\n * as they are. Measured on the 12-query eval against this\n * wiki, re-ranking moves R@1 from 33.3% to 50.0% and R@3 from 41.7% to\n * 66.7%, for about $0.0005 and 550ms a query.\n *\n * Fail-open in every direction. Seat off, backend down, no key, fewer\n * than two candidates — all return BM25's own order, which is what the\n * caller would have got anyway.\n *\n * Note what this cannot do: it only reorders what BM25 shortlisted. In\n * the eval R@3 sat exactly on that ceiling, so every remaining miss was\n * an article BM25 never returned. Widening the shortlist does not fix\n * that — past 30 the extra candidates measurably diluted the ranking.\n */\n async findRelevantReranked(\n query: string,\n agentId?: string,\n maxResults = 10,\n opts: { shortlist?: number; excerptChars?: number } = {},\n ): Promise<WikiArticle[]> {\n const shortlist = Math.max(maxResults, opts.shortlist ?? DEFAULT_SHORTLIST)\n const pool = this.findRelevant(query, agentId, shortlist)\n if (pool.length < 2) return pool.slice(0, maxResults)\n\n const candidates: RerankCandidate[] = pool.map((article, i) => ({\n // Index, not title: titles are not unique across a wiki and a\n // Choice needs distinct keys.\n id: `c${i}`,\n title: article.meta.title || `(untitled ${i})`,\n tags: article.meta.tags,\n excerpt: article.content,\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query, candidates, excerptChars: opts.excerptChars }),\n rerankQuestions(candidates),\n { incumbent: { best: candidates[0].id }, features: { agent: agentId ?? \"unknown\" } },\n )\n if (!result || result.mode !== \"active\") return pool.slice(0, maxResults)\n\n const ranking = toRanking(result.answers as never, candidates)\n return ranking.ranked\n .map((id) => pool[Number(id.slice(1))])\n .filter((a): a is WikiArticle => Boolean(a))\n .slice(0, maxResults)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n graphPath: article.meta.graphPath,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string, stat?: Stats) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full, stat)\n }\n }\n }\n}\n"],"mappings":"yPAAA,OAAS,gBAAAA,EAAc,iBAAAC,EAAe,kBAAAC,EAAgB,cAAAC,EAAY,aAAAC,EAAW,eAAAC,EAAa,YAAAC,MAA4B,KACtH,OAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,WAAAC,MAAe,OAIjDC,IAYA,SAASC,EAAaC,EAA4B,CAChD,OAAQC,EAAwC,SAASD,CAAC,CAC5D,CAKO,SAASE,EAAgBC,EAA2C,CACzE,GAAI,CAACA,EAAM,OACX,IAAIC,EACJ,GAAI,CACFA,EAAS,KAAK,MAAMD,CAAI,CAC1B,MAAE,CACA,MACF,CACA,GAAI,CAAC,MAAM,QAAQC,CAAM,EAAG,OAC5B,IAAMC,EAAMD,EAAO,OAAQJ,GACzB,OAAOA,GAAM,UAAYA,IAAM,MAC5B,OAAQA,EAAoB,UAAa,UAAaA,EAAoB,WAAa,IACvF,OAAQA,EAAoB,OAAU,UAAaA,EAAoB,QAAU,EAAE,EACxF,OAAOK,EAAI,OAASA,EAAM,MAC5B,CAqBA,SAASC,EAAoBC,EAAWC,EAAmB,CACzD,IAAMC,EAASC,GAAgC,CAC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","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","existing","isWikiArticleType","fullPath","dirname","t","action","articlePath","ts","versionDir","n","err","i","versionTimestamp","versions","version","raw","getArray","x","rawType","type","tags","related","graphPath","aliases","importance","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","e","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync"]}
|