agentix-cli 0.69.3 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/agent-V223TG6H.js +2 -0
  2. package/dist/{board-dashboard-U6IZQA4W.js → board-dashboard-HR3PQPFW.js} +2 -2
  3. package/dist/{board-dashboard-U6IZQA4W.js.map → board-dashboard-HR3PQPFW.js.map} +1 -1
  4. package/dist/{chunk-NO2HOK4B.js → chunk-23A5K5UW.js} +3 -3
  5. package/dist/chunk-23A5K5UW.js.map +1 -0
  6. package/dist/{chunk-DW5EHX3M.js → chunk-3IY2YWXP.js} +2 -2
  7. package/dist/{chunk-IULWZA3J.js → chunk-3RC4LO2G.js} +6 -6
  8. package/dist/chunk-3RC4LO2G.js.map +1 -0
  9. package/dist/{chunk-SZJMS7K4.js → chunk-5MUJZODV.js} +19 -19
  10. package/dist/chunk-5MUJZODV.js.map +1 -0
  11. package/dist/{chunk-KPPGT5FJ.js → chunk-6QDOUOKD.js} +2 -2
  12. package/dist/{chunk-E7OACKES.js → chunk-BBIWAJRX.js} +2 -2
  13. package/dist/{chunk-Y57CULGE.js → chunk-C245D4BZ.js} +2 -2
  14. package/dist/{chunk-64P4QHSZ.js → chunk-CECHWYJ2.js} +1 -1
  15. package/dist/{chunk-64P4QHSZ.js.map → chunk-CECHWYJ2.js.map} +1 -1
  16. package/dist/chunk-FBDIJEKL.js +152 -0
  17. package/dist/chunk-FBDIJEKL.js.map +1 -0
  18. package/dist/chunk-JHCI6XCJ.js +5 -0
  19. package/dist/chunk-JHCI6XCJ.js.map +1 -0
  20. package/dist/{chunk-USMCN2X3.js → chunk-LHLNARRW.js} +13 -13
  21. package/dist/chunk-ML6CNRBK.js +105 -0
  22. package/dist/chunk-ML6CNRBK.js.map +1 -0
  23. package/dist/{chunk-FGFDPYL4.js → chunk-P2RYUODK.js} +2 -2
  24. package/dist/chunk-P2RYUODK.js.map +1 -0
  25. package/dist/{chunk-SXKOI2IF.js → chunk-PHDS2HIN.js} +118 -118
  26. package/dist/chunk-PHDS2HIN.js.map +1 -0
  27. package/dist/{chunk-RN5NOIBH.js → chunk-SN5N2FPG.js} +2 -2
  28. package/dist/chunk-TLDQWTSW.js +49 -0
  29. package/dist/chunk-TLDQWTSW.js.map +1 -0
  30. package/dist/chunk-TTVVXBCM.js +2 -0
  31. package/dist/chunk-TTVVXBCM.js.map +1 -0
  32. package/dist/{chunk-B7S66EK7.js → chunk-W7SEPJFH.js} +14 -14
  33. package/dist/chunk-W7SEPJFH.js.map +1 -0
  34. package/dist/chunk-WLMQ5JMX.js +6 -0
  35. package/dist/chunk-WLMQ5JMX.js.map +1 -0
  36. package/dist/{chunk-3FWJXI7H.js → chunk-YBF2QVZ7.js} +2 -2
  37. package/dist/{chunk-VVMOTM3V.js → chunk-YK7GFEGO.js} +2 -2
  38. package/dist/cli.js +1 -1
  39. package/dist/cli.js.map +1 -1
  40. package/dist/{compaction-H5U32UU6.js → compaction-MECSN36J.js} +4 -4
  41. package/dist/compaction-MECSN36J.js.map +1 -0
  42. package/dist/{context-planner-LJT5IKH6.js → context-planner-JU7CNXCB.js} +3 -3
  43. package/dist/context-planner-JU7CNXCB.js.map +1 -0
  44. package/dist/graph-FJ53FDWK.js +2 -0
  45. package/dist/heal-CMQL5SG4.js +2 -0
  46. package/dist/index.d.ts +41 -6
  47. package/dist/index.js +2 -2
  48. package/dist/index.js.map +1 -1
  49. package/dist/loader-YFVSSYSL.js +2 -0
  50. package/dist/memory-extract-YCNCARZ2.js +2 -0
  51. package/dist/migrate-v2-ZOIMGITH.js +4 -0
  52. package/dist/{migrate-v2-KOMPDC6U.js.map → migrate-v2-ZOIMGITH.js.map} +1 -1
  53. package/dist/program-UTELWTXC.js +2 -0
  54. package/dist/promote-B5AOKPQR.js +2 -0
  55. package/dist/{providers-NRPX2FHP.js → providers-ES5KVLI4.js} +2 -2
  56. package/dist/query-QLJNQUUP.js +2 -0
  57. package/dist/registry-CTZFLXGB.js +2 -0
  58. package/dist/{request-planner-YIG5RUN2.js → request-planner-NMOAOZIM.js} +2 -2
  59. package/dist/{review-candidates-2JFQ2M53.js → review-candidates-FLY6HZEN.js} +2 -2
  60. package/dist/{routing-3CIQQZJ4.js → routing-SMIZ77CT.js} +2 -2
  61. package/dist/{seat-HMF3G6BR.js → seat-F3S2HG5G.js} +2 -2
  62. package/dist/{select-2P73MN6O.js → select-5GC7CTPQ.js} +2 -2
  63. package/dist/types-NZOBHQGS.js +2 -0
  64. package/dist/wiki-X76JUHXT.js +2 -0
  65. package/dist/wiki-X76JUHXT.js.map +1 -0
  66. package/package.json +1 -1
  67. package/dist/agent-OJQKD5AI.js +0 -2
  68. package/dist/chunk-4DRNEOOW.js +0 -2
  69. package/dist/chunk-4DRNEOOW.js.map +0 -1
  70. package/dist/chunk-B7S66EK7.js.map +0 -1
  71. package/dist/chunk-EQTSOK7L.js +0 -109
  72. package/dist/chunk-EQTSOK7L.js.map +0 -1
  73. package/dist/chunk-FGFDPYL4.js.map +0 -1
  74. package/dist/chunk-IULWZA3J.js.map +0 -1
  75. package/dist/chunk-JQXG2OO6.js +0 -152
  76. package/dist/chunk-JQXG2OO6.js.map +0 -1
  77. package/dist/chunk-JYBSYW7T.js +0 -45
  78. package/dist/chunk-JYBSYW7T.js.map +0 -1
  79. package/dist/chunk-NO2HOK4B.js.map +0 -1
  80. package/dist/chunk-SXKOI2IF.js.map +0 -1
  81. package/dist/chunk-SZJMS7K4.js.map +0 -1
  82. package/dist/chunk-VDMYBPYB.js +0 -5
  83. package/dist/chunk-VDMYBPYB.js.map +0 -1
  84. package/dist/compaction-H5U32UU6.js.map +0 -1
  85. package/dist/context-planner-LJT5IKH6.js.map +0 -1
  86. package/dist/heal-HVYQD3EZ.js +0 -2
  87. package/dist/loader-EVHZ2R73.js +0 -2
  88. package/dist/memory-extract-F76BE6KA.js +0 -2
  89. package/dist/migrate-v2-KOMPDC6U.js +0 -4
  90. package/dist/program-O67GMIWX.js +0 -2
  91. package/dist/promote-7SU6IJDC.js +0 -2
  92. package/dist/query-CY7F5ZFR.js +0 -2
  93. package/dist/registry-K76DGYLW.js +0 -2
  94. package/dist/types-S6NHM5C3.js +0 -2
  95. package/dist/wiki-VXTUHSRH.js +0 -2
  96. /package/dist/{agent-OJQKD5AI.js.map → agent-V223TG6H.js.map} +0 -0
  97. /package/dist/{chunk-DW5EHX3M.js.map → chunk-3IY2YWXP.js.map} +0 -0
  98. /package/dist/{chunk-KPPGT5FJ.js.map → chunk-6QDOUOKD.js.map} +0 -0
  99. /package/dist/{chunk-E7OACKES.js.map → chunk-BBIWAJRX.js.map} +0 -0
  100. /package/dist/{chunk-Y57CULGE.js.map → chunk-C245D4BZ.js.map} +0 -0
  101. /package/dist/{chunk-USMCN2X3.js.map → chunk-LHLNARRW.js.map} +0 -0
  102. /package/dist/{chunk-RN5NOIBH.js.map → chunk-SN5N2FPG.js.map} +0 -0
  103. /package/dist/{chunk-3FWJXI7H.js.map → chunk-YBF2QVZ7.js.map} +0 -0
  104. /package/dist/{chunk-VVMOTM3V.js.map → chunk-YK7GFEGO.js.map} +0 -0
  105. /package/dist/{heal-HVYQD3EZ.js.map → graph-FJ53FDWK.js.map} +0 -0
  106. /package/dist/{loader-EVHZ2R73.js.map → heal-CMQL5SG4.js.map} +0 -0
  107. /package/dist/{memory-extract-F76BE6KA.js.map → loader-YFVSSYSL.js.map} +0 -0
  108. /package/dist/{program-O67GMIWX.js.map → memory-extract-YCNCARZ2.js.map} +0 -0
  109. /package/dist/{promote-7SU6IJDC.js.map → program-UTELWTXC.js.map} +0 -0
  110. /package/dist/{providers-NRPX2FHP.js.map → promote-B5AOKPQR.js.map} +0 -0
  111. /package/dist/{query-CY7F5ZFR.js.map → providers-ES5KVLI4.js.map} +0 -0
  112. /package/dist/{registry-K76DGYLW.js.map → query-QLJNQUUP.js.map} +0 -0
  113. /package/dist/{routing-3CIQQZJ4.js.map → registry-CTZFLXGB.js.map} +0 -0
  114. /package/dist/{request-planner-YIG5RUN2.js.map → request-planner-NMOAOZIM.js.map} +0 -0
  115. /package/dist/{review-candidates-2JFQ2M53.js.map → review-candidates-FLY6HZEN.js.map} +0 -0
  116. /package/dist/{seat-HMF3G6BR.js.map → routing-SMIZ77CT.js.map} +0 -0
  117. /package/dist/{types-S6NHM5C3.js.map → seat-F3S2HG5G.js.map} +0 -0
  118. /package/dist/{select-2P73MN6O.js.map → select-5GC7CTPQ.js.map} +0 -0
  119. /package/dist/{wiki-VXTUHSRH.js.map → types-NZOBHQGS.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{e as o}from"./chunk-EQTSOK7L.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
- //# sourceMappingURL=chunk-RN5NOIBH.js.map
1
+ import{a as o}from"./chunk-ML6CNRBK.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
2
+ //# sourceMappingURL=chunk-SN5N2FPG.js.map
@@ -0,0 +1,49 @@
1
+ import{a as j,b as T,c as O,d as D,e as _}from"./chunk-TFVUOC2C.js";import{b as W}from"./chunk-2GIDVZ4H.js";import{b as v,c as C}from"./chunk-QOYAX2FT.js";import{f as N}from"./chunk-WLMQ5JMX.js";import{v as R,w as I}from"./chunk-BBIWAJRX.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function rt(n,a,o,t={}){let p=t.selectorModel??"haiku",u=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,i=t.maxArticles??8,g=t.timeoutMs??6e4,h=t.log??console.error.bind(console,"[wiki-query]"),e=t.messagePath?.length?t.messagePath:void 0,d=t.graphWeight??S,s=x(a.baseDir,"_index.md");if(!B(s))return k("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let A=Y(s,"utf-8"),$=Date.now(),y=[],m="";try{let c=await G(n,a,o,l,e,d);c?(y=c,m=`[wiki-rerank seat] ${c.map(f=>f.title).join(" | ")}`):(m=await Q(q(n,A,l,e),p,g),y=K(m))}catch(c){return h("selector failed:",c?.message),{...k("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-$,synthesisMs:0,selectorOutput:m}}}let b=Date.now()-$;if(y.length===0)return{...k("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:b,synthesisMs:0,selectorOutput:m}};let w=F(y,a,o,r,i);if(w.length===0)return{...k("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:y,trace:{selectorMs:b,synthesisMs:0,selectorOutput:m}};let M=Date.now(),P="";try{P=await Q(J(n,w),u,g*2)}catch(c){return h("synthesis failed:",c?.message),{...k("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:y,walked:w.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:b,synthesisMs:Date.now()-M,selectorOutput:m}}}let E=Date.now()-M;return{answer:P.trim(),citations:w.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:y,walked:w.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:b,synthesisMs:E,selectorOutput:m}}}function k(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,p){let u=new Map;for(let i of a.listArticles(o||""))u.set(i.meta.title.toLowerCase(),i.path);let l=new Map,r=[];for(let i of n)l.has(i.path)||r.push({path:i.path,hop:0});for(;r.length&&l.size<p;){let i=r.shift();if(l.has(i.path)||i.hop>t)continue;let g=o?a.readArticleAs(i.path,o):a.readArticle(i.path);if(g&&(l.set(i.path,{...g,hop:i.hop}),!(i.hop>=t)))for(let h of g.meta.related||[]){let e=u.get(h.toLowerCase());e&&!l.has(e)&&r.push({path:e,hop:i.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,p,u=S){try{let r=(a.rebuildIndex().articles??[]).filter(s=>s.path&&!s.path.includes("/_versions/"));if(r.length<2)return null;let g=H(n,r,p,u).slice(0,T).map(s=>({id:`k${s}`,title:r[s].title||r[s].path,tags:r[s].tags,excerpt:[r[s].type?`type: ${r[s].type}`:"",(r[s].related??[]).length?`related: ${(r[s].related??[]).join(", ")}`:"",(r[s].graphPath??[]).length?`graph: ${(r[s].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),h=await R(j,O({query:n,candidates:g,excerptChars:300}),D(g),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!h||h.mode!=="active")return null;let d=_(h.answers,g).ranked.slice(0,t).map(s=>r[Number(s.slice(1))]).filter(Boolean).map(s=>({title:s.title,path:s.path}));return d.length>0?d:null}catch{return null}}var S=.6;function H(n,a,o,t=S){let p=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),u=C(n,v(p)),l=u.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(u.map(e=>[e.docIndex,l>0?e.score/l:0])),i=!!o?.length,h=a.map((e,d)=>{let s=r.get(d)??0,A=i&&e.graphPath?.length?N(o,e.graphPath):0;return{i:d,score:i?(1-t)*s+t*A:s,scored:r.has(d)||A>0}}).filter(e=>e.scored).sort((e,d)=>d.score-e.score||e.i-d.i).map(e=>e.i);for(let e=0;e<a.length;e++)h.includes(e)||h.push(e);return h}function q(n,a,o,t){let p=t?.length?`
2
+ ## Intent
3
+
4
+ The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
5
+ `:"";return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
6
+
7
+ ## Question
8
+
9
+ ${n}
10
+ ${p}
11
+ ## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
12
+
13
+ ${a}
14
+
15
+ ## Your task
16
+
17
+ Pick up to ${o} articles from the catalog that are most likely to answer the question. Prefer:
18
+ - Articles whose title directly names a subject in the question.
19
+ - Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
20
+ - Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
21
+
22
+ Return ONLY valid JSON, no markdown fencing, no prose:
23
+
24
+ [
25
+ {"title": "Exact Article Title", "path": "path/from/catalog.md"},
26
+ ...
27
+ ]
28
+
29
+ If none of the articles match, return [].`}function J(n,a){let o=a.map(t=>{let p=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,u=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[p,u,"",t.content].filter(Boolean).join(`
30
+ `)}).join(`
31
+
32
+ ---
33
+
34
+ `);return`You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.
35
+
36
+ ## Question
37
+
38
+ ${n}
39
+
40
+ ## Articles (${a.length} walked from the catalog)
41
+
42
+ ${o}
43
+
44
+ ## Your task
45
+
46
+ Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
47
+
48
+ Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:p,rmSync:u}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);p(r,{recursive:!0});let i=x(r,`prompt-${Date.now()}.txt`);t(i,n);try{let g=`cat '${i}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,h=L(g,{env:W({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let e=JSON.parse(h);return String(e.result||e.content||"")}catch{return h}}finally{try{u(i,{force:!0})}catch{}}}export{rt as a,S as b,H as c};
49
+ //# sourceMappingURL=chunk-TLDQWTSW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { stripAnthropicApiKey } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, store, requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n const index = store.rebuildIndex()\n const pool = (index.articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage: \"catalog-selector\" } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question: text match (BM25 over title, tags\n * and wikilinks, scaled to 0–1) plus, when the request was classified,\n * how much of the intent-graph path each article shares with it. Articles\n * the text match never scored keep their catalog order at the end.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const docs = pool.map((a) =>\n [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \"),\n )\n const bm25 = scoreAll(question, buildIndex(docs))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const combined = pool.map((a, i) => {\n const t = text.get(i) ?? 0\n const g = useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n return { i, score: useGraph ? (1 - graphWeight) * t + graphWeight * g : t, scored: text.has(i) || g > 0 }\n })\n const ranked = combined.filter((c) => c.scored).sort((x, y) => y.score - x.score || x.i - y.i).map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: stripAnthropicApiKey({ ...process.env }), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n"],"mappings":"kPAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAEzCC,IAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,MAAgB,gBAiEzB,eAAsBC,GACpBC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAaF,EAAK,YAAc,SAChCG,EAAgBH,EAAK,eAAiB,EACtCI,EAAUJ,EAAK,SAAW,EAC1BK,EAAcL,EAAK,aAAe,EAClCM,EAAYN,EAAK,WAAa,IAC9BO,EAAMP,EAAK,KAAO,QAAQ,MAAM,KAAK,QAAS,cAAc,EAC5DQ,EAAcR,EAAK,aAAa,OAASA,EAAK,YAAc,OAC5DS,EAAcT,EAAK,aAAeU,EAGlCC,EAAcjB,EAAQI,EAAM,QAAS,WAAW,EACtD,GAAI,CAACc,EAAWD,CAAW,EACzB,OAAOE,EAAY,aAAchB,EAAU,gEAA2D,EAExG,IAAMiB,EAAUC,EAAaJ,EAAa,OAAO,EAG3CK,EAAgB,KAAK,IAAI,EAC3BC,EAAqD,CAAC,EACtDC,EAAiB,GACrB,GAAI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b,CAAG,EAC/B,OAAO,OAAOa,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOb,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","status","_question","error","titleIndex","article","opened","frontier","next","target","path","pool","rankCatalogPool","DEFAULT_SHORTLIST","i","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","docs","bm25","scoreAll","buildIndex","maxBm25","m","r","text","useGraph","ranked","t","g","ancestryScore","x","y","branch","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","stripAnthropicApiKey","envelope"]}
@@ -0,0 +1,2 @@
1
+ import{z as e}from"zod";var i=e.enum(["enum","free","ref"]),a=e.object({name:e.string().regex(/^[a-z][a-z0-9_]*$/i,"axis name must be a simple identifier"),type:i,values:e.array(e.string()).optional(),refLevel:e.string().optional(),optional:e.boolean().optional(),description:e.string().optional()}),r=e.object({id:e.string().regex(/^[a-z][a-z0-9_-]*$/,"level id must be lowercase slug"),axes:e.array(a).min(1),description:e.string().optional()}),f=e.object({version:e.number().int().default(1),levels:e.array(r).min(1).max(5),leafInput:a.optional(),leafOutput:a.optional()}),t=e.string().regex(/^[a-z0-9][a-z0-9._-]*$/,"node id must be lowercase slug (alnum, '.', '_', '-')"),n=e.object({id:t,level:e.string(),parentId:t.nullable(),axes:e.record(e.string(),e.string()),createdAt:e.string(),createdBy:e.string().optional()}),o=e.enum(["llm","user","cache","seat"]),s=e.enum(["pending","approved","rejected"]),p=e.object({ts:e.string(),msgHash:e.string(),agentId:e.string().optional(),channel:e.string().optional(),sender:e.string().optional(),chatId:e.string().optional(),path:e.array(t),proposedAxes:e.record(e.string(),e.record(e.string(),e.string())).default({}),leaf:e.object({input:e.string().optional(),output:e.string().optional()}).partial().default({}),source:o,status:s,confidence:e.number().min(0).max(1).optional(),preview:e.string().optional()}),c=e.object({fingerprint:e.string(),path:e.array(t),leaf:p.shape.leaf,updatedAt:e.string()}),m=e.object({version:e.number().int().default(1),nodes:e.array(n).default([])}),d=e.object({version:e.number().int().default(1),entries:e.record(e.string(),c).default({})});export{i as a,a as b,r as c,f as d,t as e,n as f,o as g,s as h,p as i,c as j,m as k,d as l};
2
+ //# sourceMappingURL=chunk-TTVVXBCM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graph/types.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Intent Knowledge Graph types + Zod schemas ---\n//\n// A hierarchical, enumerable intent taxonomy with fixed axes per level.\n// See plan: /Users/you/.claude/plans/delightful-floating-diffie.md\n//\n// Shape on disk (.agentx/graph/):\n// schema.json — level definitions + required axes per level\n// nodes.json — tree of nodes: { id, level, parentId, axes }\n// classifications.jsonl — append-only log of message → path decisions\n// index.json — fingerprint → pathId snap-to-path cache\n\nexport const axisTypeSchema = z.enum([\"enum\", \"free\", \"ref\"])\nexport type AxisType = z.infer<typeof axisTypeSchema>\n\nexport const axisDefSchema = z.object({\n name: z.string().regex(/^[a-z][a-z0-9_]*$/i, \"axis name must be a simple identifier\"),\n type: axisTypeSchema,\n /** For type=\"enum\": closed set of allowed values. */\n values: z.array(z.string()).optional(),\n /** For type=\"ref\": which level's nodes may be referenced. */\n refLevel: z.string().optional(),\n /** If true, this axis may be absent from a node without failing validation.\n * Use for axes that apply conditionally (e.g. a department's \"lead\" ref\n * doesn't apply to a person-kind unit). Absent/false = required. */\n optional: z.boolean().optional(),\n /** Optional human-readable help, shown as tooltip in the admin UI. */\n description: z.string().optional(),\n})\nexport type AxisDef = z.infer<typeof axisDefSchema>\n\nexport const levelDefSchema = z.object({\n id: z.string().regex(/^[a-z][a-z0-9_-]*$/, \"level id must be lowercase slug\"),\n /** Axes every node at this level MUST carry. Order matters for UI rendering. */\n axes: z.array(axisDefSchema).min(1),\n description: z.string().optional(),\n})\nexport type LevelDef = z.infer<typeof levelDefSchema>\n\nexport const graphSchemaSchema = z.object({\n version: z.number().int().default(1),\n /** Ordered from root to leaf. Max 5 to keep the taxonomy scannable. */\n levels: z.array(levelDefSchema).min(1).max(5),\n /** Axis describing where a leaf classification came from (channel, cron, etc.). */\n leafInput: axisDefSchema.optional(),\n /** Free-form description of the expected result of a leaf classification. */\n leafOutput: axisDefSchema.optional(),\n})\nexport type GraphSchema = z.infer<typeof graphSchemaSchema>\n\n// Allow dots so verb-level node ids like \"review.merge-request\" or\n// \"deploy.staging\" parse cleanly (Phase 1 of the classifier-retire plan).\n// Dots are dot-namespaced verbs only — never the leading char.\nexport const nodeIdSchema = z.string().regex(/^[a-z0-9][a-z0-9._-]*$/, \"node id must be lowercase slug (alnum, '.', '_', '-')\")\n\nexport const graphNodeSchema = z.object({\n id: nodeIdSchema,\n /** Matches a `levels[*].id` from the schema. */\n level: z.string(),\n /** null for root-level nodes (level[0]); otherwise the id of a node at level-1. */\n parentId: nodeIdSchema.nullable(),\n /** Values for every axis declared at this level's schema entry. `ref` axes\n * hold the id of another node; `enum` axes hold one of the declared values;\n * `free` axes hold any string. */\n axes: z.record(z.string(), z.string()),\n createdAt: z.string(),\n createdBy: z.string().optional(),\n})\nexport type GraphNode = z.infer<typeof graphNodeSchema>\n\n/** \"seat\": the intent-path decision seat picked an existing path. */\nexport const classificationSourceSchema = z.enum([\"llm\", \"user\", \"cache\", \"seat\"])\nexport type ClassificationSource = z.infer<typeof classificationSourceSchema>\n\nexport const classificationStatusSchema = z.enum([\"pending\", \"approved\", \"rejected\"])\nexport type ClassificationStatus = z.infer<typeof classificationStatusSchema>\n\nexport const classificationSchema = z.object({\n ts: z.string(),\n msgHash: z.string(),\n agentId: z.string().optional(),\n channel: z.string().optional(),\n sender: z.string().optional(),\n /** The conversation the message belongs to. Lets a tool running inside\n * that conversation find the path its request was filed under. */\n chatId: z.string().optional(),\n /** Node ids from root to leaf, one per level. Shorter-than-full paths are\n * allowed if the classifier was only confident down to a certain depth. */\n path: z.array(nodeIdSchema),\n /** Axis values asserted by the classifier for new nodes it proposed along\n * the path. Keyed by node id. */\n proposedAxes: z.record(z.string(), z.record(z.string(), z.string())).default({}),\n /** Leaf-level extras. */\n leaf: z.object({\n input: z.string().optional(),\n output: z.string().optional(),\n }).partial().default({}),\n source: classificationSourceSchema,\n status: classificationStatusSchema,\n confidence: z.number().min(0).max(1).optional(),\n /** Redacted first ~200 chars of the message, for the approval UI. */\n preview: z.string().optional(),\n})\nexport type Classification = z.infer<typeof classificationSchema>\n\n/** Row in the fingerprint → path snap cache. */\nexport const fingerprintEntrySchema = z.object({\n fingerprint: z.string(),\n path: z.array(nodeIdSchema),\n leaf: classificationSchema.shape.leaf,\n updatedAt: z.string(),\n})\nexport type FingerprintEntry = z.infer<typeof fingerprintEntrySchema>\n\n/** Nodes file is a plain list, not a nested tree — lookups are by id. */\nexport const nodesFileSchema = z.object({\n version: z.number().int().default(1),\n nodes: z.array(graphNodeSchema).default([]),\n})\nexport type NodesFile = z.infer<typeof nodesFileSchema>\n\n/** Index file — record of fingerprints. Hot path; kept as a map on disk. */\nexport const indexFileSchema = z.object({\n version: z.number().int().default(1),\n entries: z.record(z.string(), fingerprintEntrySchema).default({}),\n})\nexport type IndexFile = z.infer<typeof indexFileSchema>\n"],"mappings":"AAAA,OAAS,KAAAA,MAAS,MAaX,IAAMC,EAAiBD,EAAE,KAAK,CAAC,OAAQ,OAAQ,KAAK,CAAC,EAG/CE,EAAgBF,EAAE,OAAO,CACp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OAAO,EAAE,SAAS,EAG5B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAG5B,KAAMA,EAAE,MAAMK,CAAY,EAG1B,aAAcL,EAAE,OAAOA,EAAE,OAAO,EAAGA,EAAE,OAAOA,EAAE,OAAO,EAAGA,EAAE,OAAO,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,EAE/E,KAAMA,EAAE,OAAO,CACb,MAAOA,EAAE,OAAO,EAAE,SAAS,EAC3B,OAAQA,EAAE,OAAO,EAAE,SAAS,CAC9B,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,EACvB,OAAQO,EACR,OAAQC,EACR,WAAYR,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS,EAE9C,QAASA,EAAE,OAAO,EAAE,SAAS,CAC/B,CAAC,EAIYU,EAAyBV,EAAE,OAAO,CAC7C,YAAaA,EAAE,OAAO,EACtB,KAAMA,EAAE,MAAMK,CAAY,EAC1B,KAAMI,EAAqB,MAAM,KACjC,UAAWT,EAAE,OAAO,CACtB,CAAC,EAIYW,EAAkBX,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,MAAOA,EAAE,MAAMM,CAAe,EAAE,QAAQ,CAAC,CAAC,CAC5C,CAAC,EAIYM,EAAkBZ,EAAE,OAAO,CACtC,QAASA,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EACnC,QAASA,EAAE,OAAOA,EAAE,OAAO,EAAGU,CAAsB,EAAE,QAAQ,CAAC,CAAC,CAClE,CAAC","names":["z","axisTypeSchema","axisDefSchema","levelDefSchema","graphSchemaSchema","nodeIdSchema","graphNodeSchema","classificationSourceSchema","classificationStatusSchema","classificationSchema","fingerprintEntrySchema","nodesFileSchema","indexFileSchema"]}