agentix-cli 0.134.0 → 0.135.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/{absorb-eval-WU7JR3BT.js → absorb-eval-WY3YMLS4.js} +2 -2
- package/dist/{agent-2GPJGHHG.js → agent-3R5NY7I3.js} +2 -2
- package/dist/{board-dashboard-PUQPL4AX.js → board-dashboard-U3ZSCO62.js} +2 -2
- package/dist/{chunk-AHO4CQRK.js → chunk-5NT44FKL.js} +2 -2
- package/dist/{chunk-RJOA7QBB.js → chunk-6WF56ME6.js} +2 -2
- package/dist/{chunk-MCBTVNPX.js → chunk-BQIWMQNU.js} +2 -2
- package/dist/{chunk-MM3F74K4.js → chunk-EEBK4F6E.js} +3 -3
- package/dist/chunk-EEBK4F6E.js.map +1 -0
- package/dist/{chunk-YSXE65O7.js → chunk-GSKJ57XY.js} +4 -4
- package/dist/{chunk-VQYVL72V.js → chunk-H6VWU2HN.js} +2 -2
- package/dist/chunk-JRS5QRZG.js +2 -0
- package/dist/chunk-JRS5QRZG.js.map +1 -0
- package/dist/{chunk-5BI2T3WD.js → chunk-JTDUTCUE.js} +3 -3
- package/dist/chunk-JTDUTCUE.js.map +1 -0
- package/dist/{chunk-4VVHGR7H.js → chunk-KEXBEUSU.js} +1 -1
- package/dist/{chunk-4VVHGR7H.js.map → chunk-KEXBEUSU.js.map} +1 -1
- package/dist/chunk-L5UGH4T4.js +160 -0
- package/dist/chunk-L5UGH4T4.js.map +1 -0
- package/dist/{chunk-RDEFA6Y6.js → chunk-LU7GDHGD.js} +2 -2
- package/dist/chunk-MI7WOGH6.js +4 -0
- package/dist/chunk-MI7WOGH6.js.map +1 -0
- package/dist/chunk-NY7NHGVT.js +105 -0
- package/dist/chunk-NY7NHGVT.js.map +1 -0
- package/dist/chunk-QAWKN2N4.js +3 -0
- package/dist/chunk-QAWKN2N4.js.map +1 -0
- package/dist/{chunk-FEEXOWK5.js → chunk-QDWEM4DG.js} +2 -2
- package/dist/{chunk-JP5OAMWQ.js → chunk-RGZARSHV.js} +1 -1
- package/dist/{chunk-JP5OAMWQ.js.map → chunk-RGZARSHV.js.map} +1 -1
- package/dist/{chunk-TDGDH4RA.js → chunk-RVEMX5MJ.js} +2 -2
- package/dist/{chunk-TDGDH4RA.js.map → chunk-RVEMX5MJ.js.map} +1 -1
- package/dist/{chunk-URN74FTP.js → chunk-WWDYDLY2.js} +2 -2
- package/dist/{chunk-G4HDRJVN.js → chunk-YA3P77LV.js} +2 -2
- package/dist/{chunk-XWO6ALJQ.js → chunk-ZFRXFUP7.js} +2 -2
- package/dist/{chunk-NXRSIWQA.js → chunk-ZGVVYJIK.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{contributions-74M6YOCZ.js → contributions-KLRJ4ZXV.js} +2 -2
- package/dist/{enrich-NH3WHKD6.js → enrich-ZB5I7KHN.js} +2 -2
- package/dist/event-levels-CQWHSLMT.js +3 -0
- package/dist/event-levels-CQWHSLMT.js.map +1 -0
- package/dist/graph-ZVKV3JBD.js +2 -0
- package/dist/{hub-VTDFUAEH.js → hub-TILTOOSS.js} +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/load-EOZUZK7U.js +2 -0
- package/dist/model-call-PKV5UAQ7.js +2 -0
- package/dist/{program-3URNCVEZ.js → program-U3HJY7E5.js} +272 -274
- package/dist/program-U3HJY7E5.js.map +1 -0
- package/dist/{promote-B2BADAEP.js → promote-RHVZB2QZ.js} +2 -2
- package/dist/push-bridge-325SXDGN.js +1 -1
- package/dist/{query-2VIIGGDS.js → query-OZXZVLO7.js} +2 -2
- package/dist/query-runs-7VX3YAC3.js +4 -0
- package/dist/query-runs-7VX3YAC3.js.map +1 -0
- package/dist/{query-settings-VJ3POZS3.js → query-settings-2MGUS6AY.js} +2 -2
- package/dist/registry-LZLIPP7N.js +2 -0
- package/dist/roster-BZGKG2ZA.js +2 -0
- package/dist/score-DZGPLHCL.js +3 -0
- package/dist/score-DZGPLHCL.js.map +1 -0
- package/dist/types-ARP27T6T.js +2 -0
- package/dist/types-LJZ2YY5W.js +2 -0
- package/dist/{wiki-SXWJ5NJQ.js → wiki-GCRRINW3.js} +2 -2
- package/dist/wiki-GCRRINW3.js.map +1 -0
- package/dist/wiki-enrich-P5TNWACZ.js +2 -0
- package/dist/wiki-enrich-P5TNWACZ.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-5BI2T3WD.js.map +0 -1
- package/dist/chunk-7VLLZQ3N.js +0 -2
- package/dist/chunk-7VLLZQ3N.js.map +0 -1
- package/dist/chunk-DDEDSYLF.js +0 -105
- package/dist/chunk-DDEDSYLF.js.map +0 -1
- package/dist/chunk-KFIJDLQ5.js +0 -3
- package/dist/chunk-KFIJDLQ5.js.map +0 -1
- package/dist/chunk-MM3F74K4.js.map +0 -1
- package/dist/chunk-SFVDQNTY.js +0 -156
- package/dist/chunk-SFVDQNTY.js.map +0 -1
- package/dist/graph-EXDH7EPZ.js +0 -2
- package/dist/load-5DNMGHFW.js +0 -2
- package/dist/model-call-BGTDPWZD.js +0 -2
- package/dist/program-3URNCVEZ.js.map +0 -1
- package/dist/registry-PRCISYBO.js +0 -2
- package/dist/roster-IRXP32XF.js +0 -2
- package/dist/score-KDNIUTNV.js +0 -3
- package/dist/score-KDNIUTNV.js.map +0 -1
- package/dist/types-ROL44T62.js +0 -2
- /package/dist/{absorb-eval-WU7JR3BT.js.map → absorb-eval-WY3YMLS4.js.map} +0 -0
- /package/dist/{agent-2GPJGHHG.js.map → agent-3R5NY7I3.js.map} +0 -0
- /package/dist/{board-dashboard-PUQPL4AX.js.map → board-dashboard-U3ZSCO62.js.map} +0 -0
- /package/dist/{chunk-AHO4CQRK.js.map → chunk-5NT44FKL.js.map} +0 -0
- /package/dist/{chunk-RJOA7QBB.js.map → chunk-6WF56ME6.js.map} +0 -0
- /package/dist/{chunk-MCBTVNPX.js.map → chunk-BQIWMQNU.js.map} +0 -0
- /package/dist/{chunk-YSXE65O7.js.map → chunk-GSKJ57XY.js.map} +0 -0
- /package/dist/{chunk-VQYVL72V.js.map → chunk-H6VWU2HN.js.map} +0 -0
- /package/dist/{chunk-RDEFA6Y6.js.map → chunk-LU7GDHGD.js.map} +0 -0
- /package/dist/{chunk-FEEXOWK5.js.map → chunk-QDWEM4DG.js.map} +0 -0
- /package/dist/{chunk-URN74FTP.js.map → chunk-WWDYDLY2.js.map} +0 -0
- /package/dist/{chunk-G4HDRJVN.js.map → chunk-YA3P77LV.js.map} +0 -0
- /package/dist/{chunk-XWO6ALJQ.js.map → chunk-ZFRXFUP7.js.map} +0 -0
- /package/dist/{chunk-NXRSIWQA.js.map → chunk-ZGVVYJIK.js.map} +0 -0
- /package/dist/{contributions-74M6YOCZ.js.map → contributions-KLRJ4ZXV.js.map} +0 -0
- /package/dist/{enrich-NH3WHKD6.js.map → enrich-ZB5I7KHN.js.map} +0 -0
- /package/dist/{graph-EXDH7EPZ.js.map → graph-ZVKV3JBD.js.map} +0 -0
- /package/dist/{hub-VTDFUAEH.js.map → hub-TILTOOSS.js.map} +0 -0
- /package/dist/{load-5DNMGHFW.js.map → load-EOZUZK7U.js.map} +0 -0
- /package/dist/{model-call-BGTDPWZD.js.map → model-call-PKV5UAQ7.js.map} +0 -0
- /package/dist/{promote-B2BADAEP.js.map → promote-RHVZB2QZ.js.map} +0 -0
- /package/dist/{query-2VIIGGDS.js.map → query-OZXZVLO7.js.map} +0 -0
- /package/dist/{query-settings-VJ3POZS3.js.map → query-settings-2MGUS6AY.js.map} +0 -0
- /package/dist/{registry-PRCISYBO.js.map → registry-LZLIPP7N.js.map} +0 -0
- /package/dist/{roster-IRXP32XF.js.map → roster-BZGKG2ZA.js.map} +0 -0
- /package/dist/{types-ROL44T62.js.map → types-ARP27T6T.js.map} +0 -0
- /package/dist/{wiki-SXWJ5NJQ.js.map → types-LJZ2YY5W.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-ZFRXFUP7.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-LU7GDHGD.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-ROH45HXN.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-TILTOOSS.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-EOZUZK7U.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-ZB5I7KHN.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-ZB5I7KHN.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
|
|
2
|
+
`).slice(0,12).map(n=>` | ${n}`).join(`
|
|
3
|
+
`)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
|
|
4
|
+
//# sourceMappingURL=chunk-MI7WOGH6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/wiki-enrich.ts"],"sourcesContent":["import type { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { spawn } from \"child_process\"\nimport { resolve } from \"path\"\n\n// --- agentx wiki enrich: full overview, typed facts and linked history per entity (#820) ---\n//\n// Runs on demand or from a scheduled job with `command`. Each entity\n// costs one model call; `--max-cost` stops the run before the next call\n// once the spend reaches it.\n\nconst wikiDir = (dir?: string) => dir || resolve(process.cwd(), \".agentx/wiki\")\n\n/** One `claude -p` call with no tools; cost from the JSON envelope.\n * The prompt carries raw message text, so no built-in tool, MCP server,\n * hook or settings file is loaded: an injected instruction has nothing\n * to write or send with. */\nexport function claudeCall(model: string): (prompt: string) => Promise<{ text: string; costUsd: number }> {\n return async (prompt) => {\n const { claudeCliEnv } = await import(\"@/utils/workspace-env\")\n const args = [\"-p\", \"-\", \"--output-format\", \"json\", \"--max-turns\", \"1\", \"--model\", model,\n \"--tools\", \"\", \"--strict-mcp-config\", \"--mcp-config\", '{\"mcpServers\":{}}',\n \"--settings\", '{\"disableAllHooks\":true}', \"--setting-sources\", \"\", \"--no-session-persistence\"]\n const out = await new Promise<string>((ok, fail) => {\n const child = spawn(\"claude\", args, { env: claudeCliEnv(), stdio: [\"pipe\", \"pipe\", \"pipe\"] })\n let stdout = \"\"\n let stderr = \"\"\n const timer = setTimeout(() => child.kill(\"SIGTERM\"), 240_000)\n child.stdout.on(\"data\", d => { stdout += d })\n child.stderr.on(\"data\", d => { stderr += d })\n child.on(\"error\", err => { clearTimeout(timer); fail(err) })\n child.on(\"close\", code => {\n clearTimeout(timer)\n if (code === 0) ok(stdout)\n else fail(new Error(`claude exited ${code}: ${stderr.trim().slice(0, 200)}`))\n })\n child.stdin.end(prompt)\n })\n const envelope = JSON.parse(out) as { result?: string; total_cost_usd?: number; is_error?: boolean }\n if (envelope.is_error) throw new Error(`model error: ${String(envelope.result).slice(0, 200)}`)\n return { text: String(envelope.result ?? \"\"), costUsd: Number(envelope.total_cost_usd) || 0 }\n }\n}\n\nexport function registerWikiEnrich(wiki: Command): void {\n wiki\n .command(\"enrich [entities...]\")\n .description(\"write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)\")\n .option(\"--dir <path>\", \"wiki directory (default .agentx/wiki)\")\n .option(\"--types <list>\", \"comma-separated entity types\", \"person,organization,project,place,device,server,app,domain,account\")\n .option(\"--max <n>\", \"most entities per run\", \"10\")\n .option(\"--max-cost <usd>\", \"stop before the next call once the run spent this much\", \"1\")\n .option(\"--model <m>\", \"model\", \"sonnet\")\n .option(\"--force\", \"redo entities whose sources did not change\")\n .option(\"--dry-run\", \"show what would be written, write nothing\")\n .option(\"--create <title>\", \"first create a page for a thing other pages only name, then enrich it (needs --as and --owner)\")\n .option(\"--as <type>\", \"type of the page --create makes, e.g. organization\")\n .option(\"--owner <agent>\", \"agent whose wiki gets the page --create makes\")\n .option(\"--json\", \"print the run as JSON\")\n .action(async (entities: string[], opts: { dir?: string; types: string; max: string; maxCost: string; model: string; force?: boolean; dryRun?: boolean; json?: boolean; create?: string; as?: string; owner?: string }) => {\n const { WikiHub } = await import(\"@/wiki/hub\")\n const { GraphCache } = await import(\"@/wiki/ontology/graph\")\n const { loadOntology } = await import(\"@/wiki/ontology/load\")\n const { loadRoster } = await import(\"@/wiki/ontology/roster\")\n const { ENRICH_TYPES, loadEnrichState, runEnrich, saveEnrichState } = await import(\"@/wiki/enrich\")\n const dir = wikiDir(opts.dir)\n const types = opts.types.split(\",\").map(s => s.trim()).filter(Boolean)\n const unknown = types.filter(t => !ENRICH_TYPES.includes(t))\n if (unknown.length) {\n console.error(chalk.red(` not an entity type this job handles: ${unknown.join(\", \")} (use ${ENRICH_TYPES.join(\", \")})`))\n process.exitCode = 1\n return\n }\n const max = Number(opts.max)\n if (!Number.isInteger(max) || max < 1) {\n console.error(chalk.red(\" --max must be a whole number of entities, 1 or more\"))\n process.exitCode = 1\n return\n }\n const maxCostUsd = Number(opts.maxCost)\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n console.error(chalk.red(\" --max-cost must be a positive number of dollars\"))\n process.exitCode = 1\n return\n }\n const hub = new WikiHub(dir, () => {})\n if (opts.create) {\n const { createEntityPage } = await import(\"@/wiki/enrich\")\n if (!opts.as || !ENRICH_TYPES.includes(opts.as) || !opts.owner) {\n console.error(chalk.red(` --create needs --as <${ENRICH_TYPES.join(\"|\")}> and --owner <agent>`))\n process.exitCode = 1\n return\n }\n if (hub.syncedFrom(opts.owner)) {\n console.error(chalk.red(` ${opts.owner}'s pages are copied from another node; pick an agent that runs here`))\n process.exitCode = 1\n return\n }\n if (opts.dryRun) {\n console.log(chalk.dim(` --dry-run: would create \"${opts.create}\" (${opts.as}) in ${opts.owner}'s wiki`))\n } else {\n const path = createEntityPage(hub, opts.create, opts.as, opts.owner, new Date().toISOString().slice(0, 10))\n console.log(path ? chalk.green(` created ${opts.owner}/${path}`) : chalk.dim(` ${opts.owner} already has a page titled \"${opts.create}\"`))\n }\n entities = [...entities, opts.create]\n if (!types.includes(opts.as)) types.push(opts.as)\n }\n const { ontology } = loadOntology(dir)\n const g = new GraphCache().get(hub, ontology, loadRoster(dir, hub.listAgents([]), ontology.agent_names))\n const state = loadEnrichState(dir)\n const run = await runEnrich(hub, g, claudeCall(opts.model), {\n types, only: entities, max, maxCostUsd, dryRun: !!opts.dryRun, force: !!opts.force, today: new Date().toISOString().slice(0, 10),\n save: s => saveEnrichState(dir, s),\n }, state)\n\n if (opts.json) {\n console.log(JSON.stringify(run, null, 2))\n return\n }\n for (const o of run.outcomes) {\n const mark = o.status === \"written\" ? chalk.green(\"✓\") : o.status === \"dry-run\" ? chalk.cyan(\"~\") : chalk.yellow(\"·\")\n console.log(` ${mark} ${o.title} ${chalk.dim(`${o.status} · ${o.page ?? \"no page\"} · overview ${o.overview ? \"yes\" : \"no\"} · ${o.statements} facts · ${o.links} links · $${o.costUsd.toFixed(3)}`)}`)\n for (const f of o.facts ?? []) console.log(chalk.dim(` fact: ${f.property} → ${f.value}${f.role ? ` (${f.role})` : \"\"} · source ${f.source}`))\n for (const d of o.dropped.slice(0, 6)) console.log(chalk.dim(` dropped: ${d}`))\n if (o.preview) console.log(chalk.dim(o.preview.split(\"\\n\").slice(0, 12).map(l => ` | ${l}`).join(\"\\n\")))\n }\n if (run.outcomes.length === 0) console.log(chalk.dim(\" nothing to do: no entity of these types changed since the last run (--force redoes them)\"))\n console.log(chalk.dim(` spent $${run.costUsd.toFixed(3)} of $${maxCostUsd}${run.capped ? \" · stopped at the cap\" : \"\"}`))\n })\n}\n"],"mappings":"AACA,OAAOA,MAAW,QAClB,OAAS,SAAAC,MAAa,gBACtB,OAAS,WAAAC,MAAe,OAQxB,IAAMC,EAAWC,GAAiBA,GAAOF,EAAQ,QAAQ,IAAI,EAAG,cAAc,EAMvE,SAASG,EAAWC,EAA+E,CACxG,MAAO,OAAOC,GAAW,CACvB,GAAM,CAAE,aAAAC,CAAa,EAAI,KAAM,QAAO,6BAAuB,EACvDC,EAAO,CAAC,KAAM,IAAK,kBAAmB,OAAQ,cAAe,IAAK,UAAWH,EACjF,UAAW,GAAI,sBAAuB,eAAgB,oBACtD,aAAc,2BAA4B,oBAAqB,GAAI,0BAA0B,EACzFI,EAAM,MAAM,IAAI,QAAgB,CAACC,EAAIC,IAAS,CAClD,IAAMC,EAAQZ,EAAM,SAAUQ,EAAM,CAAE,IAAKD,EAAa,EAAG,MAAO,CAAC,OAAQ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K8B,CAAC,CACnC,EAAGU,CAAK,EAER,GAAIpB,EAAK,KAAM,CACb,QAAQ,IAAI,KAAK,UAAUqB,EAAK,KAAM,CAAC,CAAC,EACxC,OAEF,QAAW,KAAKA,EAAI,SAAU,CAC5B,IAAMC,EAAO,EAAE,SAAW,UAAY9C,EAAM,MAAM,QAAG,EAAI,EAAE,SAAW,UAAYA,EAAM,KAAK,GAAG,EAAIA,EAAM,OAAO,MAAG,EACpH,QAAQ,IAAI,KAAK8C,KAAQ,EAAE,UAAU9C,EAAM,IAAI,GAAG,EAAE,eAAY,EAAE,MAAQ,2BAAwB,EAAE,SAAW,MAAQ,aAAU,EAAE,yBAAsB,EAAE,qBAAkB,EAAE,QAAQ,QAAQ,CAAC,GAAG,GAAG,EACtM,QAAW+C,KAAK,EAAE,OAAS,CAAC,EAAG,QAAQ,IAAI/C,EAAM,IAAI,eAAe+C,EAAE,mBAAcA,EAAE,QAAQA,EAAE,KAAO,KAAKA,EAAE,QAAU,kBAAeA,EAAE,QAAQ,CAAC,EAClJ,QAAW9B,KAAK,EAAE,QAAQ,MAAM,EAAG,CAAC,EAAG,QAAQ,IAAIjB,EAAM,IAAI,kBAAkBiB,GAAG,CAAC,EAC/E,EAAE,SAAS,QAAQ,IAAIjB,EAAM,IAAI,EAAE,QAAQ,MAAM;AAAA,CAAI,EAAE,MAAM,EAAG,EAAE,EAAE,IAAIgD,GAAK,WAAWA,GAAG,EAAE,KAAK;AAAA,CAAI,CAAC,CAAC,EAE1GH,EAAI,SAAS,SAAW,GAAG,QAAQ,IAAI7C,EAAM,IAAI,4FAA4F,CAAC,EAClJ,QAAQ,IAAIA,EAAM,IAAI,YAAY6C,EAAI,QAAQ,QAAQ,CAAC,SAASP,IAAaO,EAAI,OAAS,2BAA0B,IAAI,CAAC,CAC3H,CAAC,CACL","names":["chalk","spawn","resolve","wikiDir","dir","claudeCall","model","prompt","claudeCliEnv","args","out","ok","fail","child","stdout","stderr","timer","d","err","code","envelope","registerWikiEnrich","wiki","entities","opts","WikiHub","GraphCache","loadOntology","loadRoster","ENRICH_TYPES","loadEnrichState","runEnrich","saveEnrichState","types","s","unknown","t","max","maxCostUsd","hub","createEntityPage","path","ontology","g","state","run","mark","f","l"]}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import{b as I}from"./chunk-KEXBEUSU.js";import{a as P}from"./chunk-RGZARSHV.js";import{a as E,b as R,c as j,d as M,e as T,j as O}from"./chunk-ERULJ2ZL.js";import{y as L,z as U}from"./chunk-4XMALK7X.js";import{c as _,d as C}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as w,appendFileSync as J,existsSync as b,mkdirSync as x,readdirSync as D,statSync as K}from"fs";import{resolve as u,join as V,relative as k,dirname as F}from"path";U();function N(v){return P.includes(v)}function Y(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 z(v,t){let e=i=>{let n=/^(.*Z)(?:-(\d+))?\.md$/.exec(i);return n?[n[1],n[2]?Number(n[2]):0]:[i,0]},[r,a]=e(v),[o,s]=e(t);return r<o?-1:r>o?1:a-s}var B=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,x(this.rawDir,{recursive:!0}),x(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),w(r,a.join(`
|
|
2
|
+
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!b(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($(u(this.rawDir,a),"utf-8"),a);s&&r.push(s)}return r}listEntries(t){if(!b(this.rawDir))return[];let e=D(this.rawDir).filter(a=>a.endsWith(".md")).sort(),r=[];for(let a of e){let o=$(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()||"",i=new Set(["id","date","agent","source","context"]),n={};for(let c of a.split(`
|
|
3
|
+
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{n[l[1]]=JSON.parse(l[2])}catch{n[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(n).length>0?n: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&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=u(this.baseDir,t);o&&this.saveVersion(t,s),x(F(s),{recursive:!0});let i=["---",`title: "${e.title}"`];e.type&&i.push(`type: ${e.type}`),e.related?.length&&i.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&i.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&i.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&i.push(`class: ${e.class}`),e.importance&&i.push(`importance: ${e.importance}`),e.importanceProposed&&i.push(`importance_proposed: ${e.importanceProposed}`),e.date&&i.push(`date: ${e.date}`),e.rolledUpInto&&i.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&i.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&i.push(`statements: ${JSON.stringify(e.statements)}`),i.push("---","",r),w(s,i.join(`
|
|
4
|
+
`));let n=o?"update":"create";return this.appendLog(n,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${a} at ${t}`),!0}saveVersion(t,e){try{if(!b(e))return;let r=$(e,"utf-8"),a=new Date().toISOString().replace(/[:.]/g,"-"),o=u(this.baseDir,"_versions",t.replace(/\.md$/,""));x(o,{recursive:!0});for(let s=0;;s++)try{w(u(o,`${s?`${a}-${s}`:a}.md`),r,{flag:"wx"});return}catch(i){if(i.code!=="EEXIST")throw i}}catch{}}getVersions(t){let e=u(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!b(e))return[];try{return D(e).filter(r=>r.endsWith(".md")).sort(z).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=$(a.path,"utf-8"),s=u(this.baseDir,t);return this.saveVersion(t,s),w(s,o),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=u(this.baseDir,t);if(!b(e))return null;let r=$(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=W=>a.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=W=>{let A=a.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return A?[...A[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},n=s("type")||s("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(n)?n:void 0,g=i("tags").filter((W,A,S)=>W&&S.indexOf(W)===A),d=i("related"),p=i("graph_path"),m=i("aliases"),h=s("importance"),f=s("importance_proposed"),y=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:i("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:i("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(s("class"))?s("class"):void 0,importance:N(h)?h:void 0,importanceProposed:N(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:s("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:Y(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,(n,c)=>{if(!n.endsWith(".md"))return;let l=k(this.baseDir,n);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 i=[];for(let n of e){let c=this.readArticle(n);c&&(t===null||this.canRead(c.meta,t))&&i.push(c)}return this.listCache.set(o,{signature:a,articles:i}),i.slice()}search(t,e,r=10){let a=t.toLowerCase(),o=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||o.push(m)}),o.length===0)return[];let s=o.map(d=>d.content),i=u(this.baseDir,"_bm25_cache.json"),n=C(s,i),c=_(t,n),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??R),s=this.findRelevant(t,e,o);if(s.length<2)return s.slice(0,r);let i=s.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),n=await L(E,j({query:t,candidates:i,excerptChars:a.excerptChars}),M(i),{incumbent:{best:i[0].id},features:{agent:e??"unknown"}});return!n||n.mode!=="active"?s.slice(0,r):T(n.answers,i).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 f=k(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||s.push(y)}),s.length===0)return[];let i=s.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),n=u(this.baseDir,"_bm25_relevance_cache.json"),c=C(i,n),l=_(t,c),g=l.reduce((h,f)=>Math.max(h,f.score),0)||1,d=new Map(l.map(h=>[h.docIndex,h.score/g])),p=!!(a&&a.length>0);return s.map((h,f)=>{let y=d.get(f)??0,W=0;p&&h.meta.graphPath?.length&&(W=O(a,h.meta.graphPath));let A=p?o.graph*W+o.bm25*y:y;return{article:h,score:A}}).filter(h=>h.score>0).sort((h,f)=>f.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(", ")}]`,i=o.content.length>600?o.content.slice(0,600)+"...":o.content,n=s+`
|
|
6
|
+
`+i;if(a+n.length>e)break;r.push(n),a+=n.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 i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);if(!n)return;let c=n.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let g of c){let d=g.replace(/\[\[|\]\]/g,"");e.set(d,(e.get(d)||0)+1)}let l=[n.meta.title.toLowerCase()];n.meta.tags&&l.push(...n.meta.tags.map(g=>g.toLowerCase())),t.push({path:i,title:n.meta.title,type:n.meta.type,related:n.meta.related,tags:n.meta.tags||[],owner:n.meta.owner,access:n.meta.access,sharedWith:n.meta.sharedWith,aliases:l,backlinks:e.get(n.meta.title)||0,sources:n.meta.sources,lastUpdated:n.meta.lastUpdated,graphPath:n.meta.graphPath})});let r={articles:t,lastRebuilt:new Date().toISOString()};w(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 i=s.access||"public",n=o.get(i)||[];n.push(s),o.set(i,n)}for(let[s,i]of Array.from(o.entries()).sort()){a.push(`## ${s}`,"");for(let n of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=n.type?` [${n.type}]`:"";a.push(`- [${n.title}](${n.path})${c} \u2014 owner: ${n.owner}`)}a.push("")}return w(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 i of t){let n=i.type||"untyped",c=o.get(n)||[];c.push(i),o.set(n,c)}let s=["# Wiki Content Catalog","",`_Last rebuilt: ${e}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of r){let n=o.get(i);if(!(!n||n.length===0)){s.push(a[i]||`## ${i}`,"");for(let c of n.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("")}}w(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 i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let n=this.readArticle(i);if(n){t++;for(let c of n.meta.tags||[])e[c]=(e[c]||0)+1;r[n.meta.access]=(r[n.meta.access]||0)+1,a[n.meta.owner]=(a[n.meta.owner]||0)+1}});let o=b(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
|
+
`;b(r)||w(r,`# Wiki Log
|
|
13
|
+
|
|
14
|
+
Chronological record of all wiki operations.
|
|
15
|
+
|
|
16
|
+
`),J(r,o)}getLog(t=20){let e=u(this.baseDir,"log.md");return b(e)?$(e,"utf-8").split(/^## /m).filter(o=>o.startsWith("[")).slice(-t).map(o=>o.trim()):[]}ensureSchema(){let t=u(this.baseDir,"_schema.md");if(b(t))return;w(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=k(this.baseDir,e);if(r.startsWith("raw/")||r.startsWith("_")||r==="WIKI.md"||r==="log.md")return;let a=$(e,"utf-8"),o=this.extractWikilinks(a);for(let s of o)t[s]||(t[s]=[]),t[s].push(r)}),w(u(this.baseDir,"_backlinks.json"),JSON.stringify(t,null,2)),t}getBacklinks(t){let e=u(this.baseDir,"_backlinks.json");if(!b(e))return[];try{return JSON.parse($(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 i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_"))return;let n=this.readArticle(i);if(!n||e&&!this.canRead(n.meta,e))return;let c=(n.meta.tags||[]).map(p=>p.toLowerCase()),l=(n.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:n,score:d})}),o.sort((s,i)=>i.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=k(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 b(t)?$(t,"utf-8"):null}setWorldview(t){w(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 i=k(this.baseDir,s);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let n=this.readArticle(i);if(!n)return;e.add(n.meta.title),a.set(n.meta.title,i);let c=this.extractWikilinks(n.content);r.set(i,c);let l=n.content.split(`
|
|
98
|
+
`).length;l>100&&t.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),n.meta.sources?.length||t.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&n.content.trim().length<100&&t.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[s,i]of r)for(let n of i)e.has(n)||t.push({type:"broken-link",article:s,message:`[[${n}]] \u2014 target article not found`});let o=this.buildBacklinks();for(let[s,i]of a)(!o[s]||o[s].length===0)&&t.push({type:"orphan",article:i,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=k(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(b(t))for(let r of D(t)){let a=V(t,r),o=K(a);o.isDirectory()?this.walkDir(a,e):e(a,o)}}};export{B as a};
|
|
105
|
+
//# sourceMappingURL=chunk-NY7NHGVT.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.importanceProposed) frontmatter.push(`importance_proposed: ${meta.importanceProposed}`)\n if (meta.date) frontmatter.push(`date: ${meta.date}`)\n if (meta.rolledUpInto) frontmatter.push(`rolled_up_into: ${JSON.stringify(meta.rolledUpInto)}`)\n if (meta.aliases?.length) frontmatter.push(`aliases: ${JSON.stringify(meta.aliases)}`)\n if (meta.statements?.length) frontmatter.push(`statements: ${JSON.stringify(meta.statements)}`)\n frontmatter.push(\"---\", \"\", content)\n\n writeFileSync(fullPath, frontmatter.join(\"\\n\"))\n const action = existing ? \"update\" : \"create\"\n this.appendLog(action, `${meta.title} [${(meta.tags || []).slice(0, 5).join(\", \")}] by ${agentId} at ${path}`)\n return true\n }\n\n // --- Article Versioning ---\n\n /**\n * Save current article content as an immutable version before overwriting.\n * Versions stored in _versions/{article-path}/{timestamp}.md\n */\n private saveVersion(articlePath: string, fullPath: string): void {\n try {\n if (!existsSync(fullPath)) return\n const content = readFileSync(fullPath, \"utf-8\")\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\")\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n mkdirSync(versionDir, { recursive: true })\n // Two writes inside one millisecond share a timestamp: the later one\n // gets a counter suffix (`<ts>-1.md`, ...) instead of overwriting.\n for (let n = 0; ; n++) {\n try {\n writeFileSync(resolve(versionDir, `${n ? `${ts}-${n}` : ts}.md`), content, { flag: \"wx\" })\n return\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err\n }\n }\n } catch {\n // Version save is best-effort\n }\n }\n\n /**\n * List all versions of an article (newest first).\n */\n getVersions(articlePath: string): Array<{ timestamp: string; path: string }> {\n const versionDir = resolve(this.baseDir, \"_versions\", articlePath.replace(/\\.md$/, \"\"))\n if (!existsSync(versionDir)) return []\n\n try {\n return readdirSync(versionDir)\n .filter(f => f.endsWith(\".md\"))\n .sort(compareVersionNames)\n .reverse()\n .map(f => ({\n timestamp: f.replace(/\\.md$/, \"\").replace(/-/g, (m, i) => i < 19 ? (i === 10 ? \"T\" : i === 13 || i === 16 ? \":\" : \"-\") : m),\n path: resolve(versionDir, f),\n }))\n } catch {\n return []\n }\n }\n\n /**\n * Restore a specific version of an article.\n */\n restoreVersion(articlePath: string, versionTimestamp: string): boolean {\n const versions = this.getVersions(articlePath)\n const version = versions.find(v => v.timestamp === versionTimestamp)\n ?? versions.find(v => v.timestamp.startsWith(versionTimestamp))\n if (!version) return false\n\n try {\n const content = readFileSync(version.path, \"utf-8\")\n const fullPath = resolve(this.baseDir, articlePath)\n // Save current as a version too before restoring\n this.saveVersion(articlePath, fullPath)\n writeFileSync(fullPath, content)\n this.appendLog(\"restore\", `${articlePath} restored to ${versionTimestamp}`)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Read an article. Returns null if not found.\n */\n readArticle(path: string): WikiArticle | null {\n const fullPath = resolve(this.baseDir, path)\n if (!existsSync(fullPath)) return null\n\n const raw = readFileSync(fullPath, \"utf-8\")\n return this.parseArticle(raw, path)\n }\n\n /**\n * Read an article with permission check.\n */\n readArticleAs(path: string, agentId: string): WikiArticle | null {\n const article = this.readArticle(path)\n if (!article) return null\n if (!this.canRead(article.meta, agentId)) return null\n return article\n }\n\n private parseArticle(raw: string, path: string): WikiArticle | null {\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n if (!fmMatch) return null\n\n const fm = fmMatch[1]\n const content = fmMatch[2].trim()\n\n const get = (key: string): string => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"))\n return m?.[1]?.trim().replace(/^\"(.*)\"$/, \"$1\") || \"\"\n }\n\n const getArray = (key: string): string[] => {\n const m = fm.match(new RegExp(`^${key}:\\\\s*\\\\[(.*)\\\\]$`, \"m\"))\n if (!m) return []\n // Quoted items may hold commas — related titles often do, e.g.\n // \"Reviewed: NOT READY, Then READY\". Unquoted legacy items may not.\n // Items are written unescaped, so a quoted item may also hold quotes\n // (\"Carbon \"12 M\" Fix\"): it ends only at a quote before a comma or the end.\n return [...m[1].matchAll(/\\s*(?:\"(.*?)\"(?=\\s*(?:,|$))|([^,]+))/g)]\n .map(x => (x[1] ?? x[2]).trim())\n .filter(Boolean)\n }\n\n // `type` and `kind` are the new structural spine; no longer stuffed into tags.\n // Legacy articles may have a `kind:` field; we promote it to `type` on read so\n // the migration (Phase 2) can patch it in place.\n const rawType = get(\"type\") || get(\"kind\")\n const validTypes = new Set([\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\",\n ])\n const type = validTypes.has(rawType) ? (rawType as WikiArticleMeta[\"type\"]) : undefined\n\n const tags = getArray(\"tags\").filter((v, i, a) => v && a.indexOf(v) === i)\n const related = getArray(\"related\")\n const graphPath = getArray(\"graph_path\")\n const aliases = getArray(\"aliases\")\n const importance = get(\"importance\")\n const importanceProposed = get(\"importance_proposed\")\n const date = get(\"date\")\n return {\n meta: {\n title: get(\"title\"),\n type,\n related: related.length ? related : undefined,\n tags,\n owner: get(\"owner\"),\n access: (get(\"access\") as WikiAccess) || \"public\",\n sharedWith: getArray(\"shared_with\"),\n created: get(\"created\"),\n lastUpdated: get(\"last_updated\"),\n sources: getArray(\"sources\"),\n graphPath: graphPath.length ? graphPath : undefined,\n class: /^[a-z][a-z0-9_]*$/.test(get(\"class\")) ? get(\"class\") : undefined,\n importance: isImportance(importance) ? importance : undefined,\n importanceProposed: isImportance(importanceProposed) ? importanceProposed : undefined,\n date: /^\\d{4}-\\d{2}-\\d{2}/.test(date) ? date.slice(0, 10) : undefined,\n rolledUpInto: get(\"rolled_up_into\") || undefined,\n aliases: aliases.length ? aliases : undefined,\n statements: parseStatements(get(\"statements\")),\n },\n content,\n path,\n }\n }\n\n // --- Index and discovery ---\n\n /**\n * List all articles accessible to an agent.\n */\n /** Catalog per agent, valid while no article file changed. The walk is\n * repeated (names, mtimes, sizes) but the frontmatter parse of every\n * article is not; on a wiki of ten thousand files that parse was the\n * cost of every fresh session. */\n private listCache = new Map<string, { signature: string; articles: WikiArticle[] }>()\n\n listArticles(agentId: string): WikiArticle[] {\n return this.listCached(agentId)\n }\n\n /** Every article whatever its access, for the owner's own views. */\n listAllArticles(): WikiArticle[] {\n return this.listCached(null)\n }\n\n private listCached(agentId: string | null): WikiArticle[] {\n const relPaths: string[] = []\n const sig: string[] = []\n this.walkDir(this.baseDir, (filePath, stat) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n relPaths.push(relPath)\n sig.push(`${relPath}:${stat?.mtimeMs ?? \"?\"}:${stat?.size ?? \"?\"}`)\n })\n const signature = sig.join(\"|\")\n const key = agentId ?? \"\\u0000all\"\n const hit = this.listCache.get(key)\n if (hit && hit.signature === signature) return hit.articles.slice()\n\n const articles: WikiArticle[] = []\n for (const relPath of relPaths) {\n const article = this.readArticle(relPath)\n if (article && (agentId === null || this.canRead(article.meta, agentId))) {\n articles.push(article)\n }\n }\n this.listCache.set(key, { signature, articles })\n return articles.slice()\n }\n\n /**\n * Search articles by keyword. Returns articles the agent can read.\n */\n search(query: string, agentId: string, maxResults: number = 10): WikiArticle[] {\n const queryLower = query.toLowerCase()\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n // BM25 over article content (cached to disk)\n const docs = articles.map((a) => a.content)\n const cachePath = resolve(this.baseDir, \"_bm25_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(query, index)\n const scoreMap = new Map(bm25Scores.map((r) => [r.docIndex, r.score]))\n\n const results = articles.map((article, i) => {\n let score = scoreMap.get(i) ?? 0\n // Additive bonuses for title and tag matches\n if (article.meta.title.toLowerCase().includes(queryLower)) score += 10\n if (article.meta.tags?.some(t => t.toLowerCase().includes(queryLower))) score += 5\n return { article, score }\n })\n\n return results\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxResults)\n .map((r) => r.article)\n }\n\n /**\n * findRelevant, then re-ranked by the wiki-rerank seat.\n *\n * Recall comes from findRelevant rather than search() because\n * findRelevant is the function everything actually calls — search()\n * turned out to have no callers at all. Additive on purpose: the\n * synchronous findRelevant is untouched and its existing callers stay\n * as they are. Measured on the 12-query eval against this\n * wiki, re-ranking moves R@1 from 33.3% to 50.0% and R@3 from 41.7% to\n * 66.7%, for about $0.0005 and 550ms a query.\n *\n * Fail-open in every direction. Seat off, backend down, no key, fewer\n * than two candidates — all return BM25's own order, which is what the\n * caller would have got anyway.\n *\n * Note what this cannot do: it only reorders what BM25 shortlisted. In\n * the eval R@3 sat exactly on that ceiling, so every remaining miss was\n * an article BM25 never returned. Widening the shortlist does not fix\n * that — past 30 the extra candidates measurably diluted the ranking.\n */\n async findRelevantReranked(\n query: string,\n agentId?: string,\n maxResults = 10,\n opts: { shortlist?: number; excerptChars?: number } = {},\n ): Promise<WikiArticle[]> {\n const shortlist = Math.max(maxResults, opts.shortlist ?? DEFAULT_SHORTLIST)\n const pool = this.findRelevant(query, agentId, shortlist)\n if (pool.length < 2) return pool.slice(0, maxResults)\n\n const candidates: RerankCandidate[] = pool.map((article, i) => ({\n // Index, not title: titles are not unique across a wiki and a\n // Choice needs distinct keys.\n id: `c${i}`,\n title: article.meta.title || `(untitled ${i})`,\n tags: article.meta.tags,\n excerpt: article.content,\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query, candidates, excerptChars: opts.excerptChars }),\n rerankQuestions(candidates),\n { incumbent: { best: candidates[0].id }, features: { agent: agentId ?? \"unknown\" } },\n )\n if (!result || result.mode !== \"active\") return pool.slice(0, maxResults)\n\n const ranking = toRanking(result.answers as never, candidates)\n return ranking.ranked\n .map((id) => pool[Number(id.slice(1))])\n .filter((a): a is WikiArticle => Boolean(a))\n .slice(0, maxResults)\n }\n\n /**\n * Find articles relevant to a message (for context injection).\n *\n * Scoring:\n * - BM25 over title+tags+content (always)\n * - + ancestry bonus if the caller classified the message through the\n * intent graph and articles carry `graphPath` from a previous classification\n *\n * `weights.graph` is scaled against `weights.bm25`. When the caller omits\n * `messagePath`, retrieval collapses to pure BM25 and matches legacy behavior.\n */\n findRelevant(\n message: string,\n agentId?: string,\n maxArticles: number = 3,\n messagePath?: string[],\n weights: { graph: number; bm25: number } = { graph: 0.6, bm25: 0.4 },\n ): WikiArticle[] {\n const articles: WikiArticle[] = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article || !this.canRead(article.meta, agentId)) return\n articles.push(article)\n })\n\n if (articles.length === 0) return []\n\n const docs = articles.map(\n (a) => `${a.meta.title} ${(a.meta.tags || []).join(\" \")} ${a.content}`,\n )\n const cachePath = resolve(this.baseDir, \"_bm25_relevance_cache.json\")\n const index = buildIndexCached(docs, cachePath)\n const bm25Scores = scoreAll(message, index)\n\n // Normalize BM25 so the two signals live on [0,1] before the weighted sum.\n const maxBm25 = bm25Scores.reduce((m, s) => Math.max(m, s.score), 0) || 1\n const bm25Map = new Map(bm25Scores.map((s) => [s.docIndex, s.score / maxBm25]))\n\n const hasGraph = !!(messagePath && messagePath.length > 0)\n const scored = articles.map((article, i) => {\n const bm25 = bm25Map.get(i) ?? 0\n let ancestry = 0\n if (hasGraph && article.meta.graphPath?.length) {\n ancestry = ancestryOf(messagePath!, article.meta.graphPath)\n }\n // When the caller passed no path, BM25 gets the full weight.\n const combined = hasGraph\n ? weights.graph * ancestry + weights.bm25 * bm25\n : bm25\n return { article, score: combined }\n })\n\n return scored\n .filter((r) => r.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, maxArticles)\n .map((r) => r.article)\n }\n\n /**\n * Build context string from relevant wiki articles for prompt injection.\n * Token-efficient: includes title + first ~500 chars of each article.\n */\n buildContext(articles: WikiArticle[], maxChars: number = 4000): string {\n if (articles.length === 0) return \"\"\n\n const lines: string[] = [\"[Wiki Knowledge]\"]\n\n let totalChars = 0\n for (const article of articles) {\n const header = `\\n## ${article.meta.title} [${(article.meta.tags || []).slice(0, 3).join(\", \")}]`\n const body = article.content.length > 600\n ? article.content.slice(0, 600) + \"...\"\n : article.content\n\n const chunk = header + \"\\n\" + body\n if (totalChars + chunk.length > maxChars) break\n\n lines.push(chunk)\n totalChars += chunk.length\n }\n\n lines.push(\"\\n[End Wiki Knowledge]\")\n return lines.join(\"\\n\")\n }\n\n /**\n * Rebuild the master index.\n */\n rebuildIndex(): WikiIndex {\n const articles: WikiIndex[\"articles\"] = []\n const backlinks = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n // Count wikilinks for backlinks\n const links = article.content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n for (const link of links) {\n const target = link.replace(/\\[\\[|\\]\\]/g, \"\")\n backlinks.set(target, (backlinks.get(target) || 0) + 1)\n }\n\n // Extract aliases from title and tags\n const aliases = [article.meta.title.toLowerCase()]\n if (article.meta.tags) {\n aliases.push(...article.meta.tags.map(t => t.toLowerCase()))\n }\n\n articles.push({\n path: relPath,\n title: article.meta.title,\n type: article.meta.type,\n related: article.meta.related,\n tags: article.meta.tags || [],\n owner: article.meta.owner,\n access: article.meta.access,\n sharedWith: article.meta.sharedWith,\n aliases,\n backlinks: backlinks.get(article.meta.title) || 0,\n sources: article.meta.sources,\n lastUpdated: article.meta.lastUpdated,\n graphPath: article.meta.graphPath,\n })\n })\n\n const index: WikiIndex = {\n articles,\n lastRebuilt: new Date().toISOString(),\n }\n\n // Machine-readable index\n writeFileSync(\n resolve(this.baseDir, \"_index.json\"),\n JSON.stringify(index, null, 2),\n )\n\n // Farzapedia-style content catalog at _index.md — the one file the\n // agentic query reads to pick candidate articles by `type` + title.\n // Load-bearing in Phase 3; grouped by type, alphabetical within group.\n this.writeCatalog(articles, index.lastRebuilt)\n\n // Human-readable WIKI.md — legacy view, grouped by access level.\n const md = [\"# Wiki Index\", \"\", `Last rebuilt: ${index.lastRebuilt}`, \"\"]\n const byAccess = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.access || \"public\"\n const list = byAccess.get(bucket) || []\n list.push(a)\n byAccess.set(bucket, list)\n }\n for (const [bucket, list] of Array.from(byAccess.entries()).sort()) {\n md.push(`## ${bucket}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const t = a.type ? ` [${a.type}]` : \"\"\n md.push(`- [${a.title}](${a.path})${t} — owner: ${a.owner}`)\n }\n md.push(\"\")\n }\n writeFileSync(resolve(this.baseDir, \"WIKI.md\"), md.join(\"\\n\"))\n\n this.log(`Index rebuilt: ${articles.length} articles`)\n this.appendLog(\"rebuild-index\", `${articles.length} articles indexed`)\n return index\n }\n\n /**\n * Write `_index.md` — the Farzapedia-style content catalog grouped by\n * article `type`. This is the one file the agentic query (Phase 3) reads\n * to pick candidate articles before walking the wikilink subgraph.\n *\n * Articles without a `type` land in \"Untyped\" at the bottom; the Phase 2\n * migration backfills those.\n */\n private writeCatalog(\n articles: WikiIndex[\"articles\"],\n lastRebuilt: string,\n ): void {\n const typeOrder: Array<NonNullable<WikiArticleMeta[\"type\"]> | \"untyped\"> = [\n \"person\", \"project\", \"place\", \"concept\", \"event\", \"decision\", \"pattern\", \"untyped\",\n ]\n const typeHeaders: Record<string, string> = {\n person: \"## People\",\n project: \"## Projects\",\n place: \"## Places\",\n concept: \"## Concepts\",\n event: \"## Events\",\n decision: \"## Decisions\",\n pattern: \"## Patterns\",\n untyped: \"## Untyped (needs migration)\",\n }\n\n const byType = new Map<string, typeof articles>()\n for (const a of articles) {\n const bucket = a.type || \"untyped\"\n const list = byType.get(bucket) || []\n list.push(a)\n byType.set(bucket, list)\n }\n\n const lines: string[] = [\n \"# Wiki Content Catalog\",\n \"\",\n `_Last rebuilt: ${lastRebuilt}_`,\n \"\",\n \"Articles grouped by type. Agentic query walks this file first to pick candidates.\",\n \"\",\n ]\n\n for (const type of typeOrder) {\n const list = byType.get(type)\n if (!list || list.length === 0) continue\n lines.push(typeHeaders[type] || `## ${type}`, \"\")\n for (const a of list.sort((x, y) => x.title.localeCompare(y.title))) {\n const access = a.access === \"private\" ? \" (private)\" : a.access === \"shared\" ? \" (shared)\" : \"\"\n const related = a.related?.length ? ` → [[${a.related.slice(0, 3).join(\"]], [[\")}]]${a.related.length > 3 ? \", …\" : \"\"}` : \"\"\n lines.push(`- [${a.title}](${a.path})${access}${related}`)\n }\n lines.push(\"\")\n }\n\n writeFileSync(resolve(this.baseDir, \"_index.md\"), lines.join(\"\\n\"))\n }\n\n /**\n * Get wiki stats.\n */\n stats(): {\n totalArticles: number\n totalEntries: number\n articlesByType: Record<string, number>\n articlesByAccess: Record<string, number>\n articlesByOwner: Record<string, number>\n } {\n let totalArticles = 0\n const byType: Record<string, number> = {}\n const byAccess: Record<string, number> = {}\n const byOwner: Record<string, number> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n totalArticles++\n for (const tag of (article.meta.tags || [])) {\n byType[tag] = (byType[tag] || 0) + 1\n }\n byAccess[article.meta.access] = (byAccess[article.meta.access] || 0) + 1\n byOwner[article.meta.owner] = (byOwner[article.meta.owner] || 0) + 1\n })\n\n const entryFiles = existsSync(this.rawDir)\n ? readdirSync(this.rawDir).filter(f => f.endsWith(\".md\")).length\n : 0\n\n return {\n totalArticles,\n totalEntries: entryFiles,\n articlesByType: byType,\n articlesByAccess: byAccess,\n articlesByOwner: byOwner,\n }\n }\n\n // --- Helpers ---\n\n // --- Log (chronological, append-only) ---\n\n /**\n * Append an entry to log.md.\n * Format: ## [YYYY-MM-DD HH:MM] action | details\n */\n appendLog(action: string, details: string): void {\n const logPath = resolve(this.baseDir, \"log.md\")\n const timestamp = new Date().toISOString().replace(\"T\", \" \").slice(0, 16)\n const entry = `## [${timestamp}] ${action} | ${details}\\n\\n`\n\n if (!existsSync(logPath)) {\n writeFileSync(logPath, \"# Wiki Log\\n\\nChronological record of all wiki operations.\\n\\n\")\n }\n\n appendFileSync(logPath, entry)\n }\n\n /**\n * Get recent log entries.\n */\n getLog(limit: number = 20): string[] {\n const logPath = resolve(this.baseDir, \"log.md\")\n if (!existsSync(logPath)) return []\n\n const content = readFileSync(logPath, \"utf-8\")\n const entries = content.split(/^## /m).filter(e => e.startsWith(\"[\")).slice(-limit)\n return entries.map(e => e.trim())\n }\n\n // --- Schema ---\n\n /**\n * Create _schema.md if it doesn't exist.\n * This tells the LLM how to operate on the wiki.\n */\n private ensureSchema(): void {\n const schemaPath = resolve(this.baseDir, \"_schema.md\")\n if (existsSync(schemaPath)) return\n\n const schema = `# Wiki Schema\n\nA personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,\nstructure emerges from data. The wiki is a compounding artifact.\n\n## Structure\n\n\\`\\`\\`\nwiki/\n _schema.md # This file\n worldview.md # YOUR mental model — the LLM reads this during absorb\n raw/entries/ # Immutable raw sources (conversations, imports, anything)\n [LLM-chosen dirs] # Structure emerges from data — the LLM picks paths\n\\`\\`\\`\n\nThe LLM decides how to organize articles. You describe YOUR world in worldview.md.\n\n## Article Format\n\n\\`\\`\\`yaml\n---\ntitle: \"Staging Deployment Process\"\ntags: [\"deploy\", \"staging\", \"devops\", \"process\", \"2026-04-06\"]\nowner: devops-agent\naccess: public\ncreated: 2026-04-06\nlast_updated: 2026-04-06\nsources: [\"entry-id-1\", \"entry-id-2\"]\n---\n\nArticle content with [[wikilinks]] and section tags.\n\n## Deploy Steps\n<!-- tags: process, runbook, staging -->\nContent specific to this section...\n\\`\\`\\`\n\n## Tags\n\nTags are the primary context-narrowing mechanism. The more tags, the better.\n\nTag aggressively:\n- **Who**: people, agents, teams involved\n- **What**: project, client, topic, technology\n- **When**: dates, periods, milestones\n- **Where**: server, environment, channel\n- **How**: process, decision, pattern\n- **Your terms**: whatever vocabulary makes sense in YOUR world\n\nSection tags (\\`<!-- tags: ... -->\\`) let different parts of an article\nmatch different queries. A deploy article might have sections tagged\n\"runbook\" and \"incident\" separately.\n\n## Operations\n\n### Absorb\nRead raw entries → read worldview.md → tag aggressively → create/update articles.\nAlso identify GAPS: \"We mention X but have no article for it.\"\n\n### Query\nMatch by tags first → then keyword within matched articles → synthesize.\nIf agent is working on a specific project, only send content tagged for that project.\n\n### Lint\nCheck for: orphan articles, broken [[wikilinks]], untagged articles,\narticles over 100 lines that should split, mentioned-but-missing topics.\n\n## Worldview\n\nEdit \\`worldview.md\\` to describe YOUR world. This is not a schema — it's your\nmental model. The LLM reads it during absorb to understand where things go.\n\nExample worldview.md:\n\\`\\`\\`\nI'm the founder of Acme Corp.\nWe build software products.\nOur agents: Marketing Bot, DevOps Bot, Coordinator.\nClients: ClientA (enterprise), ClientB (startup).\nInfrastructure: local dev machine, cloud server.\nWe use GitLab for version control.\n\\`\\`\\`\n`\n\n writeFileSync(schemaPath, schema)\n this.log(\"Created _schema.md\")\n }\n\n // --- Wikilinks and Backlinks ---\n\n /**\n * Extract all [[wikilinks]] from article content.\n */\n extractWikilinks(content: string): string[] {\n const matches = content.match(/\\[\\[([^\\]]+)\\]\\]/g) || []\n return matches.map(m => m.replace(/\\[\\[|\\]\\]/g, \"\"))\n }\n\n /**\n * Build backlinks index: for each article, which other articles link to it.\n */\n buildBacklinks(): Record<string, string[]> {\n const backlinks: Record<string, string[]> = {}\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const content = readFileSync(filePath, \"utf-8\")\n const links = this.extractWikilinks(content)\n\n for (const link of links) {\n if (!backlinks[link]) backlinks[link] = []\n backlinks[link].push(relPath)\n }\n })\n\n // Save\n writeFileSync(\n resolve(this.baseDir, \"_backlinks.json\"),\n JSON.stringify(backlinks, null, 2),\n )\n\n return backlinks\n }\n\n /**\n * Get backlinks for a specific article title.\n */\n getBacklinks(title: string): string[] {\n const path = resolve(this.baseDir, \"_backlinks.json\")\n if (!existsSync(path)) return []\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\"))\n return data[title] || []\n } catch {\n return []\n }\n }\n\n // --- Tag-based filtering (Karpathy: tags are the context narrowing mechanism) ---\n\n /**\n * Find articles matching ANY of the given tags.\n * This is how agents get relevant context — only articles tagged with\n * the client/project/topic they're working on.\n */\n findByTags(tags: string[], agentId?: string, limit: number = 10): WikiArticle[] {\n const lowerTags = tags.map(t => t.toLowerCase())\n const results: Array<{ article: WikiArticle; score: number }> = []\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article) return\n if (agentId && !this.canRead(article.meta, agentId)) return\n\n // Score: how many of the requested tags match?\n const articleTags = (article.meta.tags || []).map(t => t.toLowerCase())\n // Also check section tags: <!-- tags: foo, bar -->\n const sectionTags = (article.content.match(/<!--\\s*tags?:\\s*([^>]+)\\s*-->/gi) || [])\n .flatMap(m => m.replace(/<!--\\s*tags?:\\s*|\\s*-->/gi, \"\").split(\",\").map(t => t.trim().toLowerCase()))\n\n const allTags = [...articleTags, ...sectionTags]\n const score = lowerTags.filter(t => allTags.includes(t)).length\n\n if (score > 0) {\n results.push({ article, score })\n }\n })\n\n return results\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(r => r.article)\n }\n\n /**\n * Get all unique tags across all articles.\n */\n getAllTags(): Map<string, number> {\n const tagCounts = new Map<string, number>()\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (!article?.meta.tags) return\n\n for (const tag of article.meta.tags) {\n tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1)\n }\n })\n\n return tagCounts\n }\n\n // --- Worldview (user's mental model — input to absorb) ---\n\n /**\n * Get the worldview file. This is the user's description of their world —\n * the LLM uses it during absorb to know where things go.\n * Returns null if not set.\n */\n getWorldview(): string | null {\n const path = resolve(this.baseDir, \"worldview.md\")\n if (!existsSync(path)) return null\n return readFileSync(path, \"utf-8\")\n }\n\n /**\n * Set the worldview. The user describes their world: companies, clients,\n * projects, team, processes. The LLM uses this as context during absorb.\n */\n setWorldview(content: string): void {\n writeFileSync(resolve(this.baseDir, \"worldview.md\"), content)\n this.appendLog(\"worldview\", \"Updated worldview\")\n }\n\n // --- Lint ---\n\n /**\n * Run a lint pass on the wiki. Returns issues found.\n */\n lint(): Array<{ type: string; article: string; message: string }> {\n const issues: Array<{ type: string; article: string; message: string }> = []\n const allTitles = new Set<string>()\n const allLinks = new Map<string, string[]>() // article -> outbound links\n const articlePaths = new Map<string, string>() // title -> path\n\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\") || relPath === \"WIKI.md\" || relPath === \"log.md\") return\n\n const article = this.readArticle(relPath)\n if (!article) return\n\n allTitles.add(article.meta.title)\n articlePaths.set(article.meta.title, relPath)\n\n const links = this.extractWikilinks(article.content)\n allLinks.set(relPath, links)\n\n // Check: article too long\n const lines = article.content.split(\"\\n\").length\n if (lines > 100) {\n issues.push({\n type: \"bloated\",\n article: relPath,\n message: `${lines} lines — consider splitting`,\n })\n }\n\n // Check: no sources\n if (!article.meta.sources?.length) {\n issues.push({\n type: \"unsourced\",\n article: relPath,\n message: \"No sources listed in frontmatter\",\n })\n }\n\n // Check: stub (too short)\n if (lines < 10 && article.content.trim().length < 100) {\n issues.push({\n type: \"stub\",\n article: relPath,\n message: \"Very short article — needs enrichment\",\n })\n }\n })\n\n // Check: broken wikilinks\n for (const [articlePath, links] of allLinks) {\n for (const link of links) {\n if (!allTitles.has(link)) {\n issues.push({\n type: \"broken-link\",\n article: articlePath,\n message: `[[${link}]] — target article not found`,\n })\n }\n }\n }\n\n // Check: orphan articles (no inbound links)\n const backlinks = this.buildBacklinks()\n for (const [title, path] of articlePaths) {\n if (!backlinks[title] || backlinks[title].length === 0) {\n issues.push({\n type: \"orphan\",\n article: path,\n message: `No other articles link to \"${title}\"`,\n })\n }\n }\n\n this.appendLog(\"lint\", `Found ${issues.length} issues`)\n return issues\n }\n\n // --- Absorb summary (for automated cron) ---\n\n /**\n * Get unabsorbed entries (entries not referenced by any article's sources field).\n */\n getUnabsorbedEntries(): WikiEntry[] {\n const allSources = new Set<string>()\n\n // Collect all source IDs referenced by articles\n this.walkDir(this.baseDir, (filePath) => {\n if (!filePath.endsWith(\".md\")) return\n const relPath = relative(this.baseDir, filePath)\n if (relPath.startsWith(\"raw/\") || relPath.startsWith(\"_\")) return\n\n const article = this.readArticle(relPath)\n if (article?.meta.sources) {\n for (const s of article.meta.sources) allSources.add(s)\n }\n })\n\n // Find entries not in any article's sources\n const entries = this.listEntries()\n return entries.filter(e => !allSources.has(e.id))\n }\n\n /**\n * Build an absorb prompt for unprocessed entries.\n * Returns a prompt string an agent can execute to compile entries into articles.\n */\n buildAbsorbPrompt(maxEntries: number = 20): string | null {\n const unabsorbed = this.getUnabsorbedEntries().slice(0, maxEntries)\n if (unabsorbed.length === 0) return null\n\n const entrySummaries = unabsorbed.map(e =>\n `[${e.date} ${e.agentId} via ${e.source}] ${e.content.slice(0, 200)}`\n ).join(\"\\n\\n\")\n\n return `/wiki absorb\\n\\nThere are ${unabsorbed.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.\\n\\n${entrySummaries}`\n }\n\n private walkDir(dir: string, callback: (filePath: string, stat?: Stats) => void): void {\n if (!existsSync(dir)) return\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n const stat = statSync(full)\n if (stat.isDirectory()) {\n this.walkDir(full, callback)\n } else {\n callback(full, stat)\n }\n }\n }\n}\n"],"mappings":"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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MAAM,EAAGD,CAAU,EAClE,GAAIC,EAAW,SAAW,EAAG,OAAO,KAEpC,IAAMC,EAAiBD,EAAW,IAAIf,GACpC,IAAIA,EAAE,QAAQA,EAAE,eAAeA,EAAE,WAAWA,EAAE,QAAQ,MAAM,EAAG,GAAG,GACpE,EAAE,KAAK;AAAA;AAAA,CAAM,EAEb,MAAO;AAAA;AAAA,YAA6Be,EAAW;AAAA;AAAA,EAA2GC,GAC5J,CAEQ,QAAQC,EAAaC,EAA0D,CACrF,GAAKrI,EAAWoI,CAAG,EACnB,QAAW5I,KAASW,EAAYiI,CAAG,EAAG,CACpC,IAAME,EAAOC,EAAKH,EAAK5I,CAAK,EACtBwD,EAAOwF,EAASF,CAAI,EACtBtF,EAAK,YAAY,EACnB,KAAK,QAAQsF,EAAMD,CAAQ,EAE3BA,EAASC,EAAMtF,CAAI,EAGzB,CACF","names":["readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","readdirSync","statSync","resolve","join","relative","dirname","init_seat","isImportance","s","IMPORTANCE_LEVELS","parseStatements","line","parsed","out","compareVersionNames","a","b","split","f","m","ta","na","tb","nb","WikiStore","baseDir","resolve","log","mkdirSync","article","agentId","entry","filename","filepath","frontmatter","k","v","writeFileSync","ids","existsSync","wanted","file","readdirSync","id","readFileSync","filter","files","entries","content","fmMatch","fm","body","get","key","KNOWN","meta","path","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","importanceProposed","date","relPaths","sig","filePath","stat","relPath","relative","signature","hit","articles","query","maxResults","queryLower","docs","cachePath","index","buildIndexCached","bm25Scores","scoreAll","scoreMap","r","score","opts","shortlist","DEFAULT_SHORTLIST","pool","candidates","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","toRanking","message","maxArticles","messagePath","weights","maxBm25","bm25Map","hasGraph","bm25","ancestry","ancestryScore","combined","maxChars","lines","totalChars","header","chunk","backlinks","links","link","target","md","byAccess","bucket","list","y","lastRebuilt","typeOrder","typeHeaders","byType","access","totalArticles","byOwner","tag","entryFiles","details","logPath","appendFileSync","limit","e","schemaPath","title","lowerTags","results","articleTags","sectionTags","allTags","tagCounts","issues","allTitles","allLinks","articlePaths","allSources","maxEntries","unabsorbed","entrySummaries","dir","callback","full","join","statSync"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{existsSync as U,readFileSync as v,statSync as B}from"fs";import{resolve as I}from"path";var A=new Map;function N(t){if(!A.has(t))try{A.set(t,new RegExp(t,"i"))}catch{A.set(t,null)}return A.get(t)??null}function R(t,a,o){let i=new Set(o.types.map(r=>r.id));if(t.class&&i.has(t.class))return t.class;let n=a.split("/").slice(0,-1).map(r=>r.toLowerCase()),e=new Set((t.tags??[]).map(r=>r.toLowerCase()));for(let r of o.classify){if(!i.has(r.type))continue;let c=0;if(!(r.legacy&&(c++,!t.type||!r.legacy.includes(t.type)))&&!(r.path&&(c++,!r.path.some(m=>n.includes(m.toLowerCase()))))&&!(r.tags&&(c++,!r.tags.some(m=>e.has(m.toLowerCase()))))){if(r.title){c++;let m=N(r.title);if(!m||!m.test(t.title))continue}if(c>0)return r.type}}return i.has(o.fallback_type)?o.fallback_type:o.types[0].id}function u(t){return t.normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/\.md$/,"").replace(/[^\p{L}\p{N}]+/gu," ").trim()}function E(t){return u(t).replace(/ /g,"-").slice(0,80)||"page"}var O=/\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]/g;function G(t){if(t.meta.date)return t.meta.date;let o=(t.path.split("/").pop()??"").match(/^(\d{4}-\d{2}-\d{2})/);if(o)return o[1];let i=t.meta.title.match(/(\d{4}-\d{2}-\d{2})/);return i?i[1]:(t.meta.created||t.meta.lastUpdated||"").slice(0,10)}function $(t,a,o){if(a.size===0||!o.types.some(e=>e.id==="agent"))return;let i=o.types.find(e=>e.id==="agent").pillar,n=new Set;for(let e of t.values()){let r=u(e.title).split(" ");e.type==="person"&&r.length>1&&n.add(r[0])}for(let e of t.values()){if(e.type!=="person"&&e.type!==o.fallback_type||e.pages.some(c=>c.article.meta.class))continue;let r=M(a,[e.title]);if(!r){let c=M(a,e.pages.flatMap(m=>m.article.meta.aliases??[]));c&&(e.review??=`an alias matches agent ${c}; set class on the page to decide`);continue}if(e.type==="person"&&n.has(u(e.title))){e.review=`shares a name with agent ${r} and with a person; set class on the page to decide`;continue}e.type="agent",e.pillar=i}}function L(t,a,o=new Map){let i=new Map(a.types.map(s=>[s.id,s])),n=new Map,e=new Map,r=new Set;for(let s of t){let p=[s.article.meta.title,...s.article.meta.aliases??[]].map(u).filter(Boolean);if(p.length===0)continue;let l=p.map(d=>n.get(d)).find(Boolean);if(!l){l=E(s.article.meta.title);for(let d=2;r.has(l);d++)l=`${E(s.article.meta.title)}-${d}`;r.add(l),e.set(l,[])}e.get(l).push(s);for(let d of p)n.has(d)||n.set(d,l);let f=u(s.article.path);n.has(f)||n.set(f,l)}let c=new Map;for(let[s,p]of e){let l=new Map;for(let g of p){let w=R(g.article.meta,g.article.path,a),W=g.article.meta.class===w?1e3:w===a.fallback_type?.5:1;l.set(w,(l.get(w)??0)+W)}let f=[...l.entries()].sort((g,w)=>w[1]-g[1])[0][0],d=p[0].article,b=p.map(g=>G(g.article)).filter(Boolean).sort(),P=p.map(g=>g.article.meta.importance).find(Boolean)??a.importance.default;c.set(s,{id:s,type:f,pillar:i.get(f)?.pillar??"topics",title:d.meta.title,pages:p,statements:[],date:b[0]??"",updated:p.map(g=>g.article.meta.lastUpdated||"").sort().pop()??"",importance:p.some(g=>g.article.meta.importance==="major")?"major":P,importanceProposed:p.map(g=>g.article.meta.importanceProposed).find(Boolean),rolledUpInto:p.map(g=>g.article.meta.rolledUpInto).find(Boolean),sources:[...new Set(p.flatMap(g=>g.article.meta.sources??[]))]})}$(c,o,a);let m=s=>n.get(u(s)),y=new Map,h=new Map,x=s=>{if(s.from===s.to)return;let p=y.get(s.from)??[];if(s.property==="related"&&p.some(f=>f.to===s.to))return;p.push(s),y.set(s.from,p);let l=h.get(s.to)??[];l.push(s),h.set(s.to,l)};for(let s of c.values())for(let p of s.pages)for(let l of p.article.meta.statements??[]){let f={...l,page:p,target:m(l.value)};s.statements.push(f),f.target&&x({from:s.id,to:f.target,property:l.property,statement:f})}for(let s of c.values())for(let p of s.pages){let l=new Set(p.article.meta.related??[]);for(let f of p.article.content.matchAll(O))l.add(f[1].trim());for(let f of l){let d=m(f);d&&x({from:s.id,to:d,property:"related"})}}for(let s of c.values())s.rolledUpInto&&(s.rolledUpInto=m(s.rolledUpInto));return{ontology:a,entities:c,outgoing:y,incoming:h,names:n}}var S=class{last=null;get(a,o,i=new Map){let n=[];for(let y of a.listAgents([]))for(let h of a.getAgentWiki(y).listAllArticles())n.push({agentId:y,article:h});let e=n.map(y=>y.article),r=[...i].join(`
|
|
2
|
+
`),c=this.last;if(c&&c.ontology===o&&c.roster===r&&c.refs.length===e.length&&c.refs.every((y,h)=>y===e[h]))return c.graph;let m=L(n,o,i);return this.last={refs:e,ontology:o,roster:r,graph:m},m}};function _(t,a=[]){let o=new Map,i=(n,e)=>{let r=n?u(n):"";r&&!o.has(r)&&o.set(r,e)};for(let n of t)(!n.name||u(n.name)!==`${u(n.id)} agent`)&&i(n.id,n.id),i(n.name,n.id),i(n.persona,n.id);for(let n of a)i(n,n);return o}function M(t,a){for(let o of a){let i=u(o),n=t.get(i)??t.get(i.replace(/ (agent|bot)$/,""));if(n)return n;if(/ (agent|bot)( |$)/.test(i)){for(let[e,r]of t)if(i.startsWith(`${e} `))return r}}}var j=["IDENTITY.md","persona.md","PERSONA.md"];function C(t){let o=t.match(/\*\*Name:\*\*[ \t]*([^\n(.,;—–]+)/)?.[1]?.replace(/[*_`]/g,"").trim();return o&&o.length<=40?o:void 0}function K(t){if(t)for(let a of j){let o=I(t,a);try{if(U(o)){let i=C(v(o,"utf-8"));if(i)return i}}catch{}}}var k=null;function D(t){let a=I(t,"..","..","agentx.json"),o;try{o=B(a).mtimeMs}catch{return[]}if(k&&k.file===a&&k.mtimeMs===o)return k.agents;let i=[];try{let n=JSON.parse(v(a,"utf-8"));i=Object.entries(n.agents??{}).map(([e,r])=>({id:e,name:typeof r?.name=="string"?r.name:void 0,persona:K(typeof r?.workspace=="string"?r.workspace:void 0)}))}catch{i=[]}return k={file:a,mtimeMs:o,agents:i},i}function Q(t,a,o=[]){let i=D(t),n=new Set(i.map(e=>e.id));return _([...i,...a.filter(e=>!n.has(e)).map(e=>({id:e}))],o)}export{_ as a,M as b,C as c,D as d,Q as e,u as f,E as g,L as h,S as i};
|
|
3
|
+
//# sourceMappingURL=chunk-QAWKN2N4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/ontology/roster.ts","../src/wiki/ontology/classify.ts","../src/wiki/ontology/graph.ts"],"sourcesContent":["// --- Names the fleet's agents go by, so their pages are not people (#819) ---\n//\n// Old pages about an agent often carry `type: person` and a title that is\n// just the agent's name (\"Helper\", or a persona name). The classify rules\n// only catch titles with \"agent\" or \"bot\" in them. The roster lists every\n// name an agent answers to: its id, its configured name, the persona name\n// in its workspace, and any extra names the owner lists under\n// `agent_names` in ontology.yaml (agents on another node, for example).\n// Deterministic: no model call.\n\nimport { existsSync, readFileSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { normName } from \"./graph\"\n\n/** Normalised name → agent id. */\nexport type AgentRoster = Map<string, string>\n\nexport interface RosterAgent {\n id: string\n name?: string\n /** Persona name read from the agent's workspace. */\n persona?: string\n}\n\nexport function buildRoster(agents: RosterAgent[], extraNames: string[] = []): AgentRoster {\n const roster: AgentRoster = new Map()\n const add = (name: string | undefined, id: string): void => {\n const key = name ? normName(name) : \"\"\n if (key && !roster.has(key)) roster.set(key, id)\n }\n for (const a of agents) {\n // An agent named \"<id> Agent\" is named after a person: the bare id\n // is that person's name, so only the full name points at the agent.\n if (!a.name || normName(a.name) !== `${normName(a.id)} agent`) add(a.id, a.id)\n add(a.name, a.id)\n add(a.persona, a.id)\n }\n for (const n of extraNames) add(n, n)\n return roster\n}\n\n/** The agent a title or alias names, if any. \"<name> agent\" counts too. */\nexport function rosterMatch(roster: AgentRoster, names: string[]): string | undefined {\n for (const n of names) {\n const key = normName(n)\n const hit = roster.get(key) ?? roster.get(key.replace(/ (agent|bot)$/, \"\"))\n if (hit) return hit\n // \"Release Helper (release_helper_bot)\": an agent name, then its handle.\n if (/ (agent|bot)( |$)/.test(key)) {\n for (const [name, id] of roster) if (key.startsWith(`${name} `)) return id\n }\n }\n return undefined\n}\n\nconst PERSONA_FILES = [\"IDENTITY.md\", \"persona.md\", \"PERSONA.md\"]\n\n/** `**Name:** Nova (…)` → \"Nova\". Only a short single name counts. */\nexport function personaName(text: string): string | undefined {\n const m = text.match(/\\*\\*Name:\\*\\*[ \\t]*([^\\n(.,;—–]+)/)\n const name = m?.[1]?.replace(/[*_`]/g, \"\").trim()\n return name && name.length <= 40 ? name : undefined\n}\n\nfunction readPersona(workspace: string | undefined): string | undefined {\n if (!workspace) return undefined\n for (const f of PERSONA_FILES) {\n const file = resolve(workspace, f)\n try {\n if (existsSync(file)) {\n const name = personaName(readFileSync(file, \"utf-8\"))\n if (name) return name\n }\n } catch {\n // An unreadable workspace file just means no persona name.\n }\n }\n return undefined\n}\n\nlet cached: { file: string; mtimeMs: number; agents: RosterAgent[] } | null = null\n\n/** Agents configured in the `agentx.json` next to the wiki (`<root>/.agentx/wiki`). */\nexport function configuredAgents(wikiDir: string): RosterAgent[] {\n const file = resolve(wikiDir, \"..\", \"..\", \"agentx.json\")\n let mtimeMs: number\n try { mtimeMs = statSync(file).mtimeMs } catch { return [] }\n if (cached && cached.file === file && cached.mtimeMs === mtimeMs) return cached.agents\n let agents: RosterAgent[] = []\n try {\n const raw = JSON.parse(readFileSync(file, \"utf-8\")) as { agents?: Record<string, { name?: unknown; workspace?: unknown }> }\n agents = Object.entries(raw.agents ?? {}).map(([id, a]) => ({\n id,\n name: typeof a?.name === \"string\" ? a.name : undefined,\n persona: readPersona(typeof a?.workspace === \"string\" ? a.workspace : undefined),\n }))\n } catch {\n agents = [] // a config being rewritten; the next request reads it again\n }\n cached = { file, mtimeMs, agents }\n return agents\n}\n\n/** Roster for a wiki: its agent folders, the node's config, and `agent_names`. */\nexport function loadRoster(wikiDir: string, agentIds: string[], extraNames: string[] = []): AgentRoster {\n const configured = configuredAgents(wikiDir)\n const known = new Set(configured.map(a => a.id))\n return buildRoster([...configured, ...agentIds.filter(id => !known.has(id)).map(id => ({ id }))], extraNames)\n}\n","// --- Give a wiki page its ontology type (#811) ---\n\nimport type { WikiArticleMeta } from \"../types\"\nimport type { Ontology } from \"./types\"\n\nconst patternCache = new Map<string, RegExp | null>()\n\nfunction titlePattern(src: string): RegExp | null {\n if (!patternCache.has(src)) {\n try {\n patternCache.set(src, new RegExp(src, \"i\"))\n } catch {\n patternCache.set(src, null) // reported by checkOntology; the rule never matches\n }\n }\n return patternCache.get(src) ?? null\n}\n\n/**\n * The page's own `class` when the ontology knows it, else the first\n * classify rule whose every condition matches, else the fallback type.\n * `path` is relative to the agent's wiki, e.g. `clients/example.md`.\n */\nexport function classifyPage(meta: WikiArticleMeta, path: string, o: Ontology): string {\n const known = new Set(o.types.map(t => t.id))\n if (meta.class && known.has(meta.class)) return meta.class\n\n const folders = path.split(\"/\").slice(0, -1).map(f => f.toLowerCase())\n const tags = new Set((meta.tags ?? []).map(t => t.toLowerCase()))\n for (const rule of o.classify) {\n if (!known.has(rule.type)) continue\n let conditions = 0\n if (rule.legacy) {\n conditions++\n if (!meta.type || !rule.legacy.includes(meta.type)) continue\n }\n if (rule.path) {\n conditions++\n if (!rule.path.some(p => folders.includes(p.toLowerCase()))) continue\n }\n if (rule.tags) {\n conditions++\n if (!rule.tags.some(t => tags.has(t.toLowerCase()))) continue\n }\n if (rule.title) {\n conditions++\n const re = titlePattern(rule.title)\n if (!re || !re.test(meta.title)) continue\n }\n if (conditions > 0) return rule.type\n }\n return known.has(o.fallback_type) ? o.fallback_type : o.types[0].id\n}\n","// --- One entity per real thing, across every agent's wiki (#811) ---\n//\n// Agents each keep their own pages, so the same person or server can\n// have several. The graph merges pages that share a name (title or\n// alias) into one entity, gives it a type from the ontology, and turns\n// statements and plain links into edges both ways. It is rebuilt only\n// when a page or the ontology changed.\n\nimport type { WikiArticle } from \"../types\"\nimport type { WikiHub } from \"../hub\"\nimport { classifyPage } from \"./classify\"\nimport { rosterMatch, type AgentRoster } from \"./roster\"\nimport type { Importance, Ontology, WikiStatement } from \"./types\"\n\nexport interface GraphPage {\n agentId: string\n article: WikiArticle\n}\n\nexport interface EntityStatement extends WikiStatement {\n /** Entity id of the value when it names a page. */\n target?: string\n page: GraphPage\n}\n\nexport interface Entity {\n id: string\n type: string\n pillar: string\n title: string\n pages: GraphPage[]\n statements: EntityStatement[]\n /** YYYY-MM-DD: the event date, else the first page's creation date. */\n date: string\n updated: string\n importance: Importance\n /** A level a job suggests; only the owner may set it. */\n importanceProposed?: Importance\n rolledUpInto?: string\n /** Raw entry ids the pages were written from. */\n sources: string[]\n /** Why the type needs a person to check it (#819). */\n review?: string\n}\n\nexport interface Edge {\n from: string\n to: string\n property: string\n statement?: EntityStatement\n}\n\nexport interface WikiGraph {\n ontology: Ontology\n entities: Map<string, Entity>\n outgoing: Map<string, Edge[]>\n incoming: Map<string, Edge[]>\n /** Normalised name or path → entity id, for links. */\n names: Map<string, string>\n}\n\nexport function normName(s: string): string {\n return s.normalize(\"NFKD\").replace(/[̀-ͯ]/g, \"\").toLowerCase().replace(/\\.md$/, \"\").replace(/[^\\p{L}\\p{N}]+/gu, \" \").trim()\n}\n\nexport function slugify(s: string): string {\n return normName(s).replace(/ /g, \"-\").slice(0, 80) || \"page\"\n}\n\nconst WIKILINK = /\\[\\[([^\\]|#]+)(?:[|#][^\\]]*)?\\]\\]/g\n\nfunction eventDate(a: WikiArticle): string {\n if (a.meta.date) return a.meta.date\n const base = a.path.split(\"/\").pop() ?? \"\"\n const fromPath = base.match(/^(\\d{4}-\\d{2}-\\d{2})/)\n if (fromPath) return fromPath[1]\n const fromTitle = a.meta.title.match(/(\\d{4}-\\d{2}-\\d{2})/)\n if (fromTitle) return fromTitle[1]\n return (a.meta.created || a.meta.lastUpdated || \"\").slice(0, 10)\n}\n\n/**\n * Pages named after one of the fleet's agents are agents, not people\n * (#819). A page's own `class` still wins. When the name is also the\n * first name of a person page (\"Sam\" next to \"Sam Lee\"), the page keeps\n * its type and is flagged instead of guessed.\n */\nfunction applyRoster(entities: Map<string, Entity>, roster: AgentRoster, o: Ontology): void {\n if (roster.size === 0 || !o.types.some(t => t.id === \"agent\")) return\n const agentPillar = o.types.find(t => t.id === \"agent\")!.pillar\n const firstNames = new Set<string>()\n for (const e of entities.values()) {\n const words = normName(e.title).split(\" \")\n if (e.type === \"person\" && words.length > 1) firstNames.add(words[0])\n }\n for (const e of entities.values()) {\n // Only people and untyped pages: a project or client can share an agent's name.\n if ((e.type !== \"person\" && e.type !== o.fallback_type) || e.pages.some(p => p.article.meta.class)) continue\n const agent = rosterMatch(roster, [e.title])\n if (!agent) {\n // An alias is weaker evidence: a person can have a nickname that is\n // also an agent's name. Flag it, never retype it.\n const byAlias = rosterMatch(roster, e.pages.flatMap(p => p.article.meta.aliases ?? []))\n if (byAlias) e.review ??= `an alias matches agent ${byAlias}; set class on the page to decide`\n continue\n }\n if (e.type === \"person\" && firstNames.has(normName(e.title))) {\n e.review = `shares a name with agent ${agent} and with a person; set class on the page to decide`\n continue\n }\n e.type = \"agent\"\n e.pillar = agentPillar\n }\n}\n\n/** Build the graph from pages. Pure: tests call it directly. */\nexport function buildGraph(pages: GraphPage[], o: Ontology, roster: AgentRoster = new Map()): WikiGraph {\n const typeDef = new Map(o.types.map(t => [t.id, t]))\n const names = new Map<string, string>()\n const groups = new Map<string, GraphPage[]>()\n const usedIds = new Set<string>()\n\n for (const page of pages) {\n const keys = [page.article.meta.title, ...(page.article.meta.aliases ?? [])].map(normName).filter(Boolean)\n if (keys.length === 0) continue\n let id = keys.map(k => names.get(k)).find(Boolean)\n if (!id) {\n id = slugify(page.article.meta.title)\n for (let n = 2; usedIds.has(id); n++) id = `${slugify(page.article.meta.title)}-${n}`\n usedIds.add(id)\n groups.set(id, [])\n }\n groups.get(id)!.push(page)\n for (const k of keys) if (!names.has(k)) names.set(k, id)\n const pathKey = normName(page.article.path)\n if (!names.has(pathKey)) names.set(pathKey, id)\n }\n\n const entities = new Map<string, Entity>()\n for (const [id, group] of groups) {\n const votes = new Map<string, number>()\n for (const p of group) {\n const t = classifyPage(p.article.meta, p.article.path, o)\n // An explicit class outvotes any number of inferred ones.\n const weight = p.article.meta.class === t ? 1000 : t === o.fallback_type ? 0.5 : 1\n votes.set(t, (votes.get(t) ?? 0) + weight)\n }\n const type = [...votes.entries()].sort((a, b) => b[1] - a[1])[0][0]\n const first = group[0].article\n const dated = group.map(p => eventDate(p.article)).filter(Boolean).sort()\n const importance = group.map(p => p.article.meta.importance).find(Boolean) ?? o.importance.default\n entities.set(id, {\n id,\n type,\n pillar: typeDef.get(type)?.pillar ?? \"topics\",\n title: first.meta.title,\n pages: group,\n statements: [],\n date: dated[0] ?? \"\",\n updated: group.map(p => p.article.meta.lastUpdated || \"\").sort().pop() ?? \"\",\n importance: group.some(p => p.article.meta.importance === \"major\") ? \"major\" : importance,\n importanceProposed: group.map(p => p.article.meta.importanceProposed).find(Boolean),\n rolledUpInto: group.map(p => p.article.meta.rolledUpInto).find(Boolean),\n sources: [...new Set(group.flatMap(p => p.article.meta.sources ?? []))],\n })\n }\n applyRoster(entities, roster, o)\n\n const resolveName = (s: string): string | undefined => names.get(normName(s))\n const outgoing = new Map<string, Edge[]>()\n const incoming = new Map<string, Edge[]>()\n const addEdge = (e: Edge): void => {\n if (e.from === e.to) return\n const out = outgoing.get(e.from) ?? []\n if (e.property === \"related\" && out.some(x => x.to === e.to)) return\n out.push(e)\n outgoing.set(e.from, out)\n const inc = incoming.get(e.to) ?? []\n inc.push(e)\n incoming.set(e.to, inc)\n }\n\n for (const entity of entities.values()) {\n for (const page of entity.pages) {\n for (const s of page.article.meta.statements ?? []) {\n const st: EntityStatement = { ...s, page, target: resolveName(s.value) }\n entity.statements.push(st)\n if (st.target) addEdge({ from: entity.id, to: st.target, property: s.property, statement: st })\n }\n }\n }\n // Plain links after typed ones, so a typed edge wins over \"related\".\n for (const entity of entities.values()) {\n for (const page of entity.pages) {\n const linked = new Set(page.article.meta.related ?? [])\n for (const m of page.article.content.matchAll(WIKILINK)) linked.add(m[1].trim())\n for (const name of linked) {\n const to = resolveName(name)\n if (to) addEdge({ from: entity.id, to, property: \"related\" })\n }\n }\n }\n for (const e of entities.values()) {\n if (e.rolledUpInto) e.rolledUpInto = resolveName(e.rolledUpInto)\n }\n return { ontology: o, entities, outgoing, incoming, names }\n}\n\n/** Builds from a hub, reusing the last graph while no page changed. */\nexport class GraphCache {\n private last: { refs: WikiArticle[]; ontology: Ontology; roster: string; graph: WikiGraph } | null = null\n\n get(hub: WikiHub, o: Ontology, roster: AgentRoster = new Map()): WikiGraph {\n const pages: GraphPage[] = []\n for (const agentId of hub.listAgents([])) {\n for (const article of hub.getAgentWiki(agentId).listAllArticles()) pages.push({ agentId, article })\n }\n // The store hands back the same objects while files are unchanged.\n const refs = pages.map(p => p.article)\n const rosterKey = [...roster].join(\"\\n\")\n const last = this.last\n if (last && last.ontology === o && last.roster === rosterKey && last.refs.length === refs.length && last.refs.every((r, i) => r === refs[i])) {\n return last.graph\n }\n const graph = buildGraph(pages, o, roster)\n this.last = { refs, ontology: o, roster: rosterKey, graph }\n return graph\n }\n}\n"],"mappings":"AAUA,OAAS,cAAAA,EAAY,gBAAAC,EAAc,YAAAC,MAAgB,KACnD,OAAS,WAAAC,MAAe,OCNxB,IAAMC,EAAe,IAAI,IAEzB,SAASC,EAAaC,EAA4B,CAChD,GAAI,CAACF,EAAa,IAAIE,CAAG,EACvB,GAAI,CACFF,EAAa,IAAIE,EAAK,IAAI,O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AEF,EAGJ,CAEA,IAAImB,EAA0E,KAGvE,SAASC,EAAiBC,EAAgC,CAC/D,IAAMN,EAAOC,EAAQK,EAAS,KAAM,KAAM,aAAa,EACnDC,EACJ,GAAI,CAAEA,EAAUC,EAASR,CAAI,EAAE,OAAQ,MAAE,CAAQ,MAAO,CAAC,CAAE,CAC3D,GAAII,GAAUA,EAAO,OAASJ,GAAQI,EAAO,UAAYG,EAAS,OAAOH,EAAO,OAChF,IAAIvB,EAAwB,CAAC,EAC7B,GAAI,CACF,IAAM4B,EAAM,KAAK,MAAMN,EAAaH,EAAM,OAAO,CAAC,EAClDnB,EAAS,OAAO,QAAQ4B,EAAI,QAAU,CAAC,CAAC,EAAE,IAAI,CAAC,CAACvB,EAAIG,CAAC,KAAO,CAC1D,GAAAH,EACA,KAAM,OAAOG,GAAG,MAAS,SAAWA,EAAE,KAAO,OAC7C,QAASQ,EAAY,OAAOR,GAAG,WAAc,SAAWA,EAAE,UAAY,MAAS,CACjF,EAAE,CACJ,MAAE,CACAR,EAAS,CAAC,CACZ,CACA,OAAAuB,EAAS,CAAE,KAAAJ,EAAM,QAAAO,EAAS,OAAA1B,CAAO,EAC1BA,CACT,CAGO,SAAS6B,EAAWJ,EAAiBK,EAAoB7B,EAAuB,CAAC,EAAgB,CACtG,IAAM8B,EAAaP,EAAiBC,CAAO,EACrCO,EAAQ,IAAI,IAAID,EAAW,IAAIvB,GAAKA,EAAE,EAAE,CAAC,EAC/C,OAAOT,EAAY,CAAC,GAAGgC,EAAY,GAAGD,EAAS,OAAOzB,GAAM,CAAC2B,EAAM,IAAI3B,CAAE,CAAC,EAAE,IAAIA,IAAO,CAAE,GAAAA,CAAG,EAAE,CAAC,EAAGJ,CAAU,CAC9G","names":["existsSync","readFileSync","statSync","resolve","patternCache","titlePattern","src","classifyPage","meta","path","known","t","folders","f","tags","rule","conditions","p","re","normName","s","slugify","WIKILINK","eventDate","a","fromPath","fromTitle","applyRoster","entities","roster","t","agentPillar","firstNames","words","p","agent","rosterMatch","byAlias","buildGraph","pages","o","typeDef","names","groups","usedIds","page","keys","id","k","n","pathKey","group","votes","classifyPage","weight","type","b","first","dated","importance","resolveName","outgoing","incoming","addEdge","e","out","x","inc","entity","st","linked","m","name","to","GraphCache","hub","agentId","article","refs","rosterKey","last","r","i","graph","buildRoster","agents","extraNames","roster","add","name","id","key","normName","a","rosterMatch","names","n","hit","PERSONA_FILES","personaName","text","readPersona","workspace","f","file","resolve","existsSync","readFileSync","cached","configuredAgents","wikiDir","mtimeMs","statSync","raw","loadRoster","agentIds","configured","known"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as St,c as At}from"./chunk-QSKG754X.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-SSQMFHSM.js";import{c as ft,e as gt,f as mt}from"./chunk-KA2UIZXG.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{
|
|
1
|
+
import{b as St,c as At}from"./chunk-QSKG754X.js";import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-SSQMFHSM.js";import{c as ft,e as gt,f as mt}from"./chunk-KA2UIZXG.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-4XMALK7X.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var Ft=200,nr=7,jt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ne(e,".agentx/memory"),this.ledger=new ft(ne(e,".agentx/wiki")),Mt(this.memoryDir)||er(this.memoryDir,{recursive:!0})}filePath(e){return ne(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||$e(t.content))return!1;let r=t.source.trust??dt(t.source.channel),o=t.review??lt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Xn(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Mt(t))return[];try{let{mtimeMs:r,size:o}=tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Et(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Ae);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ne(this.memoryDir,`${t}_bm25_cache.json`),i=it(s,a),d=ot(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),c=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(c.length===0)return o.slice(-r);let f=c.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Ot(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Dt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Pe(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -38,4 +38,4 @@ ${n.text}`}async function me(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
38
38
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Xe(this.file))try{let e=JSON.parse(et(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Sn(xn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Tn(4).toString("hex")}.tmp`;Rn(t,JSON.stringify(e,null,2)+`
|
|
39
39
|
`,{encoding:"utf-8",mode:384}),An(t,this.file)}};import{extname as li}from"path";var Nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Dn=/<agentx-artifact>[\s\S]*$/i;function ld(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Nn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Dn,""):s).trim(),artifacts:r}}function ud(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Nn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Dn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ui={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},cd={bytes:20*1024*1024,perMessage:20,pathChars:512};function pd(n){return ui[li(n).toLowerCase()]??null}var ci=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
40
40
|
`);function fd(n,e,t){return n==="app"&&e&&t!==!1?ci:void 0}import{lstatSync as nt,mkdirSync as pi,readdirSync as fi,realpathSync as tt,unlinkSync as gi}from"fs";import{join as be,resolve as On}from"path";var En=".agentx/outbox",mi=7*24*60*60*1e3;function hi(n,e){try{let t=tt(On(e,n)),r=be(t,En);return tt(r)===r&&nt(r).isDirectory()?r:null}catch{return null}}function wd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=tt(On(t,n));nt(be(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||pi(be(o,En),{recursive:!0})}catch{return 0}let r=hi(n,t);return r?Mn(r,(e.now??Date.now())-(e.maxAgeMs??mi)):0}function Mn(n,e){let t=0;for(let r of fi(n)){let o=be(n,r);try{let s=nt(o);s.isDirectory()?t+=Mn(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(gi(o),t++)}catch{}}return t}export{Tt as a,jt as b,Ct as c,Di as d,ir as e,Oi as f,T as g,z as h,S as i,oe as j,Ir as k,Oe as l,F as m,Fe as n,Ce as o,Ge as p,To as q,Mo as r,Qe as s,_r as t,Go as u,Na as v,Da as w,Oa as x,Ea as y,Ma as z,Vo as A,Qo as B,Fa as C,ja as D,Ca as E,_a as F,Ha as G,Ka as H,Ba as I,qa as J,za as K,Ja as L,Ya as M,Ga as N,Va as O,Qa as P,Za as Q,ri as R,Xa as S,ed as T,td as U,nd as V,Wn as W,ld as X,ud as Y,cd as Z,pd as _,fd as $,En as aa,wd as ba};
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-QDWEM4DG.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var e=["minor","normal","major"];export{e as a};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-RGZARSHV.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/ontology/types.ts"],"sourcesContent":["// --- Wiki ontology types (#811) ---\n//\n// The ontology says what kinds of things the wiki holds (types grouped\n// into pillars), how they relate (properties), how important an event is,\n// and how each type's page is viewed (lenses). Every value here comes\n// from `ontology.yaml` in the wiki root, falling back to the generic\n// defaults in `defaults.ts`. Nothing about a particular organisation\n// belongs in code.\n\nexport type Importance = \"minor\" | \"normal\" | \"major\"\n\nexport const IMPORTANCE_LEVELS: readonly Importance[] = [\"minor\", \"normal\", \"major\"] as const\n\nexport interface PillarDef {\n id: string\n label: string\n /** One line under the pillar title. */\n description?: string\n /** Icon name from the view's small built-in icon set. */\n icon?: string\n /** Shown in the sidebar. A fallback pillar such as Topics sets false. */\n sidebar?: boolean\n}\n\nexport interface TypeDef {\n id: string\n label: string\n plural?: string\n pillar: string\n /** schema.org class, shown as a hint on the page. */\n schema?: string\n icon?: string\n /** Panels the page opens with, in order. */\n lens?: LensPanel[]\n}\n\nexport interface PropertyDef {\n id: string\n /** Read from the subject: \"Person — role at → Organization\". */\n label: string\n /** Read from the value's side: \"Organization — people ← Person\". */\n inverse?: string\n /** Wikidata property id, kept as a mapping hint. */\n wikidata?: string\n /** Types the value is expected to be. Informational. */\n range?: string[]\n /** Types the subject may be. A lens shows other subjects' statements\n * through the inverse; `wiki enrich` writes it only on these (#820). */\n domain?: string[]\n}\n\nexport type PanelSource = \"statements\" | \"linked\" | \"history\" | \"discussed\" | \"readings\" | \"notes\"\n\nexport interface LensPanel {\n /** Panel id. Used in the zoom URL, so keep it short and stable. */\n panel: string\n title?: string\n /** Where items come from. Inferred from the other fields when omitted. */\n source?: PanelSource\n /** Properties to show (statements panels). `related` covers plain links. */\n from?: string | string[]\n /** Keep only items whose other end has one of these types. */\n types?: string[]\n /** Items shown at the overview level (Z2). The full list is Z3. */\n show?: number\n group_by?: \"role\" | \"property\"\n display?: \"list\" | \"timeline\"\n /** History: importance levels shown unfolded. */\n importance?: Importance[]\n /** History: levels folded under a count. */\n fold?: Importance\n /** History: repeated minor events shown as one recurring line. */\n rollup?: { min: number; days: number }\n /** Readings: only the latest value per metric. */\n latest?: boolean\n /** `owner` marks the panel as private to the owner. */\n access?: \"owner\"\n}\n\nexport interface ClassifyRule {\n /** Type the matching page gets. */\n type: string\n /** Match when the page's legacy `type` is one of these. */\n legacy?: string[]\n /** Match when the page path starts with one of these folders. */\n path?: string[]\n /** Match when the page has any of these tags. */\n tags?: string[]\n /** Case-insensitive regular expression on the title. */\n title?: string\n}\n\nexport interface Ontology {\n version: number\n pillars: PillarDef[]\n types: TypeDef[]\n properties: PropertyDef[]\n importance: {\n default: Importance\n /** Who may set `major`: \"owner\" means agents can only propose it. */\n major_set_by: \"owner\" | \"anyone\"\n rollup: { min: number; days: number }\n }\n sidebar: {\n pins_max: number\n /** Page titles the owner pinned, in order. */\n pins: string[]\n }\n /** Rules that give a page a type, tried in order. The first match wins. */\n classify: ClassifyRule[]\n /** Type for pages no rule matches. */\n fallback_type: string\n /** Extra names of the fleet's agents, for agents that run on another\n * node or answer to a persona name (#819). The node's own agent ids,\n * configured names and persona names are found without this. */\n agent_names?: string[]\n}\n\n/** One typed fact about a page: subject (the page) → property → value. */\nexport interface WikiStatement {\n property: string\n /** A page title (becomes a link) or a literal value. */\n value: string\n role?: string\n since?: string\n until?: string\n /** Metric name for readings (disk_used, uptime). */\n metric?: string\n /** When a reading was taken. */\n at?: string\n /** Where it comes from: entry id, document, gazette reference, article. */\n source?: string\n access?: \"public\" | \"shared\" | \"private\"\n status?: \"proposed\" | \"confirmed\"\n confirmed_by?: string\n checked_at?: string\n /** The job that wrote it, e.g. \"wiki-enrich\"; its next run replaces it. */\n by?: string\n note?: string\n}\n"],"mappings":"AAWO,IAAMA,EAA2C,CAAC,QAAS,SAAU,OAAO","names":["IMPORTANCE_LEVELS"]}
|
|
1
|
+
{"version":3,"sources":["../src/wiki/ontology/types.ts"],"sourcesContent":["// --- Wiki ontology types (#811) ---\n//\n// The ontology says what kinds of things the wiki holds (types grouped\n// into pillars), how they relate (properties), how important an event is,\n// and how each type's page is viewed (lenses). Every value here comes\n// from `ontology.yaml` in the wiki root, falling back to the generic\n// defaults in `defaults.ts`. Nothing about a particular organisation\n// belongs in code.\n\nexport type Importance = \"minor\" | \"normal\" | \"major\"\n\nexport const IMPORTANCE_LEVELS: readonly Importance[] = [\"minor\", \"normal\", \"major\"] as const\n\nexport interface PillarDef {\n id: string\n label: string\n /** One line under the pillar title. */\n description?: string\n /** Icon name from the view's small built-in icon set. */\n icon?: string\n /** Shown in the sidebar. A fallback pillar such as Topics sets false. */\n sidebar?: boolean\n}\n\nexport interface TypeDef {\n id: string\n label: string\n plural?: string\n pillar: string\n /** schema.org class, shown as a hint on the page. */\n schema?: string\n icon?: string\n /** Panels the page opens with, in order. */\n lens?: LensPanel[]\n}\n\nexport interface PropertyDef {\n id: string\n /** Read from the subject: \"Person — role at → Organization\". */\n label: string\n /** Read from the value's side: \"Organization — people ← Person\". */\n inverse?: string\n /** Wikidata property id, kept as a mapping hint. */\n wikidata?: string\n /** Types the value is expected to be. Informational. */\n range?: string[]\n /** Types the subject may be. A lens shows other subjects' statements\n * through the inverse; `wiki enrich` writes it only on these (#820). */\n domain?: string[]\n}\n\nexport type PanelSource = \"statements\" | \"linked\" | \"history\" | \"discussed\" | \"readings\" | \"notes\"\n\nexport interface LensPanel {\n /** Panel id. Used in the zoom URL, so keep it short and stable. */\n panel: string\n title?: string\n /** Where items come from. Inferred from the other fields when omitted. */\n source?: PanelSource\n /** Properties to show (statements panels). `related` covers plain links. */\n from?: string | string[]\n /** Keep only items whose other end has one of these types. */\n types?: string[]\n /** Items shown at the overview level (Z2). The full list is Z3. */\n show?: number\n group_by?: \"role\" | \"property\"\n display?: \"list\" | \"timeline\"\n /** History: importance levels shown unfolded. */\n importance?: Importance[]\n /** History: levels folded under a count. */\n fold?: Importance\n /** History: repeated minor events shown as one recurring line. */\n rollup?: { min: number; days: number }\n /** Readings: only the latest value per metric. */\n latest?: boolean\n /** `owner` marks the panel as private to the owner. */\n access?: \"owner\"\n}\n\nexport interface ClassifyRule {\n /** Type the matching page gets. */\n type: string\n /** Match when the page's legacy `type` is one of these. */\n legacy?: string[]\n /** Match when the page path starts with one of these folders. */\n path?: string[]\n /** Match when the page has any of these tags. */\n tags?: string[]\n /** Case-insensitive regular expression on the title. */\n title?: string\n}\n\n/** Gives an event its importance without a model call (#811). */\nexport interface ImportanceRule {\n level: Importance\n /** Case-insensitive regular expression on the event title. */\n title?: string\n /** Match when the event page has any of these tags. */\n tags?: string[]\n}\n\nexport interface Ontology {\n version: number\n pillars: PillarDef[]\n types: TypeDef[]\n properties: PropertyDef[]\n importance: {\n default: Importance\n /** Who may set `major`: \"owner\" means agents can only propose it. */\n major_set_by: \"owner\" | \"anyone\"\n rollup: { min: number; days: number }\n /** Tried in order by `wiki events` before it asks a model. The first\n * match wins. */\n rules?: ImportanceRule[]\n }\n sidebar: {\n pins_max: number\n /** Page titles the owner pinned, in order. */\n pins: string[]\n }\n /** Rules that give a page a type, tried in order. The first match wins. */\n classify: ClassifyRule[]\n /** Type for pages no rule matches. */\n fallback_type: string\n /** Extra names of the fleet's agents, for agents that run on another\n * node or answer to a persona name (#819). The node's own agent ids,\n * configured names and persona names are found without this. */\n agent_names?: string[]\n}\n\n/** One typed fact about a page: subject (the page) → property → value. */\nexport interface WikiStatement {\n property: string\n /** A page title (becomes a link) or a literal value. */\n value: string\n role?: string\n since?: string\n until?: string\n /** Metric name for readings (disk_used, uptime). */\n metric?: string\n /** When a reading was taken. */\n at?: string\n /** Where it comes from: entry id, document, gazette reference, article. */\n source?: string\n access?: \"public\" | \"shared\" | \"private\"\n status?: \"proposed\" | \"confirmed\"\n confirmed_by?: string\n checked_at?: string\n /** The job that wrote it, e.g. \"wiki-enrich\"; its next run replaces it. */\n by?: string\n note?: string\n}\n"],"mappings":"AAWO,IAAMA,EAA2C,CAAC,QAAS,SAAU,OAAO","names":["IMPORTANCE_LEVELS"]}
|