agentix-cli 0.127.0 → 0.128.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-FF66N2KH.js → App-BOLQUKCN.js} +2 -2
- package/dist/{ChatApp-HMHQZVVD.js → ChatApp-72HXQV24.js} +2 -2
- package/dist/absorb-eval-O3HA6XA5.js +2 -0
- package/dist/{agent-UAWDO3I2.js → agent-S2DXXALS.js} +2 -2
- package/dist/{board-dashboard-Y2OECKDG.js → board-dashboard-ZKXXK5CG.js} +4 -4
- package/dist/{chunk-COWAAE54.js → chunk-2SV4RKRW.js} +2 -2
- package/dist/{chunk-YV22EOGL.js → chunk-4V7SWL2S.js} +2 -2
- package/dist/chunk-5DAEJF5S.js +36 -0
- package/dist/chunk-5DAEJF5S.js.map +1 -0
- package/dist/{chunk-VBJTGTF5.js → chunk-6GGGXCOY.js} +2 -2
- package/dist/{chunk-4WZGZ2Z6.js → chunk-6KIUVVKX.js} +2 -2
- package/dist/{chunk-NUSROFTJ.js → chunk-C5MTLW7O.js} +2 -2
- package/dist/{chunk-73WQ42PO.js → chunk-D2WX3BET.js} +2 -2
- package/dist/chunk-DN3RLR5Z.js +17 -0
- package/dist/chunk-DN3RLR5Z.js.map +1 -0
- package/dist/{chunk-EJT3F6QM.js → chunk-DQ2LNQ2D.js} +2 -2
- package/dist/{chunk-HYRBBH6T.js → chunk-EJT4MA3J.js} +9 -9
- package/dist/chunk-EJT4MA3J.js.map +1 -0
- package/dist/chunk-FSW4FUMW.js +55 -0
- package/dist/chunk-FSW4FUMW.js.map +1 -0
- package/dist/chunk-FXBMFGOV.js +6 -0
- package/dist/chunk-FXBMFGOV.js.map +1 -0
- package/dist/{chunk-PH43FUU7.js → chunk-HKW56YZK.js} +2 -2
- package/dist/{chunk-LTH3AYXC.js → chunk-LDS4SZBU.js} +2 -2
- package/dist/chunk-MRYA4J5F.js +54 -0
- package/dist/chunk-MRYA4J5F.js.map +1 -0
- package/dist/{chunk-HNBW5Q47.js → chunk-O2BS6N3T.js} +2 -2
- package/dist/{chunk-EHLTZ6IB.js → chunk-P4XGM7ZM.js} +2 -2
- package/dist/{chunk-QWQOI4G4.js → chunk-QACEFESP.js} +6 -6
- package/dist/{chunk-CKYPQMUD.js → chunk-QFZU5CEO.js} +2 -2
- package/dist/{chunk-XX5QKBX4.js → chunk-QQFURUMS.js} +2 -2
- package/dist/{chunk-I4DGMFQG.js → chunk-TG6CT54D.js} +2 -2
- package/dist/{chunk-O6FP3LPC.js → chunk-TPNTFCSQ.js} +2 -2
- package/dist/{chunk-56KNKUFF.js → chunk-VD7IO653.js} +3 -3
- package/dist/{chunk-56KNKUFF.js.map → chunk-VD7IO653.js.map} +1 -1
- package/dist/{chunk-3KYZOC7N.js → chunk-YWKLUQDC.js} +2 -2
- package/dist/chunk-Z3W7D5RR.js +4 -0
- package/dist/chunk-Z3W7D5RR.js.map +1 -0
- package/dist/{chunk-XYT6XY7G.js → chunk-ZLC4TSXF.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-2VVRJ3UF.js → client-VBV7Q43P.js} +2 -2
- package/dist/config-52C3DJD2.js +2 -0
- package/dist/{config-mutate-47WZDZBO.js → config-mutate-DKQESY6F.js} +2 -2
- package/dist/config-mutator-BF4D4QGN.js +2 -0
- package/dist/contributions-5OEZWYXI.js +57 -0
- package/dist/contributions-5OEZWYXI.js.map +1 -0
- package/dist/{doctor-Q3QNZVLC.js → doctor-VLRC4HW2.js} +2 -2
- package/dist/{follow-up-tool-GKZVG4L2.js → follow-up-tool-235LDEMP.js} +2 -2
- package/dist/{hub-DNPINTIF.js → hub-5QK7KYTZ.js} +2 -2
- package/dist/index.d.ts +224 -0
- package/dist/index.js +1 -1
- package/dist/{program-4QWUOJE3.js → program-MVD57PKP.js} +226 -222
- package/dist/program-MVD57PKP.js.map +1 -0
- package/dist/{promote-PETKX7KR.js → promote-UPPQ4BQE.js} +2 -2
- package/dist/query-XQS5JN6E.js +2 -0
- package/dist/{registry-2XDO53AJ.js → registry-MOMTLJ6R.js} +2 -2
- package/dist/{request-planner-A3WJNPXO.js → request-planner-QGZJEAKY.js} +2 -2
- package/dist/{review-candidates-A6ID2RDX.js → review-candidates-PAKF2JQF.js} +2 -2
- package/dist/{rotation-memo-6UW6DTBQ.js → rotation-memo-7VLREGS6.js} +2 -2
- package/dist/{routing-NPP3MEUW.js → routing-JG3EV4O4.js} +2 -2
- package/dist/schedule-tool-O7ZZ2A7X.js +2 -0
- package/dist/{scheduler-T6VLBM3U.js → scheduler-LMPBAA34.js} +2 -2
- package/dist/score-KDNIUTNV.js +3 -0
- package/dist/score-KDNIUTNV.js.map +1 -0
- package/dist/{seat-D3DBYTSC.js → seat-JN3IVZ3G.js} +2 -2
- package/dist/{select-RFY64RY7.js → select-ZMMRFMNO.js} +2 -2
- package/dist/{set-enabled-AU66DR5C.js → set-enabled-7Y3TW6Z4.js} +2 -2
- package/dist/{tool-F3YA2ZZQ.js → tool-OCYXCDOK.js} +2 -2
- package/dist/{tool-PCHIVR27.js → tool-S7QI6HRA.js} +2 -2
- package/dist/wiki-OCLFFZG6.js +2 -0
- package/package.json +1 -1
- package/dist/absorb-eval-ERKVVTGG.js +0 -2
- package/dist/chunk-HYRBBH6T.js.map +0 -1
- package/dist/chunk-PLIT25TH.js +0 -51
- package/dist/chunk-PLIT25TH.js.map +0 -1
- package/dist/chunk-TJ4P4WW2.js +0 -4
- package/dist/chunk-TJ4P4WW2.js.map +0 -1
- package/dist/chunk-UJXS4MS3.js +0 -49
- package/dist/chunk-UJXS4MS3.js.map +0 -1
- package/dist/chunk-Y27RUOD2.js +0 -54
- package/dist/chunk-Y27RUOD2.js.map +0 -1
- package/dist/config-YSKHOV44.js +0 -2
- package/dist/config-mutator-7DIEQUB5.js +0 -2
- package/dist/program-4QWUOJE3.js.map +0 -1
- package/dist/query-D44BUTH3.js +0 -2
- package/dist/schedule-tool-ZECUQMQK.js +0 -2
- package/dist/wiki-NI3ZPUZS.js +0 -2
- /package/dist/{App-FF66N2KH.js.map → App-BOLQUKCN.js.map} +0 -0
- /package/dist/{ChatApp-HMHQZVVD.js.map → ChatApp-72HXQV24.js.map} +0 -0
- /package/dist/{absorb-eval-ERKVVTGG.js.map → absorb-eval-O3HA6XA5.js.map} +0 -0
- /package/dist/{agent-UAWDO3I2.js.map → agent-S2DXXALS.js.map} +0 -0
- /package/dist/{board-dashboard-Y2OECKDG.js.map → board-dashboard-ZKXXK5CG.js.map} +0 -0
- /package/dist/{chunk-COWAAE54.js.map → chunk-2SV4RKRW.js.map} +0 -0
- /package/dist/{chunk-YV22EOGL.js.map → chunk-4V7SWL2S.js.map} +0 -0
- /package/dist/{chunk-VBJTGTF5.js.map → chunk-6GGGXCOY.js.map} +0 -0
- /package/dist/{chunk-4WZGZ2Z6.js.map → chunk-6KIUVVKX.js.map} +0 -0
- /package/dist/{chunk-NUSROFTJ.js.map → chunk-C5MTLW7O.js.map} +0 -0
- /package/dist/{chunk-73WQ42PO.js.map → chunk-D2WX3BET.js.map} +0 -0
- /package/dist/{chunk-EJT3F6QM.js.map → chunk-DQ2LNQ2D.js.map} +0 -0
- /package/dist/{chunk-PH43FUU7.js.map → chunk-HKW56YZK.js.map} +0 -0
- /package/dist/{chunk-LTH3AYXC.js.map → chunk-LDS4SZBU.js.map} +0 -0
- /package/dist/{chunk-HNBW5Q47.js.map → chunk-O2BS6N3T.js.map} +0 -0
- /package/dist/{chunk-EHLTZ6IB.js.map → chunk-P4XGM7ZM.js.map} +0 -0
- /package/dist/{chunk-QWQOI4G4.js.map → chunk-QACEFESP.js.map} +0 -0
- /package/dist/{chunk-CKYPQMUD.js.map → chunk-QFZU5CEO.js.map} +0 -0
- /package/dist/{chunk-XX5QKBX4.js.map → chunk-QQFURUMS.js.map} +0 -0
- /package/dist/{chunk-I4DGMFQG.js.map → chunk-TG6CT54D.js.map} +0 -0
- /package/dist/{chunk-O6FP3LPC.js.map → chunk-TPNTFCSQ.js.map} +0 -0
- /package/dist/{chunk-3KYZOC7N.js.map → chunk-YWKLUQDC.js.map} +0 -0
- /package/dist/{chunk-XYT6XY7G.js.map → chunk-ZLC4TSXF.js.map} +0 -0
- /package/dist/{client-2VVRJ3UF.js.map → client-VBV7Q43P.js.map} +0 -0
- /package/dist/{config-YSKHOV44.js.map → config-52C3DJD2.js.map} +0 -0
- /package/dist/{config-mutate-47WZDZBO.js.map → config-mutate-DKQESY6F.js.map} +0 -0
- /package/dist/{config-mutator-7DIEQUB5.js.map → config-mutator-BF4D4QGN.js.map} +0 -0
- /package/dist/{doctor-Q3QNZVLC.js.map → doctor-VLRC4HW2.js.map} +0 -0
- /package/dist/{follow-up-tool-GKZVG4L2.js.map → follow-up-tool-235LDEMP.js.map} +0 -0
- /package/dist/{hub-DNPINTIF.js.map → hub-5QK7KYTZ.js.map} +0 -0
- /package/dist/{promote-PETKX7KR.js.map → promote-UPPQ4BQE.js.map} +0 -0
- /package/dist/{query-D44BUTH3.js.map → query-XQS5JN6E.js.map} +0 -0
- /package/dist/{registry-2XDO53AJ.js.map → registry-MOMTLJ6R.js.map} +0 -0
- /package/dist/{request-planner-A3WJNPXO.js.map → request-planner-QGZJEAKY.js.map} +0 -0
- /package/dist/{review-candidates-A6ID2RDX.js.map → review-candidates-PAKF2JQF.js.map} +0 -0
- /package/dist/{rotation-memo-6UW6DTBQ.js.map → rotation-memo-7VLREGS6.js.map} +0 -0
- /package/dist/{routing-NPP3MEUW.js.map → routing-JG3EV4O4.js.map} +0 -0
- /package/dist/{schedule-tool-ZECUQMQK.js.map → schedule-tool-O7ZZ2A7X.js.map} +0 -0
- /package/dist/{scheduler-T6VLBM3U.js.map → scheduler-LMPBAA34.js.map} +0 -0
- /package/dist/{seat-D3DBYTSC.js.map → seat-JN3IVZ3G.js.map} +0 -0
- /package/dist/{select-RFY64RY7.js.map → select-ZMMRFMNO.js.map} +0 -0
- /package/dist/{set-enabled-AU66DR5C.js.map → set-enabled-7Y3TW6Z4.js.map} +0 -0
- /package/dist/{tool-F3YA2ZZQ.js.map → tool-OCYXCDOK.js.map} +0 -0
- /package/dist/{tool-PCHIVR27.js.map → tool-S7QI6HRA.js.map} +0 -0
- /package/dist/{wiki-NI3ZPUZS.js.map → wiki-OCLFFZG6.js.map} +0 -0
package/dist/chunk-PLIT25TH.js
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import{b as j}from"./chunk-UJXS4MS3.js";async function q(t,r,i,s,o={}){let e=o.retrieve??j,u=o.perEntry??2,l=o.maxArticles??8,p=o.queryChars??1500,m=new Map;for(let d of t){let n=[];try{n=await e(d.content.slice(0,p),r,i,{pool:s,maxCandidates:u,maxHops:1,maxArticles:u*2,stage:"absorb-covering"})}catch{}for(let a of n){let g=m.get(a.path);g?(g.hop=Math.min(g.hop,a.hop),g.entries.includes(d.id)||g.entries.push(d.id)):m.set(a.path,{...a,entries:[d.id]})}}return[...m.values()].sort((d,n)=>d.hop-n.hop||n.entries.length-d.entries.length||d.path.localeCompare(n.path)).slice(0,l)}function B(t){if(t.length===0)return"";let r=t.map(i=>{let s=`### ${i.meta.title} \u2014 ${i.meta.type||"untyped"} (${i.path})`,o=`Found for entries: ${i.entries.join(", ")}${i.hop>0?" (linked from a match)":""}`,e=i.meta.related?.length?`Related: ${i.meta.related.join(", ")}`:"";return[s,o,e,"",i.content].filter(u=>u!=="").join(`
|
|
2
|
-
`)}).join(`
|
|
3
|
-
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
`);return`
|
|
7
|
-
## Articles already covering these entries
|
|
8
|
-
|
|
9
|
-
These ${t.length} articles were found by searching the wiki for each entry below. Read them before you write.
|
|
10
|
-
|
|
11
|
-
- When an entry is about the subject of one of these articles, UPDATE that article: write it at the SAME path with the SAME title, carrying its full content merged with what the entry adds.
|
|
12
|
-
- Keep every fact the article already has: commit hashes, URLs, numbers, dates and [[wikilinks]]. Restructure freely, but do not drop one unless an entry explicitly says it is wrong. A save that drops one is refused and the entries stay queued.
|
|
13
|
-
- Do not create a second article (a new path or a near-identical title) for a subject one of these already covers.
|
|
14
|
-
|
|
15
|
-
${r}
|
|
16
|
-
`}var M=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,R=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,x=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,P=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,U=/^\s*\d+[.)]\s/gm;function f(t){let r=[...t.matchAll(M)].map(l=>l[0].replace(/[.,;:!?'"]+$/,"")),i=[...t.matchAll(R)].map(l=>l[1].trim()),s=t.replace(M," ").replace(R," ").replace(U," "),o=[...s.matchAll(x)].map(l=>l[0].toLowerCase()),u=[...s.replace(x," ").matchAll(P)].map(l=>D(l[0]));return{commits:$(o),urls:$(r),wikilinks:$(i),numbers:$(u)}}function V(t,r){let i=f(t),s=f(r),o=r.toLowerCase(),e=[];for(let d of i.commits)!o.includes(d)&&!s.commits.some(n=>n.startsWith(d)||d.startsWith(n))&&e.push(`commit ${d}`);let u=d=>d.toLowerCase().replace(/\/+$/,""),l=new Set(s.urls.map(u));for(let d of i.urls)l.has(u(d))||e.push(`link ${d}`);let p=new Set(s.wikilinks.map(d=>d.toLowerCase()));for(let d of i.wikilinks)p.has(d.toLowerCase())||e.push(`link [[${d}]]`);let m=new Set(s.numbers);for(let d of i.numbers)m.has(d)||e.push(`number ${d}`);return e}function D(t){return/^\d{1,3}(,\d{3})+$/.test(t)?t.replace(/,/g,""):t}function $(t){return[...new Set(t)]}function Y(t,r){if(r.some(s=>s.path===t.path))return t.path;let i=E(t.title);return i?r.find(s=>E(s.title)===i)?.path??t.path:t.path}function E(t){return(t||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}function I(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let i=r>>>0;return()=>{i=i+1831565813>>>0;let s=i;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function Q(t,r,i){let s=I(i),o=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=o.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[o[e],o[u]]=[o[u],o[e]]}return o.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var F=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function S(t){let r=new Set;for(let i of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))F.has(i[0])||r.add(i[0]);return r}function J(t,r){let i=S(t);if(i.size===0)return 1;let s=S(r),o=0;for(let e of i)s.has(e)&&o++;return o/i.size}var _=.15;function k(t){let r=f(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function v(t,r,i){return t.includes(r)||i.some(s=>s.startsWith(r)||r.startsWith(s))}var w=t=>t.toLowerCase().replace(/\/+$/,"");function X(t,r,i){let s=t.sources.map(c=>r.get(c)).filter(c=>!!c),o=t.sources.filter(c=>!r.has(c)),e=s.filter(c=>S(c.content).size>=5&&J(c.content,t.content)<_).map(c=>c.id),u=[...s.map(c=>`${c.date??""}
|
|
17
|
-
${c.content}`),t.previous??""].join(`
|
|
18
|
-
`),l=u.toLowerCase(),p=k(u),m=new Set(p.urls.map(w)),d=new Set(p.numbers),n=k(t.content),a=[];for(let c of n.commits)v(l,c,p.commits)||a.push(`commit ${c}`);for(let c of n.urls)!m.has(w(c))&&!l.includes(w(c))&&a.push(`link ${c}`);for(let c of n.numbers)/^\d{1,2}$/.test(c)||!d.has(c)&&!l.includes(c)&&a.push(`number ${c}`);let g=[];for(let c of s){let h=k(c.content);if(h.commits.length===0&&h.urls.length===0)continue;let C=i(c.id),A=(C.length>0?C:[t.content]).join(`
|
|
19
|
-
`).toLowerCase(),N=k(A);for(let y of h.commits)v(A,y,N.commits)||g.push({entry:c.id,fact:`commit ${y}`});for(let y of h.urls)A.includes(w(y))||g.push({entry:c.id,fact:`link ${y}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:o,weakSources:e,ungrounded:a,lost:g}}function Z(t,r){let i=r.toLowerCase(),s=f(r).commits,o=[];for(let e of t){let u=f(e.content),l=[...u.commits.filter(p=>!v(i,p,s)).map(p=>`commit ${p}`),...u.urls.filter(p=>!i.includes(w(p))).map(p=>`link ${p}`)];l.length>0&&o.push({entry:e.id,facts:l})}return o}var z=new Set("the and for with from into of on in at to by an a".split(" "));function K(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!z.has(r)&&!F.has(r)))}function W(t,r){if(t.size===0||r.size===0)return 0;let i=0;for(let s of t)r.has(s)&&i++;return i/(t.size+r.size-i)}function tt(t,r,i={}){let s=i.titleMin??.75,o=i.sourcesMin??.5,e=t.map(l=>({...l,tt:K(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let p=l+1;p<e.length;p++){let m=e[l],d=e[p];if(r&&!r.has(m.path)&&!r.has(d.path))continue;let n=(m.type??"")===(d.type??"")?W(m.tt,d.tt):0;if(n>=s){u.push({a:m.path,b:d.path,reason:"title",score:n});continue}if(m.ss.size>=2&&d.ss.size>=2){let a=W(m.ss,d.ss);a>=o&&u.push({a:m.path,b:d.path,reason:"sources",score:a})}}return u.sort((l,p)=>p.score-l.score||l.a.localeCompare(p.a))}var L=4e3;function et(t,r){let i=r.map(o=>{let e=o.content.length>L?`${o.content.slice(0,L)}
|
|
20
|
-
[\u2026cut]`:o.content;return`--- ENTRY ${o.id} [${o.date??""}] ---
|
|
21
|
-
${e}
|
|
22
|
-
--- END ENTRY ---`}).join(`
|
|
23
|
-
|
|
24
|
-
`),s=t.previous?`
|
|
25
|
-
## Earlier version of the article (facts here count as supported)
|
|
26
|
-
|
|
27
|
-
${t.previous}
|
|
28
|
-
`:"";return`You are auditing one wiki article against the raw entries it cites. Do not use outside knowledge.
|
|
29
|
-
|
|
30
|
-
## Article: ${t.title} (${t.type??"untyped"}, ${t.path})
|
|
31
|
-
|
|
32
|
-
${t.content}
|
|
33
|
-
${s}
|
|
34
|
-
## Cited entries (${r.length})
|
|
35
|
-
|
|
36
|
-
${i||"(none)"}
|
|
37
|
-
|
|
38
|
-
## What to report
|
|
39
|
-
|
|
40
|
-
1. Split the article into factual claims (one per sentence or bullet; skip headings and "unknown" placeholders). Count them.
|
|
41
|
-
2. A claim is supported when a cited entry or the earlier version states it or plainly implies it. List each claim that is not supported, quoted briefly.
|
|
42
|
-
3. List each claim an entry contradicts.
|
|
43
|
-
4. List the cited entry ids that are about a different subject than the article (they were merged in by mistake).
|
|
44
|
-
5. List facts from the entries that belong in this article and are missing (names, numbers, identifiers, decisions). Ignore small talk.
|
|
45
|
-
6. Verdict: "good" (nothing wrong), "minor" (wording or a small omission), "major" (an unsupported or contradicted fact, a wrong merge, or a lost identifier).
|
|
46
|
-
|
|
47
|
-
Reply with JSON only, no fencing:
|
|
48
|
-
{"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function nt(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,i=l=>Array.isArray(l)?l.map(p=>String(p)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,o=s(r.claims);if(Number.isNaN(o))return null;let e=Math.min(o,Number.isNaN(s(r.supported))?o-i(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:o,supported:Math.max(0,e),unsupported:i(r.unsupported),contradicted:i(r.contradicted),offSubject:i(r.off_subject??r.offSubject),missing:i(r.missing),verdict:u}:null}function rt(t,r,i,s=[],o=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,p=new Set;for(let n of t)for(let a of n.lost)l.add(a.entry),p.add(`${a.entry}|${a.fact}`);let m=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(a=>a.path===n))),d={sample:{articles:t.length,seed:i.seed,since:i.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,a)=>n+a.missingSources.length,0),weakSources:t.reduce((n,a)=>n+a.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,a)=>n+a.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:p.size},duplicates:{pairs:r.length,articlesInPair:m.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,o).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(a=>({path:n.path,...a}))).slice(0,o),weak:t.filter(n=>n.weakSources.length>0).slice(0,o).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,o),uncited:(e?.lost??[]).slice(0,o).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,o).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(c=>c.verdict),a=n.reduce((c,h)=>c+h.claims,0),g=n.reduce((c,h)=>c+h.supported,0);d.judge={judged:n.length,claims:a,supported:g,supportRate:a>0?g/a:1,unsupported:n.reduce((c,h)=>c+h.unsupported.length,0),contradicted:n.reduce((c,h)=>c+h.contradicted.length,0),articlesWithWrongMerge:n.filter(c=>c.offSubject.length>0).length,missingFacts:n.reduce((c,h)=>c+h.missing.length,0),verdicts:{good:n.filter(c=>c.verdict==="good").length,minor:n.filter(c=>c.verdict==="minor").length,major:n.filter(c=>c.verdict==="major").length}}}return d}var b=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function st(t){let r=t.sample.articles,i=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${b(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(_*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${b(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${b(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${b(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&i.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;i.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${b(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${b(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,o=(e,u)=>{u.length!==0&&i.push("",`## ${e}`,"",...u)};return o("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),o("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),o("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),o("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),o("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),o("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),i.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),i.join(`
|
|
49
|
-
`)+`
|
|
50
|
-
`}function it(t){if(!t||typeof t!="object")return{};let r=t,i=r.usage??{},s=o=>typeof o=="number"&&Number.isFinite(o)?o:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(i.input_tokens),outputTokens:s(i.output_tokens),cacheReadTokens:s(i.cache_read_input_tokens),cacheWriteTokens:s(i.cache_creation_input_tokens)}}function T(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function ot(t){let r=new Map,i=o=>{let e=o||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let o of t)o.kind==="call"?i(o.label).calls.push(o):o.kind==="run"&&i(o.label).runs.push(o);let s=[];for(let[o,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,a)=>n-a),p;if(u.length>0)p=u.reduce((n,a)=>n+(Date.parse(a.endedAt)-Date.parse(a.startedAt)),0);else{let n=e.map(g=>Date.parse(g.at)-g.wallMs),a=e.map(g=>Date.parse(g.at));p=Math.max(...a)-Math.min(...n)}let m=e.reduce((n,a)=>n+a.entries,0),d=e.reduce((n,a)=>n+(a.costUsd??0),0);s.push({label:o,calls:e.length,failed:e.filter(n=>n.failed).length,entries:m,articles:e.reduce((n,a)=>n+a.articles,0),refused:e.reduce((n,a)=>n+a.refused,0),heldCited:e.reduce((n,a)=>n+(a.heldCited??0),0),wallMs:p,callMsP50:T(l,.5),callMsP95:T(l,.95),prepMs:e.reduce((n,a)=>n+(a.prepMs??0),0),costUsd:d,costPerEntry:m>0?d/m:0,entriesPerMinute:p>0?m/p*6e4:0,promptChars:e.reduce((n,a)=>n+a.promptChars,0)})}return s.sort((o,e)=>o.label.localeCompare(e.label))}export{q as a,B as b,V as c,Y as d,I as e,Q as f,S as g,J as h,_ as i,X as j,Z as k,tt as l,L as m,et as n,nt as o,rt as p,st as q,it as r,ot as s};
|
|
51
|
-
//# sourceMappingURL=chunk-PLIT25TH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/absorb-context.ts","../src/wiki/absorb-eval.ts"],"sourcesContent":["// What `agentx wiki absorb` knows about the wiki before it writes (#801).\n//\n// Absorb used to show the model the catalog — titles and paths — and\n// nothing else. In the 2026-10-07 A/B one model rewrote an existing event\n// article it had never read and lost the commit, the test count and the\n// review URL; the other wrote a second event article beside the first.\n// Both are what a writer does when it cannot see the page it is editing.\n//\n// So before the compile call, each entry is run through the wiki query\n// retrieval (BM25 shortlist, rerank seat, wikilink walk) and the articles\n// it lands on go into the prompt in full. After the call, a save that\n// would drop a commit, link or number from the article it replaces is\n// refused, and a new article whose title an existing one already has is\n// written over that one instead of beside it.\n\nimport { retrieveArticles, type CatalogEntry } from \"./query\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\nexport type CoveringArticle = WikiArticle & { hop: number; entries: string[] }\n\nexport interface FindCoveringOptions {\n /** Articles picked per entry before the walk. Default 2. */\n perEntry?: number\n /** Cap on articles across the batch. Default 8. */\n maxArticles?: number\n /** Query text taken from each entry. Default 1500 chars. */\n queryChars?: number\n /** Swappable for tests. */\n retrieve?: typeof retrieveArticles\n}\n\n/**\n * The existing articles a batch of entries is about. Each entry is its own\n * query, so one batch mixing three subjects finds all three. Articles\n * picked directly (hop 0) and by more entries come first.\n */\nexport async function findCoveringArticles(\n entries: Array<{ id: string; content: string }>,\n store: WikiStore,\n agentId: string,\n pool: CatalogEntry[],\n opts: FindCoveringOptions = {},\n): Promise<CoveringArticle[]> {\n const retrieve = opts.retrieve ?? retrieveArticles\n const perEntry = opts.perEntry ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const queryChars = opts.queryChars ?? 1500\n const found = new Map<string, CoveringArticle>()\n\n for (const entry of entries) {\n let hits: Array<WikiArticle & { hop: number }> = []\n try {\n hits = await retrieve(entry.content.slice(0, queryChars), store, agentId, {\n pool,\n maxCandidates: perEntry,\n maxHops: 1,\n maxArticles: perEntry * 2,\n stage: \"absorb-covering\",\n })\n } catch {\n // Retrieval is an aid; an absorb without it is the old absorb.\n }\n for (const hit of hits) {\n const seen = found.get(hit.path)\n if (seen) {\n seen.hop = Math.min(seen.hop, hit.hop)\n if (!seen.entries.includes(entry.id)) seen.entries.push(entry.id)\n } else {\n found.set(hit.path, { ...hit, entries: [entry.id] })\n }\n }\n }\n\n return [...found.values()]\n .sort((a, b) => a.hop - b.hop || b.entries.length - a.entries.length || a.path.localeCompare(b.path))\n .slice(0, maxArticles)\n}\n\n/** The prompt section carrying the covering articles, in full. Articles are\n * never cut short: the drop-guard checks the whole old article, so the\n * model must have seen all of it. */\nexport function renderCoveringBlock(articles: CoveringArticle[]): string {\n if (articles.length === 0) return \"\"\n const body = articles\n .map((a) => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path})`\n const why = `Found for entries: ${a.entries.join(\", \")}${a.hop > 0 ? \" (linked from a match)\" : \"\"}`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, why, related, \"\", a.content].filter((l) => l !== \"\").join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n return `\n## Articles already covering these entries\n\nThese ${articles.length} articles were found by searching the wiki for each entry below. Read them before you write.\n\n- When an entry is about the subject of one of these articles, UPDATE that article: write it at the SAME path with the SAME title, carrying its full content merged with what the entry adds.\n- Keep every fact the article already has: commit hashes, URLs, numbers, dates and [[wikilinks]]. Restructure freely, but do not drop one unless an entry explicitly says it is wrong. A save that drops one is refused and the entries stay queued.\n- Do not create a second article (a new path or a near-identical title) for a subject one of these already covers.\n\n${body}\n`\n}\n\n// --- Drop-guard ---\n\nexport interface ArticleFacts {\n commits: string[]\n urls: string[]\n wikilinks: string[]\n numbers: string[]\n}\n\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/gi\nconst WIKILINK_RE = /\\[\\[([^\\]|]+)(?:\\|[^\\]]*)?\\]\\]/g\n// A short or full git hash: 7–40 hex chars holding at least one digit and\n// one letter, so words like \"defaced\" and plain numbers are not hashes.\nconst COMMIT_RE = /(?<![\\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\\w-])/gi\n// A number standing on its own: \"12\", \"1,234\", \"3.5\", \"2026-10-07\", \"14:30\",\n// \"v2\"-style suffixes excluded by the look-behind.\nconst NUMBER_RE = /(?<![\\w.,:/-])\\d+(?:[.,:\\-/]\\d+)*(?![\\w])/g\nconst LIST_MARKER_RE = /^\\s*\\d+[.)]\\s/gm\n\n/** The facts a rewrite must not lose, extracted from an article body. */\nexport function extractFacts(text: string): ArticleFacts {\n const urls = [...text.matchAll(URL_RE)].map((m) => m[0].replace(/[.,;:!?'\"]+$/, \"\"))\n const wikilinks = [...text.matchAll(WIKILINK_RE)].map((m) => m[1].trim())\n // Hashes and numbers are read with URLs and wikilink targets removed, so\n // a path segment or \"Release 2\" in a link is not counted twice.\n const rest = text.replace(URL_RE, \" \").replace(WIKILINK_RE, \" \").replace(LIST_MARKER_RE, \" \")\n const commits = [...rest.matchAll(COMMIT_RE)].map((m) => m[0].toLowerCase())\n const withoutCommits = rest.replace(COMMIT_RE, \" \")\n const numbers = [...withoutCommits.matchAll(NUMBER_RE)]\n .map((m) => normaliseNumber(m[0]))\n return {\n commits: unique(commits),\n urls: unique(urls),\n wikilinks: unique(wikilinks),\n numbers: unique(numbers),\n }\n}\n\n/**\n * The facts in `oldContent` that `newContent` no longer carries. Empty\n * means the rewrite is safe to save.\n *\n * A short hash is kept when the new text has it at any length; a URL or\n * wikilink is compared without case or trailing slash; a number is\n * compared as a token (thousands separators ignored), so \"12\" is not\n * found inside \"2012\".\n */\nexport function droppedFacts(oldContent: string, newContent: string): string[] {\n const before = extractFacts(oldContent)\n const after = extractFacts(newContent)\n const lowerNew = newContent.toLowerCase()\n const dropped: string[] = []\n\n for (const c of before.commits) {\n if (!lowerNew.includes(c) && !after.commits.some((n) => n.startsWith(c) || c.startsWith(n))) {\n dropped.push(`commit ${c}`)\n }\n }\n const urlKey = (u: string) => u.toLowerCase().replace(/\\/+$/, \"\")\n const newUrls = new Set(after.urls.map(urlKey))\n for (const u of before.urls) {\n if (!newUrls.has(urlKey(u))) dropped.push(`link ${u}`)\n }\n const newLinks = new Set(after.wikilinks.map((l) => l.toLowerCase()))\n for (const l of before.wikilinks) {\n if (!newLinks.has(l.toLowerCase())) dropped.push(`link [[${l}]]`)\n }\n const newNumbers = new Set(after.numbers)\n for (const n of before.numbers) {\n if (!newNumbers.has(n)) dropped.push(`number ${n}`)\n }\n return dropped\n}\n\nfunction normaliseNumber(n: string): string {\n // 1,234 → 1234; leave 3,5 (a decimal comma) and dates alone.\n return /^\\d{1,3}(,\\d{3})+$/.test(n) ? n.replace(/,/g, \"\") : n\n}\n\nfunction unique(list: string[]): string[] {\n return [...new Set(list)]\n}\n\n// --- Duplicate redirect ---\n\n/**\n * Where an absorbed article is written. A new path whose title an existing\n * article already carries is the same subject filed twice, so it goes to\n * the existing article — where the drop-guard then applies.\n */\nexport function absorbTargetPath(\n article: { path: string; title: string },\n catalog: Array<{ path: string; title: string }>,\n): string {\n if (catalog.some((a) => a.path === article.path)) return article.path\n const key = titleKey(article.title)\n if (!key) return article.path\n return catalog.find((a) => titleKey(a.title) === key)?.path ?? article.path\n}\n\nfunction titleKey(title: string): string {\n return (title || \"\").toLowerCase().replace(/[^\\p{L}\\p{N}]+/gu, \" \").trim()\n}\n","// Measuring what `agentx wiki absorb` writes (#808).\n//\n// Absorb turns raw entries into articles, and until now nothing checked\n// the result against the entries it came from. This module is the\n// scorecard: a fixed, seeded sample of articles, five checks per article,\n// and an optional model judge for the questions a string match cannot\n// answer (is this claim supported, does this source belong here).\n//\n// The deterministic checks are deliberately narrow. A commit hash or URL\n// in an article that no cited entry and no earlier version carries is\n// almost certainly made up or mis-attributed; a commit or URL in a cited\n// entry that no article carries was almost certainly lost. Prose claims\n// are left to the judge.\n\nimport { extractFacts } from \"./absorb-context\"\n\nexport interface EvalArticle {\n path: string\n title: string\n type?: string\n content: string\n sources: string[]\n lastUpdated?: string\n /** The article body before this absorb touched it, when one exists. */\n previous?: string\n}\n\nexport interface EvalEntry {\n id: string\n date?: string\n content: string\n}\n\n// --- Sample ---\n\n/** A small seeded PRNG, so a sample can be drawn again from the same seed. */\nexport function seededRandom(seed: string): () => number {\n let h = 1779033703 ^ seed.length\n for (let i = 0; i < seed.length; i++) {\n h = Math.imul(h ^ seed.charCodeAt(i), 3432918353)\n h = (h << 13) | (h >>> 19)\n }\n let a = h >>> 0\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** `n` items picked without replacement. Same items and seed, same pick. */\nexport function pickSample<T extends { path: string }>(items: T[], n: number, seed: string): T[] {\n const rng = seededRandom(seed)\n const pool = [...items].sort((a, b) => a.path.localeCompare(b.path))\n for (let i = pool.length - 1; i > 0; i--) {\n const j = Math.floor(rng() * (i + 1))\n ;[pool[i], pool[j]] = [pool[j], pool[i]]\n }\n return pool.slice(0, Math.max(0, n)).sort((a, b) => a.path.localeCompare(b.path))\n}\n\n// --- Terms ---\n\nconst STOP = new Set(\n (\"about after again also because been before being between could does doing during each from have having here into \"\n + \"just more most only other over same should some such than that their them then there these they this those \"\n + \"through under until very were what when where which while will with would your yours user assistant agent \"\n + \"message entry please thanks\").split(\" \"),\n)\n\n/** Distinctive words: four letters or more, lower-cased, minus common ones. */\nexport function terms(text: string): Set<string> {\n const out = new Set<string>()\n for (const m of text.toLowerCase().matchAll(/[\\p{L}\\p{N}][\\p{L}\\p{N}_-]{3,}/gu)) {\n if (!STOP.has(m[0])) out.add(m[0])\n }\n return out\n}\n\n/** Share of `entry`'s distinctive words that appear in `article`. */\nexport function termOverlap(entry: string, article: string): number {\n const e = terms(entry)\n if (e.size === 0) return 1\n const a = terms(article)\n let hit = 0\n for (const t of e) if (a.has(t)) hit++\n return hit / e.size\n}\n\n// --- Per-article checks ---\n\n/** Below this share of shared words a cited entry is flagged as weak. */\nexport const WEAK_CITATION = 0.15\n\nexport interface ArticleCheck {\n path: string\n title: string\n type?: string\n sources: number\n /** Cited ids with no entry behind them. */\n missingSources: string[]\n /** Cited entries that share almost no words with the article. */\n weakSources: string[]\n /** Commits, links and numbers in the article that neither a cited entry\n * nor the earlier version carries. */\n ungrounded: string[]\n /** Commits and links in a cited entry that no article citing it carries. */\n lost: Array<{ entry: string; fact: string }>\n}\n\n/** What a fact looks like when matched against grounding text. */\nfunction factStrings(text: string): { commits: string[]; urls: string[]; numbers: string[] } {\n const f = extractFacts(text)\n return { commits: f.commits, urls: f.urls, numbers: f.numbers }\n}\n\nfunction hasCommit(haystack: string, commit: string, known: string[]): boolean {\n return haystack.includes(commit) || known.some((k) => k.startsWith(commit) || commit.startsWith(k))\n}\n\nconst urlKey = (u: string) => u.toLowerCase().replace(/\\/+$/, \"\")\n\n/**\n * Check one article against its cited entries.\n *\n * `citersOf` returns every article (in the whole wiki, not only the\n * sample) that cites an entry, so a fact moved to a sibling article is\n * not counted as lost.\n */\nexport function checkArticle(\n article: EvalArticle,\n entries: Map<string, EvalEntry>,\n citersOf: (entryId: string) => string[],\n): ArticleCheck {\n const cited = article.sources.map((id) => entries.get(id)).filter((e): e is EvalEntry => !!e)\n const missingSources = article.sources.filter((id) => !entries.has(id))\n\n const weakSources = cited\n .filter((e) => terms(e.content).size >= 5 && termOverlap(e.content, article.content) < WEAK_CITATION)\n .map((e) => e.id)\n\n // Grounding: entry text with its date (absorb is shown the date in the\n // entry header), plus the earlier version of the article.\n const grounding = [...cited.map((e) => `${e.date ?? \"\"}\\n${e.content}`), article.previous ?? \"\"].join(\"\\n\")\n const groundLower = grounding.toLowerCase()\n const g = factStrings(grounding)\n const groundUrls = new Set(g.urls.map(urlKey))\n const groundNumbers = new Set(g.numbers)\n const mine = factStrings(article.content)\n const ungrounded: string[] = []\n for (const c of mine.commits) if (!hasCommit(groundLower, c, g.commits)) ungrounded.push(`commit ${c}`)\n for (const u of mine.urls) if (!groundUrls.has(urlKey(u)) && !groundLower.includes(urlKey(u))) ungrounded.push(`link ${u}`)\n for (const n of mine.numbers) {\n // Bare small integers (\"2 tests\", \"3 people\") are too common to judge.\n if (/^\\d{1,2}$/.test(n)) continue\n if (!groundNumbers.has(n) && !groundLower.includes(n)) ungrounded.push(`number ${n}`)\n }\n\n const lost: Array<{ entry: string; fact: string }> = []\n for (const e of cited) {\n const facts = factStrings(e.content)\n if (facts.commits.length === 0 && facts.urls.length === 0) continue\n const carriers = citersOf(e.id)\n const text = (carriers.length > 0 ? carriers : [article.content]).join(\"\\n\").toLowerCase()\n const carrierFacts = factStrings(text)\n for (const c of facts.commits) if (!hasCommit(text, c, carrierFacts.commits)) lost.push({ entry: e.id, fact: `commit ${c}` })\n for (const u of facts.urls) if (!text.includes(urlKey(u))) lost.push({ entry: e.id, fact: `link ${u}` })\n }\n\n return {\n path: article.path,\n title: article.title,\n type: article.type,\n sources: article.sources.length,\n missingSources,\n weakSources,\n ungrounded,\n lost,\n }\n}\n\n// --- Uncited entries ---\n\n/**\n * Entries absorb read and cited nowhere that carry a commit or link no\n * article on the node has. A successful run marks every entry it read as\n * done (#762), so a fact in an entry the model passed over is gone from\n * the queue for good; the per-article \"lost\" check cannot see it because\n * no article points back at the entry.\n */\nexport function uncitedWithFacts(\n uncited: EvalEntry[],\n allArticles: string,\n): Array<{ entry: string; facts: string[] }> {\n const lower = allArticles.toLowerCase()\n const known = extractFacts(allArticles).commits\n const out: Array<{ entry: string; facts: string[] }> = []\n for (const e of uncited) {\n const f = extractFacts(e.content)\n const missing = [\n ...f.commits.filter((c) => !hasCommit(lower, c, known)).map((c) => `commit ${c}`),\n ...f.urls.filter((u) => !lower.includes(urlKey(u))).map((u) => `link ${u}`),\n ]\n if (missing.length > 0) out.push({ entry: e.id, facts: missing })\n }\n return out\n}\n\n// --- Duplicates ---\n\nexport interface DuplicatePair {\n a: string\n b: string\n reason: \"title\" | \"sources\"\n score: number\n}\n\nconst TITLE_STOP = new Set(\"the and for with from into of on in at to by an a\".split(\" \"))\n\nfunction titleTerms(title: string): Set<string> {\n return new Set(\n (title || \"\").toLowerCase().split(/[^\\p{L}\\p{N}]+/u).filter((w) => (w.length > 1 || /\\d/.test(w)) && !TITLE_STOP.has(w) && !STOP.has(w)),\n )\n}\n\nfunction jaccard<T>(a: Set<T>, b: Set<T>): number {\n if (a.size === 0 || b.size === 0) return 0\n let inter = 0\n for (const x of a) if (b.has(x)) inter++\n return inter / (a.size + b.size - inter)\n}\n\n/**\n * Pairs of articles that look like one subject filed twice: the same type\n * and near-identical title words, or most of their sources in common.\n * Only pairs touching `focus` are returned when it is given.\n */\nexport function findDuplicates(\n catalog: Array<{ path: string; title: string; type?: string; sources?: string[] }>,\n focus?: Set<string>,\n opts: { titleMin?: number; sourcesMin?: number } = {},\n): DuplicatePair[] {\n const titleMin = opts.titleMin ?? 0.75\n const sourcesMin = opts.sourcesMin ?? 0.5\n const rows = catalog.map((a) => ({ ...a, tt: titleTerms(a.title), ss: new Set(a.sources ?? []) }))\n const pairs: DuplicatePair[] = []\n for (let i = 0; i < rows.length; i++) {\n for (let j = i + 1; j < rows.length; j++) {\n const x = rows[i], y = rows[j]\n if (focus && !focus.has(x.path) && !focus.has(y.path)) continue\n const t = (x.type ?? \"\") === (y.type ?? \"\") ? jaccard(x.tt, y.tt) : 0\n if (t >= titleMin) { pairs.push({ a: x.path, b: y.path, reason: \"title\", score: t }); continue }\n if (x.ss.size >= 2 && y.ss.size >= 2) {\n const s = jaccard(x.ss, y.ss)\n if (s >= sourcesMin) pairs.push({ a: x.path, b: y.path, reason: \"sources\", score: s })\n }\n }\n }\n return pairs.sort((p, q) => q.score - p.score || p.a.localeCompare(q.a))\n}\n\n// --- Model judge ---\n\nexport interface JudgeVerdict {\n claims: number\n supported: number\n unsupported: string[]\n contradicted: string[]\n /** Cited entry ids that are about a different subject (a wrong merge). */\n offSubject: string[]\n /** Facts in the entries that belong in this article and are missing. */\n missing: string[]\n verdict: \"good\" | \"minor\" | \"major\"\n}\n\n/** Per-entry cap in the judge prompt, so one long transcript cannot crowd out the rest. */\nexport const JUDGE_ENTRY_CHARS = 4000\n\nexport function buildJudgePrompt(article: EvalArticle, entries: EvalEntry[]): string {\n const sourceBlock = entries\n .map((e) => {\n const body = e.content.length > JUDGE_ENTRY_CHARS ? `${e.content.slice(0, JUDGE_ENTRY_CHARS)}\\n[…cut]` : e.content\n return `--- ENTRY ${e.id} [${e.date ?? \"\"}] ---\\n${body}\\n--- END ENTRY ---`\n })\n .join(\"\\n\\n\")\n const earlier = article.previous\n ? `\\n## Earlier version of the article (facts here count as supported)\\n\\n${article.previous}\\n`\n : \"\"\n return `You are auditing one wiki article against the raw entries it cites. Do not use outside knowledge.\n\n## Article: ${article.title} (${article.type ?? \"untyped\"}, ${article.path})\n\n${article.content}\n${earlier}\n## Cited entries (${entries.length})\n\n${sourceBlock || \"(none)\"}\n\n## What to report\n\n1. Split the article into factual claims (one per sentence or bullet; skip headings and \"unknown\" placeholders). Count them.\n2. A claim is supported when a cited entry or the earlier version states it or plainly implies it. List each claim that is not supported, quoted briefly.\n3. List each claim an entry contradicts.\n4. List the cited entry ids that are about a different subject than the article (they were merged in by mistake).\n5. List facts from the entries that belong in this article and are missing (names, numbers, identifiers, decisions). Ignore small talk.\n6. Verdict: \"good\" (nothing wrong), \"minor\" (wording or a small omission), \"major\" (an unsupported or contradicted fact, a wrong merge, or a lost identifier).\n\nReply with JSON only, no fencing:\n{\"claims\": 0, \"supported\": 0, \"unsupported\": [], \"contradicted\": [], \"off_subject\": [], \"missing\": [], \"verdict\": \"good\"}`\n}\n\nexport function parseJudgeReply(value: unknown): JudgeVerdict | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null\n const v = value as Record<string, unknown>\n const list = (x: unknown) => (Array.isArray(x) ? x.map((s) => String(s)) : [])\n const num = (x: unknown) => (typeof x === \"number\" && Number.isFinite(x) && x >= 0 ? Math.round(x) : NaN)\n const claims = num(v.claims)\n if (Number.isNaN(claims)) return null\n const supported = Math.min(claims, Number.isNaN(num(v.supported)) ? claims - list(v.unsupported).length : num(v.supported))\n const verdict = v.verdict === \"good\" || v.verdict === \"minor\" || v.verdict === \"major\" ? v.verdict : null\n if (!verdict) return null\n return {\n claims,\n supported: Math.max(0, supported),\n unsupported: list(v.unsupported),\n contradicted: list(v.contradicted),\n offSubject: list(v.off_subject ?? v.offSubject),\n missing: list(v.missing),\n verdict,\n }\n}\n\n// --- Scorecard ---\n\nexport interface Scorecard {\n sample: { articles: number; seed: string; since?: string; byType: Record<string, number> }\n citations: { withSources: number; missingSources: number; weakSources: number; articlesWithWeak: number }\n grounding: { articlesWithUngrounded: number; ungroundedFacts: number }\n lost: { entriesWithLostFacts: number; lostFacts: number }\n duplicates: { pairs: number; articlesInPair: number }\n /** Entries read in the window that no article cites. */\n uncited?: { entries: number; withLostFacts: number }\n judge?: {\n judged: number\n claims: number\n supported: number\n supportRate: number\n unsupported: number\n contradicted: number\n articlesWithWrongMerge: number\n missingFacts: number\n verdicts: Record<\"good\" | \"minor\" | \"major\", number>\n }\n examples: {\n ungrounded: Array<{ path: string; facts: string[] }>\n lost: Array<{ path: string; entry: string; fact: string }>\n weak: Array<{ path: string; entries: string[] }>\n duplicates: DuplicatePair[]\n uncited: Array<{ entry: string; facts: string[] }>\n judged: Array<{ path: string; verdict: string; unsupported: string[]; contradicted: string[]; offSubject: string[]; missing: string[] }>\n }\n}\n\nexport function buildScorecard(\n checks: ArticleCheck[],\n duplicates: DuplicatePair[],\n meta: { seed: string; since?: string },\n judged: Array<{ path: string; verdict: JudgeVerdict }> = [],\n maxExamples = 5,\n uncited?: { entries: number; lost: Array<{ entry: string; facts: string[] }> },\n): Scorecard {\n const byType: Record<string, number> = {}\n for (const c of checks) byType[c.type ?? \"untyped\"] = (byType[c.type ?? \"untyped\"] ?? 0) + 1\n const lostEntries = new Set<string>()\n const lostKeys = new Set<string>()\n for (const c of checks) for (const l of c.lost) { lostEntries.add(l.entry); lostKeys.add(`${l.entry}|${l.fact}`) }\n const inPair = new Set(duplicates.flatMap((d) => [d.a, d.b]).filter((p) => checks.some((c) => c.path === p)))\n\n const card: Scorecard = {\n sample: { articles: checks.length, seed: meta.seed, since: meta.since, byType },\n citations: {\n withSources: checks.filter((c) => c.sources > 0).length,\n missingSources: checks.reduce((s, c) => s + c.missingSources.length, 0),\n weakSources: checks.reduce((s, c) => s + c.weakSources.length, 0),\n articlesWithWeak: checks.filter((c) => c.weakSources.length > 0).length,\n },\n grounding: {\n articlesWithUngrounded: checks.filter((c) => c.ungrounded.length > 0).length,\n ungroundedFacts: checks.reduce((s, c) => s + c.ungrounded.length, 0),\n },\n lost: { entriesWithLostFacts: lostEntries.size, lostFacts: lostKeys.size },\n duplicates: { pairs: duplicates.length, articlesInPair: inPair.size },\n ...(uncited ? { uncited: { entries: uncited.entries, withLostFacts: uncited.lost.length } } : {}),\n examples: {\n ungrounded: checks.filter((c) => c.ungrounded.length > 0).slice(0, maxExamples).map((c) => ({ path: c.path, facts: c.ungrounded.slice(0, 6) })),\n lost: checks.flatMap((c) => c.lost.map((l) => ({ path: c.path, ...l }))).slice(0, maxExamples),\n weak: checks.filter((c) => c.weakSources.length > 0).slice(0, maxExamples).map((c) => ({ path: c.path, entries: c.weakSources })),\n duplicates: duplicates.slice(0, maxExamples),\n uncited: (uncited?.lost ?? []).slice(0, maxExamples).map((u) => ({ entry: u.entry, facts: u.facts.slice(0, 4) })),\n judged: judged\n .filter((j) => j.verdict.verdict !== \"good\")\n .slice(0, maxExamples)\n .map((j) => ({\n path: j.path,\n verdict: j.verdict.verdict,\n unsupported: j.verdict.unsupported.slice(0, 4),\n contradicted: j.verdict.contradicted.slice(0, 4),\n offSubject: j.verdict.offSubject,\n missing: j.verdict.missing.slice(0, 4),\n })),\n },\n }\n\n if (judged.length > 0) {\n const v = judged.map((j) => j.verdict)\n const claims = v.reduce((s, x) => s + x.claims, 0)\n const supported = v.reduce((s, x) => s + x.supported, 0)\n card.judge = {\n judged: v.length,\n claims,\n supported,\n supportRate: claims > 0 ? supported / claims : 1,\n unsupported: v.reduce((s, x) => s + x.unsupported.length, 0),\n contradicted: v.reduce((s, x) => s + x.contradicted.length, 0),\n articlesWithWrongMerge: v.filter((x) => x.offSubject.length > 0).length,\n missingFacts: v.reduce((s, x) => s + x.missing.length, 0),\n verdicts: {\n good: v.filter((x) => x.verdict === \"good\").length,\n minor: v.filter((x) => x.verdict === \"minor\").length,\n major: v.filter((x) => x.verdict === \"major\").length,\n },\n }\n }\n return card\n}\n\nconst pct = (n: number, d: number) => (d > 0 ? `${Math.round((n / d) * 100)}%` : \"–\")\n\n/** The scorecard as Markdown, for the issue or a PR comment. */\nexport function renderScorecard(card: Scorecard): string {\n const n = card.sample.articles\n const lines = [\n `# Wiki absorb scorecard`,\n \"\",\n `Sample: ${n} articles (seed \\`${card.sample.seed}\\`${card.sample.since ? `, changed since ${card.sample.since}` : \"\"}). `\n + `Types: ${Object.entries(card.sample.byType).map(([t, k]) => `${t} ${k}`).join(\", \") || \"–\"}.`,\n \"\",\n \"| Check | Result | Lower is better? |\",\n \"|---|---|---|\",\n `| Articles citing at least one entry | ${card.citations.withSources}/${n} (${pct(card.citations.withSources, n)}) | no |`,\n `| Cited ids with no entry | ${card.citations.missingSources} | yes |`,\n `| Articles with a weak citation (entry shares <${Math.round(WEAK_CITATION * 100)}% of its words) | ${card.citations.articlesWithWeak}/${n} (${pct(card.citations.articlesWithWeak, n)}) | yes |`,\n `| Articles with an ungrounded commit, link or number | ${card.grounding.articlesWithUngrounded}/${n} (${pct(card.grounding.articlesWithUngrounded, n)}) | yes |`,\n `| Ungrounded facts | ${card.grounding.ungroundedFacts} | yes |`,\n `| Commits or links lost from cited entries | ${card.lost.lostFacts} across ${card.lost.entriesWithLostFacts} entries | yes |`,\n `| Sampled articles in a likely duplicate pair | ${card.duplicates.articlesInPair}/${n} (${pct(card.duplicates.articlesInPair, n)}) | yes |`,\n ]\n if (card.uncited) {\n lines.push(\n `| Entries read in the window but cited by no article | ${card.uncited.entries} | – |`,\n `| …of which carry a commit or link no article has | ${card.uncited.withLostFacts} | yes |`,\n )\n }\n if (card.judge) {\n const j = card.judge\n lines.push(\n `| Judge: claims supported by the cited entries | ${j.supported}/${j.claims} (${pct(j.supported, j.claims)}) | no |`,\n `| Judge: unsupported / contradicted claims | ${j.unsupported} / ${j.contradicted} | yes |`,\n `| Judge: articles with an off-subject source (wrong merge) | ${j.articlesWithWrongMerge}/${j.judged} (${pct(j.articlesWithWrongMerge, j.judged)}) | yes |`,\n `| Judge: facts missing from the article | ${j.missingFacts} | yes |`,\n `| Judge verdicts good / minor / major | ${j.verdicts.good} / ${j.verdicts.minor} / ${j.verdicts.major} | – |`,\n )\n }\n const ex = card.examples\n const section = (title: string, rows: string[]) => {\n if (rows.length === 0) return\n lines.push(\"\", `## ${title}`, \"\", ...rows)\n }\n section(\"Examples: ungrounded facts\", ex.ungrounded.map((e) => `- \\`${e.path}\\`: ${e.facts.join(\"; \")}`))\n section(\"Examples: lost facts\", ex.lost.map((e) => `- \\`${e.path}\\` ← entry \\`${e.entry}\\`: ${e.fact}`))\n section(\"Examples: weak citations\", ex.weak.map((e) => `- \\`${e.path}\\`: ${e.entries.map((x) => `\\`${x}\\``).join(\", \")}`))\n section(\"Examples: uncited entries with facts no article has\", ex.uncited.map((u) => `- \\`${u.entry}\\`: ${u.facts.join(\"; \")}`))\n section(\"Examples: likely duplicates\", ex.duplicates.map((d) => `- \\`${d.a}\\` ↔ \\`${d.b}\\` (${d.reason}, ${d.score.toFixed(2)})`))\n section(\n \"Examples: judge findings\",\n ex.judged.map((e) => {\n const parts = [\n e.unsupported.length ? `unsupported: ${e.unsupported.join(\" | \")}` : \"\",\n e.contradicted.length ? `contradicted: ${e.contradicted.join(\" | \")}` : \"\",\n e.offSubject.length ? `off-subject: ${e.offSubject.join(\", \")}` : \"\",\n e.missing.length ? `missing: ${e.missing.join(\" | \")}` : \"\",\n ].filter(Boolean)\n return `- \\`${e.path}\\` (${e.verdict}): ${parts.join(\"; \")}`\n }),\n )\n lines.push(\n \"\",\n \"## Method\",\n \"\",\n \"- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.\",\n \"- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.\",\n \"- Lost: a commit hash or link in a cited entry that no article citing that entry contains.\",\n \"- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.\",\n \"- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.\",\n \"- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.\",\n \"- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items.\",\n )\n return lines.join(\"\\n\") + \"\\n\"\n}\n\n// --- Run telemetry ---\n\n/** One compile call, as appended to `_absorb-runs.jsonl`. */\nexport interface AbsorbCallRecord {\n kind: \"call\"\n at: string\n label?: string\n agent: string\n model: string\n entries: number\n articles: number\n refused: number\n /** Entries held by a refused save that another saved article cites:\n * they leave the queue, so the refused update is never retried. */\n heldCited?: number\n failed: boolean\n /** The model call alone. */\n wallMs: number\n /** Retrieval, fact lookups and prompt building before the call. */\n prepMs?: number\n promptChars: number\n promptParts?: Record<string, number>\n costUsd?: number\n apiMs?: number\n inputTokens?: number\n outputTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n}\n\n/** One whole `wiki absorb` invocation. */\nexport interface AbsorbRunRecord {\n kind: \"run\"\n label?: string\n startedAt: string\n endedAt: string\n max: number\n model: string\n}\n\n/** Cost and timing fields from the claude CLI's `--output-format json` envelope. */\nexport function envelopeUsage(envelope: unknown): Partial<AbsorbCallRecord> {\n if (!envelope || typeof envelope !== \"object\") return {}\n const e = envelope as Record<string, any>\n const u = (e.usage ?? {}) as Record<string, unknown>\n const n = (x: unknown) => (typeof x === \"number\" && Number.isFinite(x) ? x : undefined)\n return {\n costUsd: n(e.total_cost_usd) ?? n(e.cost_usd),\n apiMs: n(e.duration_api_ms),\n inputTokens: n(u.input_tokens),\n outputTokens: n(u.output_tokens),\n cacheReadTokens: n(u.cache_read_input_tokens),\n cacheWriteTokens: n(u.cache_creation_input_tokens),\n }\n}\n\nexport interface RunSummary {\n label: string\n calls: number\n failed: number\n entries: number\n articles: number\n refused: number\n heldCited: number\n /** First call start to last call end, or the run records' span when present. */\n wallMs: number\n callMsP50: number\n callMsP95: number\n /** Time spent before the model calls, summed. */\n prepMs: number\n costUsd: number\n costPerEntry: number\n entriesPerMinute: number\n promptChars: number\n}\n\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0\n return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]\n}\n\n/** Totals per run label from the telemetry lines. Calls without a label group under \"(none)\". */\nexport function summariseRuns(records: Array<AbsorbCallRecord | AbsorbRunRecord>): RunSummary[] {\n const groups = new Map<string, { calls: AbsorbCallRecord[]; runs: AbsorbRunRecord[] }>()\n const group = (label?: string) => {\n const key = label || \"(none)\"\n let g = groups.get(key)\n if (!g) groups.set(key, (g = { calls: [], runs: [] }))\n return g\n }\n for (const r of records) {\n if (r.kind === \"call\") group(r.label).calls.push(r)\n else if (r.kind === \"run\") group(r.label).runs.push(r)\n }\n const out: RunSummary[] = []\n for (const [label, { calls, runs }] of groups) {\n if (calls.length === 0) continue\n const ms = calls.map((c) => c.wallMs).sort((a, b) => a - b)\n let wallMs: number\n if (runs.length > 0) {\n wallMs = runs.reduce((s, r) => s + (Date.parse(r.endedAt) - Date.parse(r.startedAt)), 0)\n } else {\n const starts = calls.map((c) => Date.parse(c.at) - c.wallMs)\n const ends = calls.map((c) => Date.parse(c.at))\n wallMs = Math.max(...ends) - Math.min(...starts)\n }\n const entries = calls.reduce((s, c) => s + c.entries, 0)\n const costUsd = calls.reduce((s, c) => s + (c.costUsd ?? 0), 0)\n out.push({\n label,\n calls: calls.length,\n failed: calls.filter((c) => c.failed).length,\n entries,\n articles: calls.reduce((s, c) => s + c.articles, 0),\n refused: calls.reduce((s, c) => s + c.refused, 0),\n heldCited: calls.reduce((s, c) => s + (c.heldCited ?? 0), 0),\n wallMs,\n callMsP50: percentile(ms, 0.5),\n callMsP95: percentile(ms, 0.95),\n prepMs: calls.reduce((s, c) => s + (c.prepMs ?? 0), 0),\n costUsd,\n costPerEntry: entries > 0 ? costUsd / entries : 0,\n entriesPerMinute: wallMs > 0 ? (entries / wallMs) * 60_000 : 0,\n promptChars: calls.reduce((s, c) => s + c.promptChars, 0),\n })\n }\n return out.sort((a, b) => a.label.localeCompare(b.label))\n}\n"],"mappings":"wCAqCA,eAAsBA,EACpBC,EACAC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACD,CAC5B,IAAMC,EAAWD,EAAK,UAAYE,EAC5BC,EAAWH,EAAK,UAAY,EAC5BI,EAAcJ,EAAK,aAAe,EAClCK,EAAaL,EAAK,YAAc,KAChCM,EAAQ,IAAI,IAElB,QAAWC,KAASX,EAAS,CAC3B,IAAIY,EAA6C,CAAC,EAClD,GAAI,CACFA,EAAO,MAAMP,EAASM,EAAM,QAAQ,MAAM,EAAGF,CAAU,EAAGR,EAAOC,EAAS,CACxE,KAAAC,EACA,cAAeI,EACf,QAAS,EACT,YAAaA,EAAW,EACxB,MAAO,iBACT,CAAC,CACH,MAAE,CAEF,CACA,QAAWM,KAAOD,EAAM,CACtB,IAAME,EAAOJ,EAAM,IAAIG,EAAI,IAAI,EAC3BC,GACFA,EAAK,IAAM,KAAK,IAAIA,EAAK,IAAKD,EAAI,GAAG,EAChCC,EAAK,QAAQ,SAASH,EAAM,EAAE,GAAGG,EAAK,QAAQ,KAAKH,EAAM,EAAE,GAEhED,EAAM,IAAIG,EAAI,KAAM,CAAE,GAAGA,EAAK,QAAS,CAACF,EAAM,EAAE,CAAE,CAAC,GAKzD,MAAO,CAAC,GAAGD,EAAM,OAAO,CAAC,EACtB,KAAK,CAACK,EAAGC,IAAMD,EAAE,IAAMC,EAAE,KAAOA,EAAE,QAAQ,OAASD,EAAE,QAAQ,QAAUA,EAAE,KA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,CAAC9C,EAAGtB,IAAMsB,EAAItB,EAAE,QAAS,CAAC,EAChD,UAAWoE,EAAM,OAAO,CAAC9C,EAAGtB,IAAMsB,GAAKtB,EAAE,WAAa,GAAI,CAAC,EAC3D,OAAAuE,EACA,UAAWZ,EAAWW,EAAI,EAAG,EAC7B,UAAWX,EAAWW,EAAI,GAAI,EAC9B,OAAQF,EAAM,OAAO,CAAC9C,EAAGtB,IAAMsB,GAAKtB,EAAE,QAAU,GAAI,CAAC,EACrD,QAAA0E,EACA,aAAc3F,EAAU,EAAI2F,EAAU3F,EAAU,EAChD,iBAAkBwF,EAAS,EAAKxF,EAAUwF,EAAU,IAAS,EAC7D,YAAaH,EAAM,OAAO,CAAC9C,EAAGtB,IAAMsB,EAAItB,EAAE,YAAa,CAAC,CAC1D,CAAC,EAEH,OAAOpC,EAAI,KAAK,CAACZ,EAAGO,IAAMP,EAAE,MAAM,cAAcO,EAAE,KAAK,CAAC,CAC1D","names":["findCoveringArticles","entries","store","agentId","pool","opts","retrieve","retrieveArticles","perEntry","maxArticles","queryChars","found","entry","hits","hit","seen","a","b","renderCoveringBlock","articles","body","header","why","related","l","URL_RE","WIKILINK_RE","COMMIT_RE","NUMBER_RE","LIST_MARKER_RE","extractFacts","text","urls","m","wikilinks","rest","commits","numbers","normaliseNumber","unique","droppedFacts","oldContent","newContent","before","after","lowerNew","dropped","c","urlKey","u","newUrls","newLinks","newNumbers","n","list","absorbTargetPath","article","catalog","key","titleKey","title","seededRandom","seed","h","i","a","t","pickSample","items","n","rng","pool","b","j","STOP","terms","text","out","m","termOverlap","entry","article","e","hit","WEAK_CITATION","factStrings","f","extractFacts","hasCommit","haystack","commit","known","k","urlKey","u","checkArticle","entries","citersOf","cited","id","missingSources","weakSources","grounding","groundLower","g","groundUrls","groundNumbers","mine","ungrounded","lost","facts","carriers","carrierFacts","c","uncitedWithFacts","uncited","allArticles","lower","missing","TITLE_STOP","titleTerms","title","w","jaccard","inter","x","findDuplicates","catalog","focus","opts","titleMin","sourcesMin","rows","pairs","y","s","p","q","JUDGE_ENTRY_CHARS","buildJudgePrompt","sourceBlock","body","earlier","parseJudgeReply","value","v","list","num","claims","supported","verdict","buildScorecard","checks","duplicates","meta","judged","maxExamples","byType","lostEntries","lostKeys","l","inPair","d","card","pct","renderScorecard","lines","ex","section","parts","envelopeUsage","envelope","percentile","sorted","summariseRuns","records","groups","group","label","key","r","calls","runs","ms","wallMs","starts","ends","costUsd"]}
|
package/dist/chunk-TJ4P4WW2.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{a as c}from"./chunk-EHLTZ6IB.js";import{resolve as a}from"path";import{existsSync as h,readdirSync as y,mkdirSync as l,readFileSync as u,writeFileSync as p,renameSync as f}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=a(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=a(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new c(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=a(this.agentsDir,e,this.mode),i=new c(t,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(h(this.agentsDir))for(let t of y(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let i=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let s of r)g.entries[s]={at:d,cited:i.has(s)};let n=this.ledgerPath(e);l(a(n,".."),{recursive:!0});let o=`${n}.tmp`;p(o,`${JSON.stringify(g,null,2)}
|
|
2
|
-
`),f(o,n)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let i=r.get(t.agentId);i?i.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:i,cited:g,read:d,pending:n,articles:o}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:i.length,totalArticles:o.length,cited:g.length,readNotCited:d.length,unabsorbed:n.length,articles:o}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,i=new Set;for(let s of t)if(s.sources)for(let S of s.sources)i.add(S);let g=this.readLedger(e).entries,d=[],n=[],o=[];for(let s of r)i.has(s.id)?d.push(s):g[s.id]?n.push(s):o.push(s);return{all:r,cited:d,read:n,pending:o,articles:t}}syncedFrom(e){let r=a(this.agentsDir,e,"_synced.json");if(!h(r))return null;try{return JSON.parse(u(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=a(this.agentsDir,e,"_synced.json");l(a(t,".."),{recursive:!0});let i=`${t}.tmp`;p(i,`${JSON.stringify(r,null,2)}
|
|
3
|
-
`),f(i,t)}ledgerPath(e){return a(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!h(r))return{entries:{}};try{return{entries:JSON.parse(u(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-TJ4P4WW2.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/hub.ts"],"sourcesContent":["import { WikiStore } from \"./store\"\nimport { resolve } from \"path\"\nimport { existsSync, readdirSync, mkdirSync, readFileSync, writeFileSync, renameSync } from \"fs\"\nimport type { WikiEntry } from \"./types\"\n\nexport type WikiMode = \"flat\" | \"graph\" | \"unified\"\n\n/**\n * WikiHub: manages per-agent wikis with a shared raw entry pool.\n * Supports two compilation modes:\n * - flat: Karpathy pattern — tags, LLM-chosen paths, worldview, gap detection\n * - graph: Knowledge graph — kind, parent, hierarchy, events, entities\n *\n * Both modes share the same raw entries. Articles stored separately:\n * agents/<id>/flat/ ← Karpathy compilation\n * agents/<id>/graph/ ← Knowledge graph compilation\n */\nexport class WikiHub {\n private baseDir: string\n private agentsDir: string\n private mode: WikiMode\n private sharedStore: WikiStore\n private agentStores: Map<string, WikiStore> = new Map()\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-hub]\"),\n mode: WikiMode = \"graph\",\n ) {\n this.baseDir = baseDir\n this.agentsDir = resolve(baseDir, \"agents\")\n this.mode = mode\n this.log = log\n\n mkdirSync(this.agentsDir, { recursive: true })\n this.sharedStore = new WikiStore(baseDir, log)\n }\n\n getMode(): WikiMode { return this.mode }\n\n /**\n * Get or create the wiki store for a specific agent (mode-aware).\n * flat: agents/<id>/flat/\n * graph: agents/<id>/graph/\n */\n getAgentWiki(agentId: string): WikiStore {\n const key = `${agentId}:${this.mode}`\n if (this.agentStores.has(key)) return this.agentStores.get(key)!\n\n const agentDir = resolve(this.agentsDir, agentId, this.mode)\n const store = new WikiStore(agentDir, this.log)\n this.agentStores.set(key, store)\n return store\n }\n\n /** The wiki root: shared sidecars (_facts.json, _questions.json) live here. */\n getBaseDir(): string {\n return this.baseDir\n }\n\n getSharedStore(): WikiStore {\n return this.sharedStore\n }\n\n listAgents(entries: WikiEntry[] = this.sharedStore.listEntries()): string[] {\n const agents = new Set<string>()\n\n for (const e of entries) agents.add(e.agentId)\n\n if (existsSync(this.agentsDir)) {\n for (const dir of readdirSync(this.agentsDir)) {\n if (!dir.startsWith(\"_\") && !dir.startsWith(\".\")) {\n agents.add(dir)\n }\n }\n }\n\n return [...agents].sort()\n }\n\n getAgentEntries(agentId: string): WikiEntry[] {\n return this.sharedStore.listEntries({ agentId })\n }\n\n /**\n * Entries absorb has not dealt with yet: no article cites them and no\n * successful absorb run has read them. Without the second check an\n * entry absorb read and chose not to cite came back on every run, and\n * a backfill kept re-reading the head of the queue (#762).\n */\n getUnabsorbedEntries(agentId: string): WikiEntry[] {\n return this.classifyEntries(agentId).pending\n }\n\n /**\n * Record every entry handed to the model in a successful absorb run,\n * cited or not. Callers must not call this for a failed run, so those\n * entries are offered again.\n */\n markProcessed(agentId: string, entryIds: string[], citedIds: Iterable<string>): void {\n const cited = new Set(citedIds)\n const ledger = this.readLedger(agentId)\n const at = new Date().toISOString()\n for (const id of entryIds) ledger.entries[id] = { at, cited: cited.has(id) }\n\n const file = this.ledgerPath(agentId)\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(ledger, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /**\n * Counts and articles per agent, for `GET /wiki/agents` and the mesh.\n * The raw entries are read once and grouped here: reading them again\n * per agent made the endpoint take 25 to 75 s on a fleet with 30\n * agents and 10k entries, past the mesh client's 5 s timeout (#603).\n */\n summary(): AgentWikiSummary[] {\n const entries = this.sharedStore.listEntries()\n const byAgent = new Map<string, WikiEntry[]>()\n for (const e of entries) {\n const list = byAgent.get(e.agentId)\n if (list) list.push(e)\n else byAgent.set(e.agentId, [e])\n }\n return this.listAgents(entries).map(agentId => {\n const { all, cited, read, pending, articles } = this.classifyEntries(agentId, byAgent.get(agentId) ?? [])\n return {\n agentId,\n totalEntries: all.length,\n totalArticles: articles.length,\n cited: cited.length,\n readNotCited: read.length,\n unabsorbed: pending.length,\n articles,\n }\n })\n }\n\n /** Split an agent's entries into cited by an article, read but not cited, and pending. */\n private classifyEntries(agentId: string, all: WikiEntry[] = this.getAgentEntries(agentId)) {\n const articles = this.getAgentWiki(agentId).rebuildIndex().articles\n\n const citedIds = new Set<string>()\n for (const article of articles) {\n if (article.sources) {\n for (const s of article.sources) citedIds.add(s)\n }\n }\n const ledger = this.readLedger(agentId).entries\n\n const cited: WikiEntry[] = []\n const read: WikiEntry[] = []\n const pending: WikiEntry[] = []\n for (const e of all) {\n if (citedIds.has(e.id)) cited.push(e)\n else if (ledger[e.id]) read.push(e)\n else pending.push(e)\n }\n return { all, cited, read, pending, articles }\n }\n\n /**\n * The peer an agent's articles were copied from by `wiki sync --articles`,\n * or null for an agent this node absorbs itself. A copied agent is\n * read-only here: absorb and patch leave it to its home node.\n */\n syncedFrom(agentId: string): SyncedFrom | null {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n if (!existsSync(file)) return null\n try {\n return JSON.parse(readFileSync(file, \"utf-8\")) as SyncedFrom\n } catch (err) {\n // A damaged marker still means the agent lives elsewhere.\n this.log(`synced marker ${file} is not valid JSON: ${(err as Error).message}`)\n return { node: \"unknown\", peerUrl: \"\", at: \"\" }\n }\n }\n\n markSynced(agentId: string, from: SyncedFrom): void {\n const file = resolve(this.agentsDir, agentId, \"_synced.json\")\n mkdirSync(resolve(file, \"..\"), { recursive: true })\n const tmp = `${file}.tmp`\n writeFileSync(tmp, `${JSON.stringify(from, null, 2)}\\n`)\n renameSync(tmp, file)\n }\n\n /** agents/<id>/_absorbed.json — shared by every mode, like the raw entries. */\n private ledgerPath(agentId: string): string {\n return resolve(this.agentsDir, agentId, \"_absorbed.json\")\n }\n\n private readLedger(agentId: string): AbsorbLedger {\n const file = this.ledgerPath(agentId)\n if (!existsSync(file)) return { entries: {} }\n try {\n const parsed = JSON.parse(readFileSync(file, \"utf-8\")) as AbsorbLedger\n return { entries: parsed.entries ?? {} }\n } catch (err) {\n // Treating a damaged ledger as empty would let the next run\n // overwrite it and re-queue everything it recorded.\n throw new Error(`absorb ledger ${file} is not valid JSON: ${(err as Error).message}`)\n }\n }\n}\n\nexport interface SyncedFrom {\n /** The peer's node id. */\n node: string\n peerUrl: string\n /** When the last copy finished. */\n at: string\n}\n\ninterface AbsorbLedger {\n entries: Record<string, { at: string; cited: boolean }>\n}\n\nexport interface AgentWikiSummary {\n agentId: string\n totalEntries: number\n totalArticles: number\n /** Entries an article cites. */\n cited: number\n /** Entries a successful absorb run read and did not cite. */\n readNotCited: number\n /** Entries absorb has not read yet. */\n unabsorbed: number\n articles: Array<{ title: string; path: string; tags?: string[] }>\n}\n"],"mappings":"wCACA,OAAS,WAAAA,MAAe,OACxB,OAAS,cAAAC,EAAY,eAAAC,EAAa,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,EAAe,cAAAC,MAAkB,KAerF,IAAMC,EAAN,KAAc,CACX,QACA,UACA,KACA,YACA,YAAsC,IAAI,IAC1C,IAER,YACEC,EAAkBR,EAAQ,QAAQ,IAAI,EAAG,cAAc,EACvDS,EAAoC,QAAQ,MAAM,KAAK,QAAS,YAAY,EAC5EC,EAAiB,QACjB,CACA,KAAK,QAAUF,EACf,KAAK,UAAYR,EAAQQ,EAAS,QAAQ,EAC1C,KAAK,KAAOE,EACZ,KAAK,IAAMD,EAEXN,EAAU,KAAK,UAAW,CAAE,UAAW,EAAK,CAAC,EAC7C,KAAK,YAAc,IAAIQ,EAAUH,EAASC,CAAG,CAC/C,CAEA,SAAoB,CAAE,OAAO,KAAK,IAAK,CAOvC,aAAaG,EAA4B,CACvC,IAAMC,EAAM,GAAGD,KAAW,KAAK,OAC/B,GAAI,KAAK,YAAY,IAAIC,CAAG,EAAG,OAAO,KAAK,YAAY,IAAIA,CAAG,EAE9D,IAAMC,EAAWd,EAAQ,KAAK,UAAWY,EAAS,KAAK,IAAI,EACrDG,EAAQ,IAAIJ,EAAUG,EAAU,KAAK,GAAG,EAC9C,YAAK,YAAY,IAAID,EAAKE,CAAK,EACxBA,CACT,CAGA,YAAqB,CACnB,OAAO,KAAK,OACd,CAEA,gBAA4B,CAC1B,OAAO,KAAK,WACd,CAEA,WAAWC,EAAuB,KAAK,YAAY,YAAY,EAAa,CAC1E,IAAMC,EAAS,IAAI,IAEnB,QAAWC,KAAKF,EAASC,EAAO,IAAIC,EAAE,OAAO,EAE7C,GAAIjB,EAAW,KAAK,SAAS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,CAAE,UAAW,EAAK,CAAC,EAClD,IAAMC,EAAM,GAAGD,QACfrB,EAAcsB,EAAK,GAAG,KAAK,UAAUU,EAAM,KAAM,CAAC;AAAA,CAAK,EACvD/B,EAAWqB,EAAKD,CAAI,CACtB,CAGQ,WAAWd,EAAyB,CAC1C,OAAOZ,EAAQ,KAAK,UAAWY,EAAS,gBAAgB,CAC1D,CAEQ,WAAWA,EAA+B,CAChD,IAAMc,EAAO,KAAK,WAAWd,CAAO,EACpC,GAAI,CAACX,EAAWyB,CAAI,EAAG,MAAO,CAAE,QAAS,CAAC,CAAE,EAC5C,GAAI,CAEF,MAAO,CAAE,QADM,KAAK,MAAMtB,EAAasB,EAAM,OAAO,CAAC,EAC5B,SAAW,CAAC,CAAE,CACzC,OAASU,EAAP,CAGA,MAAM,IAAI,MAAM,iBAAiBV,wBAA4BU,EAAc,SAAS,CACtF,CACF,CACF","names":["resolve","existsSync","readdirSync","mkdirSync","readFileSync","writeFileSync","renameSync","WikiHub","baseDir","log","mode","WikiStore","agentId","key","agentDir","store","entries","agents","e","dir","entryIds","citedIds","cited","ledger","at","id","file","tmp","byAgent","list","all","read","pending","articles","article","s","err","from"]}
|
package/dist/chunk-UJXS4MS3.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{c as R}from"./chunk-56KNKUFF.js";import{a as O,b as j,c as E,d as T,e as D,j as _}from"./chunk-LTH3AYXC.js";import{y as M,z as F}from"./chunk-3KYZOC7N.js";import{b as S,c as P}from"./chunk-QOYAX2FT.js";import{readFileSync as G,existsSync as J}from"fs";F();import{resolve as $}from"path";import{execSync as K}from"child_process";async function it(r,e,i,t={}){let h=t.selectorModel??"haiku",m=t.synthModel??"sonnet",o=t.maxCandidates??3,c=t.maxHops??2,n=t.maxArticles??8,u=t.timeoutMs??6e4,g=t.log??console.error.bind(console,"[wiki-query]"),p=t.messagePath?.length?t.messagePath:void 0,s=t.graphWeight??x,a=$(e.baseDir,"_index.md");if(!J(a))return b("no-catalog",r,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let d=G(a,"utf-8"),v=Date.now(),f=[],y="";try{let l=await Y(r,N(e),i,o,p,s);l?(f=l,y=`[wiki-rerank seat] ${l.map(k=>k.title).join(" | ")}`):(y=await I(U(r,d,o,p),h,u),f=V(y))}catch(l){return g("selector failed:",l?.message),{...b("error",r,`Selector: ${l?.message||"unknown"}`),trace:{selectorMs:Date.now()-v,synthesisMs:0,selectorOutput:y}}}let A=Date.now()-v;if(f.length===0)return{...b("no-candidates",r,"Selector returned no candidates."),trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let w=Q(f,e,i,c,n);if(w.length===0)return{...b("no-candidates",r,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:A,synthesisMs:0,selectorOutput:y}};let C=Date.now(),W="";try{W=await I(z(r,w),m,u*2)}catch(l){return g("synthesis failed:",l?.message),{...b("error",r,`Synthesis: ${l?.message||"unknown"}`),candidates:f,walked:w.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:A,synthesisMs:Date.now()-C,selectorOutput:y}}}let L=Date.now()-C;return{answer:W.trim(),citations:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type})),candidates:f,walked:w.map(l=>({title:l.meta.title,path:l.path,type:l.meta.type,hop:l.hop??0})),status:"ok",trace:{selectorMs:A,synthesisMs:L,selectorOutput:y}}}async function st(r,e,i,t={}){let h=t.maxCandidates??3,m=t.graphWeight??x,o=t.messagePath?.length?t.messagePath:void 0,c=t.pool??N(e);if(c.length===0||!r.trim())return[];let n=await Y(r,c,i,h,o,m,t.stage??"retrieve");if(!n){let u=new Set(P(r,S(c.map(H))).map(g=>g.docIndex));n=B(r,c,o,m).filter(g=>u.has(g)).slice(0,h).map(g=>({title:c[g].title,path:c[g].path}))}return n.length===0?[]:Q(n,e,i,t.maxHops??1,t.maxArticles??6)}function N(r){try{return(r.rebuildIndex().articles??[]).filter(e=>e.path&&!e.path.includes("/_versions/"))}catch{return[]}}function b(r,e,i){return{answer:"",citations:[],candidates:[],walked:[],status:r,error:i}}function Q(r,e,i,t,h){let m=new Map;for(let n of e.listArticles(i||""))m.set(n.meta.title.toLowerCase(),n.path);let o=new Map,c=[];for(let n of r)o.has(n.path)||c.push({path:n.path,hop:0});for(;c.length&&o.size<h;){let n=c.shift();if(o.has(n.path)||n.hop>t)continue;let u=i?e.readArticleAs(n.path,i):e.readArticle(n.path);if(u&&(o.set(n.path,{...u,hop:n.hop}),!(n.hop>=t)))for(let g of u.meta.related||[]){let p=m.get(g.toLowerCase());p&&!o.has(p)&&c.push({path:p,hop:n.hop+1})}}return Array.from(o.values())}async function Y(r,e,i,t,h,m=x,o="catalog-selector"){try{if(e.length<2)return null;let n=B(r,e,h,m).slice(0,j).map(s=>({id:`k${s}`,title:e[s].title||e[s].path,tags:e[s].tags,excerpt:[e[s].type?`type: ${e[s].type}`:"",(e[s].related??[]).length?`related: ${(e[s].related??[]).join(", ")}`:"",(e[s].graphPath??[]).length?`graph: ${(e[s].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),u=await M(O,E({query:r,candidates:n,excerptChars:300}),T(n),{features:{agent:i??"unknown",stage:o}});if(!u||u.mode!=="active")return null;let p=D(u.answers,n).ranked.slice(0,t).map(s=>e[Number(s.slice(1))]).filter(Boolean).map(s=>({title:s.title,path:s.path}));return p.length>0?p:null}catch{return null}}var x=.6;function B(r,e,i,t=x){let h=P(r,S(e.map(H))),m=h.reduce((a,d)=>Math.max(a,d.score),0),o=new Map(h.map(a=>[a.docIndex,m>0?a.score/m:0])),c=!!i?.length,n=a=>c&&a.graphPath?.length?_(i,a.graphPath):0,u=(a,d)=>d.score-a.score||a.i-d.i,g=e.map((a,d)=>({i:d,score:(o.get(d)??0)*(1+t*n(a))})).filter(a=>o.has(a.i)).sort(u),p=e.map((a,d)=>({i:d,score:n(a)})).filter(a=>!o.has(a.i)&&a.score>0).sort(u),s=[...g,...p].map(a=>a.i);for(let a=0;a<e.length;a++)s.includes(a)||s.push(a);return s}function H(r){return[r.title,(r.tags??[]).join(" "),(r.related??[]).join(" ")].join(" ")}function U(r,e,i,t){let h=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
|
-
${r}
|
|
10
|
-
${h}
|
|
11
|
-
## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
|
|
12
|
-
|
|
13
|
-
${e}
|
|
14
|
-
|
|
15
|
-
## Your task
|
|
16
|
-
|
|
17
|
-
Pick up to ${i} 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 z(r,e){let i=e.map(t=>{let h=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,m=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[h,m,"",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
|
-
${r}
|
|
39
|
-
|
|
40
|
-
## Articles (${e.length} walked from the catalog)
|
|
41
|
-
|
|
42
|
-
${i}
|
|
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 V(r){let e=r.match(/\[[\s\S]*?\]/);if(!e)return[];try{let i=JSON.parse(e[0]);return Array.isArray(i)?i.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function I(r,e,i){let{writeFileSync:t,mkdirSync:h,rmSync:m}=await import("fs"),{tmpdir:o}=await import("os"),c=$(o(),`agentx-wiki-query-${process.pid}`);h(c,{recursive:!0});let n=$(c,`prompt-${Date.now()}.txt`);t(n,r);try{let u=`cat '${n}' | claude -p - --output-format json --max-turns 1 --model ${e} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,g=K(u,{env:R(),encoding:"utf-8",timeout:i,maxBuffer:4*1024*1024});try{let p=JSON.parse(g);return String(p.result||p.content||"")}catch{return g}}finally{try{m(n,{force:!0})}catch{}}}export{it as a,st as b,N as c,x as d,B as e};
|
|
49
|
-
//# sourceMappingURL=chunk-UJXS4MS3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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 { claudeCliEnv } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle, WikiIndex } 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, catalogPool(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\nexport interface RetrieveOptions {\n /** Articles picked before the walk. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from the picked articles. Default 1. */\n maxHops?: number\n /** Hard cap on articles returned. Default 6. */\n maxArticles?: number\n messagePath?: string[]\n graphWeight?: number\n /** The catalog to pick from. Pass it when retrieving many times in a row,\n * so the index is not rebuilt for every call. */\n pool?: CatalogEntry[]\n /** Seat telemetry label. */\n stage?: string\n}\n\n/**\n * The retrieval half of agenticQuery, without the synthesis call: BM25\n * shortlist, rerank seat, then the `related` wikilink walk. Returns the\n * walked articles, hop 0 first.\n *\n * When the seat is off or fails, the BM25 order decides on its own, and\n * only articles the text matched are picked: an article chosen for\n * nothing but its catalog position is noise here, not a candidate. There\n * is no CLI fallback, so this never spends an LLM call.\n */\nexport async function retrieveArticles(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: RetrieveOptions = {},\n): Promise<Array<WikiArticle & { hop: number }>> {\n const maxCandidates = opts.maxCandidates ?? 3\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const pool = opts.pool ?? catalogPool(store)\n if (pool.length === 0 || !question.trim()) return []\n\n let candidates = await selectCandidatesViaSeat(\n question, pool, requesterId, maxCandidates, messagePath, graphWeight, opts.stage ?? \"retrieve\",\n )\n if (!candidates) {\n const matched = new Set(scoreAll(question, buildIndex(pool.map(catalogDoc))).map((r) => r.docIndex))\n candidates = rankCatalogPool(question, pool, messagePath, graphWeight)\n .filter((i) => matched.has(i))\n .slice(0, maxCandidates)\n .map((i) => ({ title: pool[i].title, path: pool[i].path }))\n }\n if (candidates.length === 0) return []\n return walkSubgraph(candidates, store, requesterId, opts.maxHops ?? 1, opts.maxArticles ?? 6)\n}\n\nexport type CatalogEntry = WikiIndex[\"articles\"][number]\n\n/** The catalog retrieval picks from: every indexed article but old versions. */\nexport function catalogPool(store: WikiStore): CatalogEntry[] {\n try {\n return (store.rebuildIndex().articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n } catch {\n return []\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 pool: CatalogEntry[],\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n stage = \"catalog-selector\",\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\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 } },\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. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\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 bm25 = scoreAll(question, buildIndex(pool.map(catalogDoc)))\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 branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].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\n/** What BM25 sees of a catalog entry: the catalog carries no body. */\nfunction catalogDoc(a: { title: string; tags?: string[]; related?: string[] }): string {\n return [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \")\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: claudeCliEnv(), 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":"iNAAA,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,CACF,IAAMC,EAAU,MAAMC,EAAwBvB,EAAUwB,EAAYvB,CAAK,EAAGC,EAAaI,EAAeK,EAAaC,CAAW,EAC5HU,GACFF,EAAaE,EACbD,EAAiB,sBAAsBC,EAAQ,IAAKG,GAAMA,EAAE,KAAK,EAAE,KAAK,KAAK,MAE7EJ,EAAiB,MAAMK,EACrBC,EAAoB3B,EAAUiB,EAASX,EAAeK,CAAW,EACjEP,EACAK,CACF,EACAW,EAAaQ,EAAgBP,CAAc,EAE/C,OAASQ,EAAP,CACA,OAAAnB,EAAI,mBAAoBmB,GAAG,OAAO,EAC3B,CAAE,GAAGb,EAAY,QAAShB,EAAU,aAAa6B,GAAG,SAAW,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V,GAAWA,GAAK,OAAOA,EAAE,OAAU,UAAY,OAAOA,EAAE,MAAS,QAAQ,EACjF,IAAKA,IAAY,CAAE,MAAOA,EAAE,MAAO,KAAMA,EAAE,IAAK,EAAE,EAHlB,CAAC,CAItC,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAEA,eAAelD,EAAU6D,EAAgBC,EAAe/E,EAAoC,CAG1F,GAAM,CAAE,cAAAgF,EAAe,UAAAC,EAAW,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EACxD,CAAE,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EAC9BC,EAAMhG,EAAQ+F,EAAO,EAAG,qBAAqB,QAAQ,KAAK,EAChEF,EAAUG,EAAK,CAAE,UAAW,EAAK,CAAC,EAClC,IAAMC,EAAajG,EAAQgG,EAAK,UAAU,KAAK,IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMtF,EAASiG,EAAK,CAAE,IAAKC,EAAa,EAAG,SAAU,QAAS,QAASvF,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EACpH,GAAI,CACF,IAAMwF,EAAW,KAAK,MAAMb,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","catalogPool","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","retrieveArticles","pool","matched","scoreAll","buildIndex","catalogDoc","r","rankCatalogPool","i","status","_question","error","titleIndex","article","opened","frontier","next","target","path","stage","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","bm25","maxBm25","m","text","useGraph","branch","ancestryScore","byScore","x","y","branchOnly","ranked","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","claudeCliEnv","envelope"]}
|