wiki-plugin-similarity 0.18.0 → 0.19.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.
@@ -1,7 +1,9 @@
1
- /* wiki-plugin-similarity - 0.18.0 - Fri, 04 Sep 2026 07:13:10 GMT */
2
- (()=>{var V={high:.78,medium:.68,low:.58},G=V.medium,Q=10,K=t=>{let e=[],n=[],o=[],p=null,b=null,m="search",x=!1,C=!1,k=!1,R=null,T=null,v=(r,c)=>r===c||r.startsWith(c)&&/^[\s:]/.test(r.slice(c.length)),y=(r,c)=>r.slice(c.length).replace(/^\s*:?\s*/,"").trim();for(let r of t.split(`
3
- `)){let c=r.trim();if(!c||c.startsWith("#"))continue;let g=c.toUpperCase();if(v(g,"LIVE")){x=!0;continue}if(v(g,"SUBJECT")){C=!0;continue}if(v(g,"AUTHOR")){!e.length&&m==="search"&&(m="author");continue}if(v(g,"REPORT")){m==="search"&&(m="report");continue}if(v(g,"KEYWORD")){m==="search"&&(m="keyword");continue}if(v(g,"SITES")){m==="search"&&(m="sites");continue}if(v(g,"BUILD")){m==="search"&&(m="build");continue}if(v(g,"FORCE")){k=!0;continue}if(v(g,"GHOST")){R=y(c,"GHOST"),m==="search"&&(m="ghost");continue}if(v(g,"BUTTON")){T=y(c,"BUTTON");continue}if(v(g,"ROSTER")){let j=y(c,"ROSTER");j&&n.push(j);continue}if(v(g,"FARM")){let j=y(c,"FARM");j&&o.push(j);continue}if(v(g,"LIST")){!e.length&&m==="search"&&(m="list");continue}if(v(g,"STATUS")){m==="search"&&(m="status");continue}if(v(g,"SIMILAR")){let j=y(g,"SIMILAR").toLowerCase();p=V[j]||G,!e.length&&m==="search"&&(m="similar");continue}if(v(g,"THRESHOLD")){let j=y(c,"THRESHOLD");p=V[j.toLowerCase()]??(parseFloat(j)||G);continue}if(v(g,"LIMIT")){b=parseInt(y(c,"LIMIT"))||Q;continue}e.push(["PUBLIC","LOCAL","PRIVATE","GALAXY","SITE"].includes(g)?g:c)}return{mode:m,specs:e,rosterRefs:n,farms:o,threshold:p??G,limit:b??Q,live:x,subject:C,force:k,ghostUrl:R,label:T,thresholdSet:p!==null}},tt=t=>t.includes("*")||t.includes("?"),et=t=>t==="PUBLIC"||t==="LOCAL"||t==="PRIVATE"||t==="GALAXY";var st=t=>t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),J=new Map,yt=async(t,e)=>{if(J.has(t))return J.get(t);let n=`${e}/system/indexed-domains.json?pattern=${encodeURIComponent(t)}`,o=await fetch(n);if(!o.ok)throw new Error(`indexed-domains failed: ${o.status}`);let p=await o.json();return J.set(t,p),p},M=async(t,e)=>{t.length||(t=[window.location.hostname]);let n=new Set,o=[];for(let p of t)if(p==="*"||tt(p)||et(p))for(let b of await yt(p,e))n.has(b.domain)||(n.add(b.domain),o.push(b));else n.has(p)||(n.add(p),o.push({domain:p,page_count:null}));return o},xt=/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+|localhost)(:\d+)?$/,bt=/^ROSTER ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,vt=/^REFERENCES ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,nt=async t=>{let e=t.indexOf("/"),n=await fetch(`//${t.slice(0,e)}/${t.slice(e+1)}.json`);if(!n.ok)throw new Error(`roster page ${t} failed: ${n.status}`);return n.json()},ot=async(t,e,n)=>{if(n.has(t))return;n.add(t);let o;try{o=await nt(t)}catch(p){console.warn(p.message);return}for(let p of o.story||[])if(p.type==="roster")for(let b of(p.text||"").split(/\r?\n/)){let m=b.trim();if(!m)continue;let x=m.match(xt);if(x){e.add(x[0]);continue}let C=m.match(bt);if(C){await ot(C[1],e,n);continue}let k=m.match(vt);if(k)try{let R=await nt(k[1]);for(let T of R.story||[])T.type==="reference"&&T.site&&e.add(T.site)}catch(R){console.warn(R.message)}}},St=async t=>{let e=new Set,n=new Set;for(let o of t)await ot(o,e,n);return[...e]},it=async(t,e)=>{let n=typeof window<"u"&&window.location?window.location.hostname:null,o=t.map(p=>p.toUpperCase()==="SITE"&&n?n:p);return e.length?[...o,...await St(e)]:o};var W=new Map,kt=t=>`${window.location.origin}/system/semantic-vectors.json?domain=${encodeURIComponent(t)}`,at=async t=>{if(W.has(t))return W.get(t);let e=await fetch(kt(t));if(!e.ok)return[];let n=await e.json();return W.set(t,n),n},q=async(t,e)=>{let n=await fetch(`${e}/system/embed.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t})});if(!n.ok)throw new Error(`embed failed: ${n.status}`);return(await n.json()).vector},rt=async(t,e)=>{let o=(await at(e)).find(p=>p.slug===t);return o?o.vector:null},N=(t,e,{threshold:n,limit:o,excludeSlug:p,excludeDomain:b})=>{let m=[];for(let{domain:x,pages:C}of e)for(let{slug:k,title:R,vector:T}of C){if(k===p&&x===b)continue;let v=0;for(let y=0;y<t.length;y++)v+=t[y]*T[y];v>=n&&m.push({domain:x,slug:k,title:R,score:v})}return m.sort((x,C)=>C.score-x.score),m.slice(0,o)},z=async(t,e)=>{let n=await M(t,e);return(await Promise.all(n.map(async({domain:p})=>({domain:p,pages:await at(p)})))).filter(p=>p.pages.length>0)};var lt=t=>{let e=t.parents(".page:first"),n=e.prev(".page"),o=n.length?n:e,p=(o.attr("id")||"").split("_rev")[0],b=o.data("site")||window.location.hostname,m=o.data("data")||{},x=m.title||o.find(".title").text().trim()||p,C=[x,...(m.story||[]).filter(k=>k.type==="markdown"||k.type==="paragraph").map(k=>(k.text||"").trim()).filter(Boolean)].join(`
4
- `).slice(0,2e3);return{slug:p,site:b,title:x,text:C,isSelf:!n.length}},D=t=>`Subject: ${t.title}${t.isSelf?" (this page)":` @ ${t.site}`}`;var ct=t=>`sim-cache-${t}`,dt=t=>{try{let e=JSON.parse(localStorage.getItem(ct(t.id))||"null");return e?.text===(t.text||"")?e:null}catch{return null}},A=(t,e)=>{try{localStorage.setItem(ct(t.id),JSON.stringify({text:t.text||"",ts:Date.now(),...e}))}catch{}},ut=t=>{let e=Math.floor((Date.now()-t)/1e3);return e<60?`${e}s ago`:e<3600?`${Math.floor(e/60)}m ago`:e<86400?`${Math.floor(e/3600)}h ago`:`${Math.floor(e/86400)}d ago`};var O=`
1
+ /* wiki-plugin-similarity - 0.19.0 - Fri, 04 Sep 2026 07:52:20 GMT */
2
+ (()=>{var lt={high:.78,medium:.68,low:.58},rt=lt.medium,$t=10,ct=t=>{let e=[],n=[],s=[],i=null,r=null,u="search",g=!1,k=!1,b=!1,M=null,R=null,A=null,U=null,w=(a,d)=>a===d||a.startsWith(d)&&/^[\s:]/.test(a.slice(d.length)),v=(a,d)=>a.slice(d.length).replace(/^\s*:?\s*/,"").trim();for(let a of t.split(`
3
+ `)){let d=a.trim();if(!d||d.startsWith("#"))continue;let y=d.toUpperCase();if(w(y,"LIVE")){g=!0;continue}if(w(y,"SUBJECT")){k=!0;continue}if(w(y,"AUTHOR")){!e.length&&u==="search"&&(u="author");continue}if(w(y,"REPORT")){u==="search"&&(u="report");continue}if(w(y,"KEYWORD")){u==="search"&&(u="keyword");continue}if(w(y,"SITES")){u==="search"&&(u="sites");continue}if(w(y,"BUILD")){u==="search"&&(u="build");continue}if(w(y,"FORCE")){b=!0;continue}if(w(y,"GHOST")){M=v(d,"GHOST"),u==="search"&&(u="ghost");continue}if(w(y,"BUTTON")){R=v(d,"BUTTON");continue}if(w(y,"BATCH")){let C=v(d,"BATCH").toLowerCase();A=C==="off"||C==="no"||C==="0"?0:parseInt(C)||50;continue}if(w(y,"ALGORITHM")){U=v(d,"ALGORITHM").replace(/^\[\[|\]\]$/g,"").trim()||"search-algorithm",u==="search"&&!e.length&&(u="algorithm");continue}if(w(y,"ROSTER")){let C=v(d,"ROSTER");C&&n.push(C);continue}if(w(y,"FARM")){let C=v(d,"FARM");C&&s.push(C);continue}if(w(y,"LIST")){!e.length&&u==="search"&&(u="list");continue}if(w(y,"STATUS")){u==="search"&&(u="status");continue}if(w(y,"SIMILAR")){let C=v(y,"SIMILAR").toLowerCase();i=lt[C]||rt,!e.length&&u==="search"&&(u="similar");continue}if(w(y,"THRESHOLD")){let C=v(d,"THRESHOLD");i=lt[C.toLowerCase()]??(parseFloat(C)||rt);continue}if(w(y,"LIMIT")){r=parseInt(v(d,"LIMIT"))||$t;continue}e.push(["PUBLIC","LOCAL","PRIVATE","GALAXY","SITE"].includes(y)?y:d)}return{mode:u,specs:e,rosterRefs:n,farms:s,threshold:i??rt,limit:r??$t,live:g,subject:k,force:b,ghostUrl:M,label:R,batch:A,algorithm:U,thresholdSet:i!==null}},W=t=>t.includes("*")||t.includes("?"),Z=t=>t==="PUBLIC"||t==="LOCAL"||t==="PRIVATE"||t==="GALAXY";var bt=t=>t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),dt=new Map,Wt=async(t,e)=>{if(dt.has(t))return dt.get(t);let n=`${e}/system/indexed-domains.json?pattern=${encodeURIComponent(t)}`,s=await fetch(n);if(!s.ok)throw new Error(`indexed-domains failed: ${s.status}`);let i=await s.json();return dt.set(t,i),i},K=async(t,e)=>{t.length||(t=[window.location.hostname]);let n=new Set,s=[];for(let i of t)if(i==="*"||W(i)||Z(i))for(let r of await Wt(i,e))n.has(r.domain)||(n.add(r.domain),s.push(r));else n.has(i)||(n.add(i),s.push({domain:i,page_count:null}));return s},Zt=/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+|localhost)(:\d+)?$/,Xt=/^ROSTER ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,Qt=/^REFERENCES ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,yt=async t=>{let e=t.indexOf("/"),n=await fetch(`//${t.slice(0,e)}/${t.slice(e+1)}.json`);if(!n.ok)throw new Error(`roster page ${t} failed: ${n.status}`);return n.json()},xt=async(t,e,n)=>{if(n.has(t))return;n.add(t);let s;try{s=await yt(t)}catch(i){console.warn(i.message);return}for(let i of s.story||[])if(i.type==="roster")for(let r of(i.text||"").split(/\r?\n/)){let u=r.trim();if(!u)continue;let g=u.match(Zt);if(g){e.add(g[0]);continue}let k=u.match(Xt);if(k){await xt(k[1],e,n);continue}let b=u.match(Qt);if(b)try{let M=await yt(b[1]);for(let R of M.story||[])R.type==="reference"&&R.site&&e.add(R.site)}catch(M){console.warn(M.message)}}},te=async t=>{let e=new Set,n=new Set;for(let s of t)await xt(s,e,n);return[...e]},St=async(t,e)=>{let n=typeof window<"u"&&window.location?window.location.hostname:null,s=t.map(i=>i.toUpperCase()==="SITE"&&n?n:i);return e.length?[...s,...await te(e)]:s};var ut=new Map,ee=t=>`${window.location.origin}/system/semantic-vectors.json?domain=${encodeURIComponent(t)}`,vt=async t=>{if(ut.has(t))return ut.get(t);let e=await fetch(ee(t));if(!e.ok)return[];let n=await e.json();return ut.set(t,n),n},X=async(t,e)=>{let n=await fetch(`${e}/system/embed.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t})});if(!n.ok)throw new Error(`embed failed: ${n.status}`);return(await n.json()).vector},kt=async(t,e)=>{let s=(await vt(e)).find(i=>i.slug===t);return s?s.vector:null},Q=(t,e,{threshold:n,limit:s,excludeSlug:i,excludeDomain:r})=>{let u=[];for(let{domain:g,pages:k}of e)for(let{slug:b,title:M,vector:R}of k){if(b===i&&g===r)continue;let A=0;for(let U=0;U<t.length;U++)A+=t[U]*R[U];A>=n&&u.push({domain:g,slug:b,title:M,score:A})}return u.sort((g,k)=>k.score-g.score),u.slice(0,s)},tt=async(t,e)=>{let n=await K(t,e);return(await Promise.all(n.map(async({domain:i})=>({domain:i,pages:await vt(i)})))).filter(i=>i.pages.length>0)};var Lt=t=>{let e=t.parents(".page:first"),n=e.prev(".page"),s=n.length?n:e,i=(s.attr("id")||"").split("_rev")[0],r=s.data("site")||window.location.hostname,u=s.data("data")||{},g=u.title||s.find(".title").text().trim()||i,k=[g,...(u.story||[]).filter(b=>b.type==="markdown"||b.type==="paragraph").map(b=>(b.text||"").trim()).filter(Boolean)].join(`
4
+ `).slice(0,2e3);return{slug:i,site:r,title:g,text:k,isSelf:!n.length}},B=t=>`Subject: ${t.title}${t.isSelf?" (this page)":` @ ${t.site}`}`;var Et=t=>`sim-cache-${t}`,jt=t=>{try{let e=JSON.parse(localStorage.getItem(Et(t.id))||"null");return e?.text===(t.text||"")?e:null}catch{return null}},Y=(t,e)=>{try{localStorage.setItem(Et(t.id),JSON.stringify({text:t.text||"",ts:Date.now(),...e}))}catch{}},Ct=t=>{let e=Math.floor((Date.now()-t)/1e3);return e<60?`${e}s ago`:e<3600?`${Math.floor(e/60)}m ago`:e<86400?`${Math.floor(e/3600)}h ago`:`${Math.floor(e/86400)}d ago`};var ne=()=>{let t=new Set;try{for(let e of Object.keys(window.wiki?.neighborhood||{}))t.add(e);document.querySelectorAll(".page").forEach(e=>{let n=window.$?window.$(e).data("site"):null;t.add(n||window.location.hostname)})}catch{}return[...t]},Tt=async(t,e)=>{let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let s=new Error(`${t.split("/").pop()} failed: ${n.status}`);throw s.status=n.status,s.body=await n.json().catch(()=>({})),s}return n.json()},se=(t,e,n)=>{let s=t.slice(0,n).map(r=>`${r.site} ${r.slug}`).join("|"),i=e.slice(0,n).map(r=>`${r.site} ${r.slug}`).join("|");return s===i},It=async t=>{let{origin:e,query:n,seeded:s={},specs:i,limit:r,batch:u,algorithm:g,render:k}=t,b=q=>t.status&&t.status(q),M={roster:[...t.roster||[],...g&&g.liked||[]],neighborhood:ne(),followed:!0,...t.prefer||{}};b("Ranking sites\u2026");let R=await Tt(`${e}/system/site-rank.json`,{query:n,...s,domains:i,prefer:M,algorithm:g||{},batch:u||50}),A=R.batches||[],w={searched:0,total:R.count||A.reduce((q,F)=>q+F.length,0),batches:A.length,done:0,stopped:!1,converged:!1,running:!0,unindexed:R.unindexed||[]},v=new Map,a=[],d=0,y=()=>{w.stopped=!0};w.stop=y;let C=async q=>{let F={query:n,...s,domains:q,limit:Math.max(r*3,30),flat:!0};t.thresholdSet&&(F.threshold=t.threshold);let m=await Tt(`${e}/system/search-report.json`,F);for(let h of m.results||[]){let l=`${h.site} ${h.slug}`,o=v.get(l);(!o||o.score<h.score)&&v.set(l,h)}let p=[...v.values()].sort((h,l)=>l.score-h.score),c=se(a,p,r);a=p,w.searched+=q.length,w.done+=1,d=c?d+1:0},V=()=>A.slice(w.done),_=async(q=!1)=>{for(w.running=!0,w.stopped=!1;w.done<A.length&&!w.stopped;)if(await C(A[w.done]),k(a,w),!q&&d>=3&&w.done<A.length){w.converged=!0;break}return w.running=!1,k(a,w),a};return w.continueAll=()=>(w.converged=!1,d=-1/0,_(!0)),await _(!1),{results:a,state:w,remaining:V}};var nt="similarity:learned",oe=new Set(["liked","visited","neighbourhood","neighborhood","followed","centroid","fresh"]),et=/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+|localhost)(:\d+)?$/,ht=t=>{let e={weights:{},always:[],never:[],batch:null};for(let n of(t||"").split(`
5
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let[i,...r]=s.split(/\s+/),u=i.toUpperCase().replace(/:$/,"");if(u==="WEIGHT"&&r.length>=2){let g=r[0].toLowerCase().replace("neighborhood","neighbourhood"),k=parseFloat(r[1]);oe.has(g)&&Number.isFinite(k)&&(e.weights[g]=k)}else u==="ALWAYS"&&r[0]&&et.test(r[0])?e.always.push(r[0].toLowerCase()):u==="NEVER"&&r[0]&&et.test(r[0])?e.never.push(r[0].toLowerCase()):u==="BATCH"&&r[0]&&(e.batch=parseInt(r[0])||null)}return e},mt=()=>{try{let t=JSON.parse(localStorage.getItem(nt)||"{}"),e={};for(let[n,s]of Object.entries(t.sites||t)){let i=typeof s=="number"?s:s&&typeof s.score=="number"?s.score:0;i>0&&(e[n.toLowerCase()]=Math.min(1,i))}return e}catch{return{}}},ie=(t,e)=>{if(!t)return`${e}/search-algorithm.json`;let n=t.indexOf("/");if(n>0&&et.test(t.slice(0,n)))return`//${t.slice(0,n)}/${t.slice(n+1)}.json`;let s=t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"");return`${e}/${s}.json`},ae=t=>{let e=new Set;for(let n of t.story||[])if(n.type==="roster")for(let s of(n.text||"").split(/\r?\n/)){let i=s.trim();et.test(i)&&e.add(i.toLowerCase())}return[...e]},Rt=new Map,At=async(t,e)=>{let n=ie(t,e),s=Rt.get(n);if(!s){s={weights:{},always:[],never:[],liked:[],batch:null,page:null};try{let i=await fetch(n);if(i.ok){let r=await i.json(),u=(r.story||[]).find(g=>g.type==="similarity"&&/^\s*ALGORITHM\b/im.test(g.text||""));u&&Object.assign(s,ht(u.text)),s.liked=ae(r),s.page={url:n,title:r.title}}}catch{}Rt.set(n,s)}return{...s,learned:mt()}};var re={neighbourhood:.1,visited:.2,clicked:.35},le=7*864e5,Ot=200,Pt=()=>{try{return JSON.parse(localStorage.getItem(nt)||"{}").sites||{}}catch{return{}}},Ut=t=>{try{localStorage.setItem(nt,JSON.stringify({sites:t,savedAt:Date.now()}))}catch{}},st=(t,e)=>{let n=Math.max(0,(e-(t.at||e))/le);return(t.score||0)*Math.pow(.5,n)},ot=(t,e)=>{if(!t||t==="localhost")return 0;let n=t.toLowerCase(),s=Date.now(),i=Pt(),r=i[n]?st(i[n],s):0,u=Math.min(1,r+(re[e]||.1));i[n]={score:u,at:s};let g=Object.keys(i);if(g.length>Ot){g.sort((k,b)=>st(i[b],s)-st(i[k],s));for(let k of g.slice(Ot))delete i[k]}return Ut(i),u},ce=()=>{let t=Date.now();return Object.entries(Pt()).map(([e,n])=>[e,st(n,t)]).filter(([,e])=>e>.01).sort((e,n)=>n[1]-e[1])},Ht=()=>Ut({}),Mt=!1,Dt=t=>{try{return window.$&&window.$(t).data("site")||window.location.hostname}catch{return window.location.hostname}},qt=()=>{if(Mt||typeof document>"u")return;Mt=!0;let t=new Set;document.querySelectorAll(".main > .page").forEach(n=>{let s=Dt(n);t.has(s)||(t.add(s),ot(s,"neighbourhood"))});let e=document.querySelector(".main");!e||typeof MutationObserver>"u"||new MutationObserver(n=>{for(let s of n)for(let i of s.addedNodes)i.nodeType===1&&i.classList.contains("page")&&!i.classList.contains("ghost")&&ot(Dt(i),"visited")}).observe(e,{childList:!0})},Nt=(t,e=20)=>new Promise((n,s)=>{let r=((t.data("data")||{}).story||[]).find(b=>b.type==="roster"&&/^\s*sites i visit\b/i.test(b.text||""));if(!r)return s(new Error('no "Sites I visit" roster on this page'));let u=ce().slice(0,e);if(!u.length)return s(new Error("nothing learned yet"));let g=["Sites I visit",...u.map(([b])=>b)].join(`
6
+ `),k={...r,text:g};try{window.wiki.pageHandler.put(t,{type:"edit",id:r.id,item:k});let b=t.find(`.item[data-id="${r.id}"]`);b.length&&(b.data("item",k),window.wiki.plugins?.roster?.emit?.(b,k)),n(u.length)}catch(b){s(b)}});var N=`
5
7
  .sim-form { display:flex; gap:6px; margin-bottom:8px; }
6
8
  .sim-input { flex:1; padding:6px 8px; font-size:14px; border:1px solid #ccc; border-radius:3px; }
7
9
  .sim-btn { padding:6px 14px; background:#c4561d; color:white; border:none;
@@ -25,81 +27,96 @@
25
27
  .sim-list td { padding:3px 8px 3px 0; border-bottom:1px solid #f0f0f0; vertical-align:middle; }
26
28
  .sim-list td:last-child { text-align:right; color:#999; font-size:11px; }
27
29
  .sim-list .sim-flag { margin-right:6px; }
28
- `,ft=(t,e)=>`<img class="sim-flag remote" src="${window.wiki.site(t).flag()}"
30
+ `,Ft=(t,e)=>`<img class="sim-flag remote" src="${window.wiki.site(t).flag()}"
29
31
  title="${t} \u2014 score ${e.toFixed(3)}"
30
- data-site="${t}">`;var Et="Search Tool",Lt="search-tool",F=null,jt=()=>fetch(`/${Lt}.json`,{method:"GET"}).then(t=>{F=t.ok}).catch(()=>{F=!1}),Ct=t=>{let e=window.$(t).parents(".page");return e.length?e:null},mt=(t,e)=>{window.wiki.doInternalLink(Et,e?null:t)},pt=()=>{typeof document>"u"||!window.wiki||!window.$||(jt(),document.addEventListener("click",t=>{if(F!==!0)return;let e=t.target&&t.target.closest&&t.target.closest("a.search");if(!e)return;let n=Ct(e);n&&(t.preventDefault(),t.stopPropagation(),mt(n,t.shiftKey))},!0),document.addEventListener("keydown",t=>{if(F!==!0||t.key!=="Enter")return;let e=t.target;if(!e||!e.classList||!e.classList.contains("search")||!e.closest(".searchbox"))return;let n=(e.value||"").trim();n&&(t.preventDefault(),t.stopPropagation(),window.$(".incremental-search").remove(),e.value="",Tt(n),mt(window.$(".page").last(),!1))},!0))},Y=null,Tt=t=>{Y=t},ht=()=>{let t=Y;return Y=null,t};var Z=(t,e,n,o)=>`<a class="sim-link" data-title="${n}" data-slug="${e}" data-site="${t}" href="#">${ft(t,o)} ${n}</a>`,Rt=(t,e)=>{let{mode:n,specs:o,threshold:p,limit:b,force:m,ghostUrl:x,label:C}=K(e?.text||"");if(n==="ghost")t.html(`
31
- <style>${O}</style>
32
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
32
+ data-site="${t}">`;var de="Search Tool",ue="search-tool",it=null,he=()=>fetch(`/${ue}.json`,{method:"GET"}).then(t=>{it=t.ok}).catch(()=>{it=!1}),me=t=>{let e=window.$(t).parents(".page");return e.length?e:null},Bt=(t,e)=>{window.wiki.doInternalLink(de,e?null:t)},_t=()=>{typeof document>"u"||!window.wiki||!window.$||(he(),document.addEventListener("click",t=>{if(it!==!0)return;let e=t.target&&t.target.closest&&t.target.closest("a.search");if(!e)return;let n=me(e);n&&(t.preventDefault(),t.stopPropagation(),Bt(n,t.shiftKey))},!0),document.addEventListener("keydown",t=>{if(it!==!0||t.key!=="Enter")return;let e=t.target;if(!e||!e.classList||!e.classList.contains("search")||!e.closest(".searchbox"))return;let n=(e.value||"").trim();n&&(t.preventDefault(),t.stopPropagation(),window.$(".incremental-search").remove(),e.value="",fe(n),Bt(window.$(".page").last(),!1))},!0))},ft=null,fe=t=>{ft=t},zt=()=>{let t=ft;return ft=null,t};var at=(t,e,n,s)=>`<a class="sim-link" data-title="${n}" data-slug="${e}" data-site="${t}" href="#">${Ft(t,s)} ${n}</a>`,pe=(t,e)=>{let n=()=>Math.random().toString(16).slice(2,18).padEnd(16,"0"),s=[{type:"markdown",id:n(),text:`Federated search for **${t}** \u2014 ${e.length} results, searched a batch at a time, nearest sites first.`}],i=[...new Set(e.map(r=>r.title))];i.length&&s.push({type:"markdown",id:n(),text:i.map(r=>`- [[${r}]]`).join(`
33
+ `)}),s.push({type:"markdown",id:n(),text:"# Results"});for(let r of e)s.push({type:"reference",id:n(),site:r.site,slug:r.slug,title:r.title,text:r.synopsis||`score ${r.score}`});return{title:`${t} Federated Search`,story:s}},ge=(t,e)=>{let{mode:n,specs:s,threshold:i,limit:r,force:u,ghostUrl:g,label:k}=ct(e?.text||"");if(n==="ghost")t.html(`
34
+ <style>${N}</style>
35
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
33
36
  <div class="sim-form">
34
- <button class="sim-btn">${C||"Open"}</button>
37
+ <button class="sim-btn">${k||"Open"}</button>
35
38
  </div>
36
39
  <div class="sim-status"></div>
37
40
  </div>`);else if(n==="build")t.html(`
38
- <style>${O}</style>
39
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
41
+ <style>${N}</style>
42
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
40
43
  <div class="sim-form">
41
- <button class="sim-btn">${C||`Index ${o.length?o.join(", "):"*"}${m?" (force)":""}`}</button>
44
+ <button class="sim-btn">${k||`Index ${s.length?s.join(", "):"*"}${u?" (force)":""}`}</button>
42
45
  </div>
43
46
  <div class="sim-status"></div>
44
- </div>`);else if(n==="list"){let k=o.length?o.join(", "):"*";t.html(`
45
- <style>${O}</style>
46
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
47
- <div class="sim-status">Loading indexed domains (${k})\u2026</div>
47
+ </div>`);else if(n==="list"){let b=s.length?s.join(", "):"*";t.html(`
48
+ <style>${N}</style>
49
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
50
+ <div class="sim-status">Loading indexed domains (${b})\u2026</div>
48
51
  <div class="sim-list"></div>
49
- </div>`)}else if(n==="status")t.html(`
50
- <style>${O}</style>
51
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
52
+ </div>`)}else if(n==="algorithm")t.html(`
53
+ <style>${N}</style>
54
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="">
55
+ <div class="sim-status">Reading this search algorithm\u2026</div>
56
+ <div class="sim-list"></div>
57
+ </div>`);else if(n==="status")t.html(`
58
+ <style>${N}</style>
59
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
52
60
  <div class="sim-status">Reading the state of the index\u2026</div>
53
61
  <div class="sim-list"></div>
54
- </div>`);else if(n==="similar"){let k=o.length?o.join(", "):"current domain";t.html(`
55
- <style>${O}</style>
56
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
57
- <div class="sim-status">Finding similar pages across ${k}\u2026</div>
62
+ </div>`);else if(n==="similar"){let b=s.length?s.join(", "):"current domain";t.html(`
63
+ <style>${N}</style>
64
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
65
+ <div class="sim-status">Finding similar pages across ${b}\u2026</div>
58
66
  <div class="sim-results"></div>
59
- </div>`)}else if(n==="author"||n==="report"||n==="keyword"||n==="sites"){let k=o.length?o.join(", "):"(current domain)",R=n==="report"?"Report":n==="keyword"?"Keyword":n==="sites"?"Sites":"Author",T=n==="sites"?"Where should this page go? Title + first paragraph\u2026":"Search wiki pages\u2026";t.html(`
60
- <style>${O}</style>
61
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
67
+ </div>`)}else if(n==="author"||n==="report"||n==="keyword"||n==="sites"){let b=s.length?s.join(", "):"(current domain)",M=n==="report"?"Report":n==="keyword"?"Keyword":n==="sites"?"Sites":"Author",R=n==="sites"?"Where should this page go? Title + first paragraph\u2026":"Search wiki pages\u2026";t.html(`
68
+ <style>${N}</style>
69
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
62
70
  <div class="sim-form">
63
- <input class="sim-input" type="text" placeholder="${T}" />
64
- <button class="sim-btn">${R}</button>
71
+ <input class="sim-input" type="text" placeholder="${R}" />
72
+ <button class="sim-btn">${M}</button>
65
73
  </div>
66
- <div class="sim-status">Domains: ${k}</div>
74
+ <div class="sim-status">Domains: ${b}</div>
67
75
  <div class="sim-results"></div>
68
- </div>`)}else{let k=o.length?o.join(", "):"(current domain)";t.html(`
69
- <style>${O}</style>
70
- <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${o.join(",")||""}">
76
+ </div>`)}else{let b=s.length?s.join(", "):"(current domain)";t.html(`
77
+ <style>${N}</style>
78
+ <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
71
79
  <div class="sim-form">
72
80
  <input class="sim-input" type="text" placeholder="Search wiki pages\u2026" />
73
81
  <button class="sim-btn">Search</button>
74
82
  </div>
75
- <div class="sim-status">Domains: ${k}</div>
83
+ <div class="sim-status">Domains: ${b}</div>
76
84
  <div class="sim-results"></div>
77
- </div>`)}},It=(t,e)=>{let{mode:n,specs:o,rosterRefs:p,farms:b,threshold:m,limit:x,live:C,subject:k,force:R,ghostUrl:T,thresholdSet:v}=K(e?.text||""),y=window.location.origin,r=t.find(".sim-status")[0],c=k?lt(t):null,g=C||c?null:dt(e),j=it(o,p),X=()=>c?{seed:{site:c.site,slug:c.slug},text:c.text,excludePage:{site:c.site,slug:c.slug}}:{},U=(d,h,i)=>{let u=h>0?`${h.toLocaleString()} pages across ${i} domains`:`${i} domain${i===1?"":"s"}`,l=[`${d} \u2014 ${u}`];return v&&l.push(`threshold ${m}`),l.push(`limit ${x}`),C&&l.push("LIVE"),l.join(" \xB7 ")};t.on("dblclick",d=>{$(d.target).closest(".sim-input").length||window.wiki.textEditor(t,e)}),t.on("click",".sim-link",function(d){d.preventDefault();let h=$(this),i=d.shiftKey?null:t.parents(".page");window.wiki.doInternalLink(h.data("title"),i,h.data("site"))});let gt=!o.length||o.length===1&&o[0]==="*"?"on farm":o.length===1?`on ${o[0]}`:"in domains",B=d=>d?` \xB7 cached ${ut(d)}`:"";if(n==="status"){let d=t.find(".sim-list")[0],h=l=>{if(!l)return"unknown";let s=(Date.now()-new Date(l))/864e5;return s<1?"today":s<2?"yesterday":`${Math.floor(s)} days ago`},i=l=>l?new Date(l).toISOString().slice(0,10):"\u2014",u=l=>{if(!l||!l.warm)return"";let s=l.warm,a=Math.round((l.bytes||0)/1e6),f=s.state==="warm"?`warm \u2014 ${s.done.toLocaleString()} sites resident in ${Math.round(s.ms/1e3)} s`:s.state==="warming"?`warming \u2014 ${s.done.toLocaleString()} of ${s.total.toLocaleString()} sites so far`:"not warmed",w=s.capped?" \xB7 <strong>cap reached</strong>, some sites re-parse per query":"";return`<tr><th>Vector store</th><td>${(l.pages||0).toLocaleString()} pages \xB7 ${a} MB of ${Math.round((l.capBytes||0)/1e6)} MB \xB7 ${f}${w}</td></tr>`};(async()=>{try{let l=()=>fetch(`${y}/system/embed.json?text=ping`).then(async S=>S.ok?{ok:!0}:{ok:!1,detail:((await S.json().catch(()=>({}))).error||`status ${S.status}`).replace(/^embedding unavailable: /,"")}).catch(S=>({ok:!1,detail:S.message})),[s,a,f]=await Promise.all([fetch(`${y}/system/similarity-health.json`).then(S=>S.json()),fetch(`${y}/system/indexed-domains.json`).then(S=>S.ok?S.json():[]),l()]),w=s.embedder||{},E=a.map(S=>S.built).filter(Boolean).sort(),L=a.reduce((S,_)=>S+(_.page_count||0),0),I=!f.ok,P=I?`<strong>Semantic search is down</strong> \u2014 a query cannot be turned into a vector right now (${f.detail}), so searches on this page will answer by keyword instead.`:"Semantic search is <strong>up</strong> \u2014 checked just now by embedding a word.",H=w.via==="url"?`delegated to <code>${w.url}</code> (from ${w.source||"config"})`:w.via==="semindex"?"in this process, via the SemIndex plugin":"in this process, in a supervised child";r.style.display="none",d.innerHTML=`<h3>The Index Behind These Answers</h3>
85
+ </div>`)}},we=(t,e)=>{let{mode:n,specs:s,rosterRefs:i,farms:r,threshold:u,limit:g,live:k,subject:b,force:M,ghostUrl:R,thresholdSet:A,batch:U,algorithm:w}=ct(e?.text||""),v=window.location.origin,a=t.find(".sim-status")[0];qt();let d=b?Lt(t):null,y=k||d?null:jt(e),C=St(s,i),V=()=>d?{seed:{site:d.site,slug:d.slug},text:d.text,excludePage:{site:d.site,slug:d.slug}}:{},_=(m,p,c)=>{let h=p>0?`${p.toLocaleString()} pages across ${c} domains`:`${c} domain${c===1?"":"s"}`,l=[`${m} \u2014 ${h}`];return A&&l.push(`threshold ${u}`),l.push(`limit ${g}`),k&&l.push("LIVE"),l.join(" \xB7 ")};t.on("dblclick",m=>{$(m.target).closest(".sim-input").length||window.wiki.textEditor(t,e)}),t.on("click",".sim-link",function(m){m.preventDefault();let p=$(this),c=m.shiftKey?null:t.parents(".page");window.wiki.doInternalLink(p.data("title"),c,p.data("site"))});let q=!s.length||s.length===1&&s[0]==="*"?"on farm":s.length===1?`on ${s[0]}`:"in domains",F=m=>m?` \xB7 cached ${Ct(m)}`:"";if(n==="status"){let m=t.find(".sim-list")[0],p=l=>{if(!l)return"unknown";let o=(Date.now()-new Date(l))/864e5;return o<1?"today":o<2?"yesterday":`${Math.floor(o)} days ago`},c=l=>l?new Date(l).toISOString().slice(0,10):"\u2014",h=l=>{if(!l||!l.warm)return"";let o=l.warm,f=Math.round((l.bytes||0)/1e6),S=o.state==="warm"?`warm \u2014 ${o.done.toLocaleString()} sites resident in ${Math.round(o.ms/1e3)} s`:o.state==="warming"?`warming \u2014 ${o.done.toLocaleString()} of ${o.total.toLocaleString()} sites so far`:"not warmed",L=o.capped?" \xB7 <strong>cap reached</strong>, some sites re-parse per query":"";return`<tr><th>Vector store</th><td>${(l.pages||0).toLocaleString()} pages \xB7 ${f} MB of ${Math.round((l.capBytes||0)/1e6)} MB \xB7 ${S}${L}</td></tr>`};(async()=>{try{let l=()=>fetch(`${v}/system/embed.json?text=ping`).then(async E=>E.ok?{ok:!0}:{ok:!1,detail:((await E.json().catch(()=>({}))).error||`status ${E.status}`).replace(/^embedding unavailable: /,"")}).catch(E=>({ok:!1,detail:E.message})),[o,f,S]=await Promise.all([fetch(`${v}/system/similarity-health.json`).then(E=>E.json()),fetch(`${v}/system/indexed-domains.json`).then(E=>E.ok?E.json():[]),l()]),L=o.embedder||{},x=f.map(E=>E.built).filter(Boolean).sort(),j=f.reduce((E,z)=>E+(z.page_count||0),0),D=!S.ok,P=D?`<strong>Semantic search is down</strong> \u2014 a query cannot be turned into a vector right now (${S.detail}), so searches on this page will answer by keyword instead.`:"Semantic search is <strong>up</strong> \u2014 checked just now by embedding a word.",I=L.via==="url"?`delegated to <code>${L.url}</code> (from ${L.source||"config"})`:L.via==="semindex"?"in this process, via the SemIndex plugin":"in this process, in a supervised child";a.style.display="none",m.innerHTML=`<h3>The Index Behind These Answers</h3>
78
86
  <p>${P}</p>
79
87
  <table>
80
- <tr><th>Model</th><td>${s.model||"\u2014"} \xB7 ${s.dim||"\u2014"} dimensions</td></tr>
81
- <tr><th>Embedder</th><td>${H}${I?" \u2014 <strong>currently down</strong>":""}</td></tr>
82
- <tr><th>Indexed</th><td>${a.length.toLocaleString()} domains \xB7 ${L.toLocaleString()} pages</td></tr>
83
- <tr><th>Newest page vectors</th><td>${i(E[E.length-1])} (${h(E[E.length-1])})</td></tr>
84
- <tr><th>Oldest page vectors</th><td>${i(E[0])} (${h(E[0])})</td></tr>
85
- <tr><th>Plugin</th><td>wiki-plugin-similarity ${s.version||"\u2014"}</td></tr>
86
- ${u(s.store)}
88
+ <tr><th>Model</th><td>${o.model||"\u2014"} \xB7 ${o.dim||"\u2014"} dimensions</td></tr>
89
+ <tr><th>Embedder</th><td>${I}${D?" \u2014 <strong>currently down</strong>":""}</td></tr>
90
+ <tr><th>Indexed</th><td>${f.length.toLocaleString()} domains \xB7 ${j.toLocaleString()} pages</td></tr>
91
+ <tr><th>Newest page vectors</th><td>${c(x[x.length-1])} (${p(x[x.length-1])})</td></tr>
92
+ <tr><th>Oldest page vectors</th><td>${c(x[0])} (${p(x[0])})</td></tr>
93
+ <tr><th>Plugin</th><td>wiki-plugin-similarity ${o.version||"\u2014"}</td></tr>
94
+ ${h(o.store)}
87
95
  </table>
88
96
  <p class="sim-count">A domain's vectors are only rebuilt when its pages change, so an old
89
97
  date means a quiet site, not a broken one. Pages saved since the last build are findable
90
- by keyword but not yet by meaning.</p>`}catch(l){r.textContent=`Index state unavailable: ${l.message}`}})()}else if(n==="list"){let d=t.find(".sim-list")[0],h=(i,u)=>{let l=i.reduce((s,a)=>s+(a.page_count||0),0);r.style.display="none",d.innerHTML=`<h3>Indexed Farm Domains</h3>
98
+ by keyword but not yet by meaning.</p>`}catch(l){a.textContent=`Index state unavailable: ${l.message}`}})()}else if(n==="algorithm")setTimeout(()=>{let m=t.find(".sim-list")[0];try{let p=ht(e.text||""),c=mt(),h=Object.entries(c).sort((o,f)=>f[1]-o[1]).slice(0,8);a.style.display="none",m.innerHTML=`<h3>This Search Algorithm</h3>
99
+ <table>
100
+ ${Object.entries(p.weights).map(([o,f])=>`<tr><th>weight ${o}</th><td>${f}</td></tr>`).join("")}
101
+ <tr><th>always</th><td>${p.always.length?p.always.join(", "):"\u2014"}</td></tr>
102
+ <tr><th>never</th><td>${p.never.length?p.never.join(", "):"\u2014"}</td></tr>
103
+ <tr><th>batch</th><td>${p.batch||50}</td></tr>
104
+ </table>
105
+ <p class="sim-count">Learned in this browser: ${h.length?h.map(([o,f])=>`${o} (${f.toFixed(2)})`).join(", "):"nothing yet \u2014 sites you are near, open and click will appear here"}</p>
106
+ <p class="sim-count"><button class="sim-remember">Remember</button> <button class="sim-forget">Forget</button>
107
+ <span class="sim-remember-note"></span></p>`;let l=m.querySelector(".sim-remember-note");m.querySelector(".sim-remember").addEventListener("click",async()=>{try{let o=await Nt(t.parents(".page"));l.textContent=`${o} sites written into "Sites I visit" \u2014 read the roster above, delete any line.`}catch(o){l.textContent=`Could not remember here: ${o.message}`}}),m.querySelector(".sim-forget").addEventListener("click",()=>{Ht(),l.textContent="Forgotten \u2014 the browser starts learning again from here."})}catch(p){a.textContent=`Algorithm unreadable: ${p.message}`}},0);else if(n==="list"){let m=t.find(".sim-list")[0],p=(c,h)=>{let l=c.reduce((o,f)=>o+(f.page_count||0),0);a.style.display="none",m.innerHTML=`<h3>Indexed Farm Domains</h3>
91
108
  <table>
92
109
  <tr><th>Domain</th><th>Pages</th></tr>
93
- ${i.map(({domain:s,page_count:a})=>`
110
+ ${c.map(({domain:o,page_count:f})=>`
94
111
  <tr>
95
- <td><img class="sim-flag remote" src="${window.wiki.site(s).flag()}"
96
- title="${s}" data-site="${s}"> ${s}</td>
97
- <td>${a!=null?a.toLocaleString():"\u2014"}</td>
112
+ <td><img class="sim-flag remote" src="${window.wiki.site(o).flag()}"
113
+ title="${o}" data-site="${o}"> ${o}</td>
114
+ <td>${f!=null?f.toLocaleString():"\u2014"}</td>
98
115
  </tr>`).join("")}
99
116
  </table>
100
- <p class="sim-count">${i.length} domains \u2014 ${l.toLocaleString()} pages${B(u)}</p>`};g?.domains?h(g.domains,g.ts):(async()=>{try{let i=await j,u=i.length?i.join(","):"*",l=`${y}/system/indexed-domains.json?pattern=${encodeURIComponent(u)}&limit=${x}`,s=await fetch(l);if(!s.ok)throw new Error(`indexed-domains failed: ${s.status}`);let a=await s.json();if(!a.length){r.textContent="No indexed domains found";return}h(a,null),A(e,{domains:a})}catch(i){r.textContent=`Error: ${i.message}`}})()}else if(n==="similar"){let d=t.find(".sim-results")[0],h=(i,u)=>{if(!i.length){r.textContent=`No similar pages found above threshold ${m}`;return}d.innerHTML=`<h3>Similar Pages</h3><ul>${i.map(({domain:l,slug:s,title:a,score:f})=>`<li>${Z(l,s,a,f)}</li>`).join("")}</ul><p class="sim-count">${i.length} found ${gt}${B(u)}</p>`,r.style.display="none"};g?.scored?h(g.scored,g.ts):(async()=>{try{let i=t.parents(".page"),u=c||(()=>{let w=i.find(".title").text().trim()||document.title;return{slug:st(w),site:window.location.hostname,title:w,text:null,isSelf:!0}})(),l=await z(await j,y),s=l.reduce((w,E)=>w+E.pages.length,0);r.textContent=(c?`${D(u)} \xB7 `:"")+`Searching ${s.toLocaleString()} pages\u2026`;let a=await rt(u.slug,u.site);if(!a){r.textContent="Embedding page (not yet indexed)\u2026";let w=u.text||i.find(".item").map((E,L)=>$(L).text().trim()).get().filter(Boolean).join(`
101
- `);a=await q(w||u.title,y)}let f=N(a,l,{threshold:m,limit:x,excludeSlug:u.slug,excludeDomain:u.site});h(f,null),c&&(r.textContent=D(u),r.style.display=""),f.length&&!c&&A(e,{scored:f})}catch(i){r.textContent=`Error: ${i.message}`}})()}else if(n==="ghost"){let d=t.find(".sim-btn")[0],h=async()=>{if(!T){r.textContent="No URL \u2014 GHOST needs a page-json URL";return}d.disabled=!0,r.textContent="Fetching\u2026";try{let i=await fetch(T);if(!i.ok)throw new Error(`fetch failed: ${i.status}`);let u=await i.json();window.wiki.showResult(window.wiki.newPage(u),{$page:t.parents(".page")}),r.textContent=""}catch(i){r.textContent=`Error: ${i.message}`}finally{d.disabled=!1}};d.addEventListener("click",h)}else if(n==="build"){let d=t.find(".sim-btn")[0],h=async()=>{d.disabled=!0,r.textContent="Building index\u2026 (may take a while for large scopes)";try{let i=encodeURIComponent((o.length?o:["*"]).join(",")),u=await fetch(`${y}/system/build-index.json?domains=${i}&force=${R?1:0}`);if(u.status===501){let s=await u.json().catch(()=>({}));throw new Error(s.hint||"indexing runs on the farm indexer, not this server")}if(!u.ok)throw new Error(`build-index failed: ${u.status}`);let l=await u.json();window.wiki.showResult(window.wiki.newPage(l),{$page:t.parents(".page")}),r.textContent=""}catch(i){r.textContent=`Error: ${i.message}`}finally{d.disabled=!1}};d.addEventListener("click",h)}else if(n==="report"){let d=t.find(".sim-input")[0],h=t.find(".sim-btn")[0],i=`Domains: ${o.length?o.join(", "):"*"}`;c&&!d.value&&(d.value=c.title),(async()=>{try{let a=await j,f=await M(a.length?a:["*"],y),w=f.reduce((E,L)=>E+(L.page_count||0),0);i=U("Report ready",w,f.length),b.length&&(i+=` \xB7 +${b.length} peer farm${b.length>1?"s":""}`),c&&(i=`${D(c)} \xB7 ${i}`),r.textContent=i}catch(a){r.textContent=`Domain listing unavailable: ${a.message}`}})();let u=new Set([502,503]),l=async(a,f)=>{let w=encodeURIComponent((f.length?f:["*"]).join(",")),E=b.length?`&farms=${encodeURIComponent(b.join(","))}`:"",L=await fetch(`${y}/system/farm-search.json?q=${encodeURIComponent(a)}&pattern=${w}&limit=${x}${E}`);if(!L.ok)throw new Error(`keyword search also failed: ${L.status}`);let I=await L.json();window.wiki.showResult(window.wiki.newPage(I),{$page:t.parents(".page")})},s=async()=>{let a=d.value.trim();if(a){h.disabled=!0,r.textContent=b.length?"Generating report (asking peer farms)\u2026":"Generating report\u2026";try{let f=await j,w=c&&a===c.title?X():{},E={query:a,domains:f.length?f:["*"],limit:x,live:C,...w};b.length&&(E.farms=b),v&&(E.threshold=m);let L=await fetch(`${y}/system/search-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(u.has(L.status)){let S=((await L.json().catch(()=>({}))).error||`status ${L.status}`).replace(/^embedding unavailable: /,"");r.textContent="Semantic search unavailable \u2014 searching by keyword instead\u2026",await l(a,f),r.textContent=`Semantic search unavailable (${S}) \u2014 these are keyword matches, ranked by word not meaning.`;return}if(!L.ok)throw new Error(`search-report failed: ${L.status}`);let I=await L.json(),P=window.wiki.newPage(I);window.wiki.showResult(P,{$page:t.parents(".page")}),r.textContent=i}catch(f){r.textContent=`Error: ${f.message}`}finally{h.disabled=!1}}};if(h.addEventListener("click",s),d.addEventListener("keydown",a=>{a.key==="Enter"&&s()}),n==="report"&&o.join(",")==="*"){let a=ht();a&&(d.value=a,s())}}else if(n==="sites"){let d=t.find(".sim-input")[0],h=t.find(".sim-btn")[0],i=`Domains: ${o.length?o.join(", "):"*"}`;c&&!d.value&&(d.value=c.title),(async()=>{try{let l=await j,s=await M(l.length?l:["*"],y),a=s.reduce((f,w)=>f+(w.page_count||0),0);i=U("Site report ready",a,s.length),c&&(i=`${D(c)} \xB7 ${i}`),r.textContent=i}catch(l){r.textContent=`Domain listing unavailable: ${l.message}`}})();let u=async()=>{let l=d.value.trim();if(l){h.disabled=!0,r.textContent="Ranking sites\u2026";try{let s=await j,a=c&&l===c.title?X():{},f=await fetch(`${y}/system/site-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:l,domains:s.length?s:["*"],limit:x,...a})});if(!f.ok)throw new Error(`site-report failed: ${f.status}`);let w=await f.json();window.wiki.showResult(window.wiki.newPage(w),{$page:t.parents(".page")}),r.textContent=i}catch(s){r.textContent=`Error: ${s.message}`}finally{h.disabled=!1}}};h.addEventListener("click",u),d.addEventListener("keydown",l=>{l.key==="Enter"&&u()})}else if(n==="keyword"){let d=t.find(".sim-input")[0],h=t.find(".sim-btn")[0];c&&!d.value&&(d.value=c.title),r.textContent=(c?`${D(c)} \xB7 `:"")+`Keyword search ready \u2014 domains: ${o.length?o.join(", "):"*"} \xB7 limit ${x}`;let i=async()=>{let u=d.value.trim();if(u){h.disabled=!0,r.textContent="Searching live site indexes\u2026";try{let l=await j,s=encodeURIComponent((l.length?l:["*"]).join(",")),a=b.length?`&farms=${encodeURIComponent(b.join(","))}`:"",f=await fetch(`${y}/system/farm-search.json?q=${encodeURIComponent(u)}&pattern=${s}&limit=${x}${a}`);if(!f.ok)throw new Error(`farm-search failed: ${f.status}`);let w=await f.json();window.wiki.showResult(window.wiki.newPage(w),{$page:t.parents(".page")}),r.textContent=`Keyword search ready \u2014 domains: ${o.length?o.join(", "):"*"} \xB7 limit ${x}`}catch(l){r.textContent=`Error: ${l.message}`}finally{h.disabled=!1}}};h.addEventListener("click",i),d.addEventListener("keydown",u=>{u.key==="Enter"&&i()})}else if(n==="author"){let d=t.find(".sim-input")[0],h=t.find(".sim-btn")[0],i=t.find(".sim-results")[0],u=null;c&&!d.value&&(d.value=c.title),(async()=>{try{g||(r.textContent="Resolving domains\u2026"),u=await z(await j,y);let s=u.reduce((a,f)=>a+f.pages.length,0);r.textContent=(c?`${D(c)} \xB7 `:"")+U("Author ready",s,u.length)}catch(s){r.textContent=`Load error: ${s.message}`}})();let l=async()=>{let s=d.value.trim();if(!(!s||!u)){h.disabled=!0,r.textContent="Embedding query\u2026",i.innerHTML="";try{let a=await q(s,y),f=N(a,u,{threshold:m,limit:x,excludeSlug:null,excludeDomain:null}),w=new Set,E=[];for(let{title:S}of f)w.has(S)||(w.add(S),E.push(S));let L=()=>Math.floor(Math.random()*18446744073709552e3).toString(16).padStart(16,"0"),I=E.map(S=>`- [[${S}]]`).join(`
102
- `),P=[{type:"markdown",id:L(),text:`# Similar Pages
117
+ <p class="sim-count">${c.length} domains \u2014 ${l.toLocaleString()} pages${F(h)}</p>`};y?.domains?p(y.domains,y.ts):(async()=>{try{let c=await C,h=c.length?c.join(","):"*",l=`${v}/system/indexed-domains.json?pattern=${encodeURIComponent(h)}&limit=${g}`,o=await fetch(l);if(!o.ok)throw new Error(`indexed-domains failed: ${o.status}`);let f=await o.json();if(!f.length){a.textContent="No indexed domains found";return}p(f,null),Y(e,{domains:f})}catch(c){a.textContent=`Error: ${c.message}`}})()}else if(n==="similar"){let m=t.find(".sim-results")[0],p=(c,h)=>{if(!c.length){a.textContent=`No similar pages found above threshold ${u}`;return}m.innerHTML=`<h3>Similar Pages</h3><ul>${c.map(({domain:l,slug:o,title:f,score:S})=>`<li>${at(l,o,f,S)}</li>`).join("")}</ul><p class="sim-count">${c.length} found ${q}${F(h)}</p>`,a.style.display="none"};y?.scored?p(y.scored,y.ts):(async()=>{try{let c=t.parents(".page"),h=d||(()=>{let L=c.find(".title").text().trim()||document.title;return{slug:bt(L),site:window.location.hostname,title:L,text:null,isSelf:!0}})(),l=await tt(await C,v),o=l.reduce((L,x)=>L+x.pages.length,0);a.textContent=(d?`${B(h)} \xB7 `:"")+`Searching ${o.toLocaleString()} pages\u2026`;let f=await kt(h.slug,h.site);if(!f){a.textContent="Embedding page (not yet indexed)\u2026";let L=h.text||c.find(".item").map((x,j)=>$(j).text().trim()).get().filter(Boolean).join(`
118
+ `);f=await X(L||h.title,v)}let S=Q(f,l,{threshold:u,limit:g,excludeSlug:h.slug,excludeDomain:h.site});p(S,null),d&&(a.textContent=B(h),a.style.display=""),S.length&&!d&&Y(e,{scored:S})}catch(c){a.textContent=`Error: ${c.message}`}})()}else if(n==="ghost"){let m=t.find(".sim-btn")[0],p=async()=>{if(!R){a.textContent="No URL \u2014 GHOST needs a page-json URL";return}m.disabled=!0,a.textContent="Fetching\u2026";try{let c=await fetch(R);if(!c.ok)throw new Error(`fetch failed: ${c.status}`);let h=await c.json();window.wiki.showResult(window.wiki.newPage(h),{$page:t.parents(".page")}),a.textContent=""}catch(c){a.textContent=`Error: ${c.message}`}finally{m.disabled=!1}};m.addEventListener("click",p)}else if(n==="build"){let m=t.find(".sim-btn")[0],p=async()=>{m.disabled=!0,a.textContent="Building index\u2026 (may take a while for large scopes)";try{let c=encodeURIComponent((s.length?s:["*"]).join(",")),h=await fetch(`${v}/system/build-index.json?domains=${c}&force=${M?1:0}`);if(h.status===501){let o=await h.json().catch(()=>({}));throw new Error(o.hint||"indexing runs on the farm indexer, not this server")}if(!h.ok)throw new Error(`build-index failed: ${h.status}`);let l=await h.json();window.wiki.showResult(window.wiki.newPage(l),{$page:t.parents(".page")}),a.textContent=""}catch(c){a.textContent=`Error: ${c.message}`}finally{m.disabled=!1}};m.addEventListener("click",p)}else if(n==="report"){let m=t.find(".sim-input")[0],p=t.find(".sim-btn")[0],c=`Domains: ${s.length?s.join(", "):"*"}`;d&&!m.value&&(m.value=d.title),(async()=>{try{let x=await C,j=await K(x.length?x:["*"],v),D=j.reduce((P,I)=>P+(I.page_count||0),0);c=_("Report ready",D,j.length),r.length&&(c+=` \xB7 +${r.length} peer farm${r.length>1?"s":""}`),d&&(c=`${B(d)} \xB7 ${c}`),a.textContent=c}catch(x){a.textContent=`Domain listing unavailable: ${x.message}`}})();let h=new Set([502,503]),l=async(x,j)=>{let D=encodeURIComponent((j.length?j:["*"]).join(",")),P=r.length?`&farms=${encodeURIComponent(r.join(","))}`:"",I=await fetch(`${v}/system/farm-search.json?q=${encodeURIComponent(x)}&pattern=${D}&limit=${g}${P}`);if(!I.ok)throw new Error(`keyword search also failed: ${I.status}`);let E=await I.json();window.wiki.showResult(window.wiki.newPage(E),{$page:t.parents(".page")})},o=x=>U!=null?U>0:x.some(j=>j.toUpperCase()==="GALAXY"),f=t.find(".sim-results")[0],S=async(x,j,D)=>{let P=await At(w,v),I=j.filter(O=>!Z(O)&&O!=="*"&&!W(O)),E=null,z=O=>{let T=pe(x,O);E&&E.remove(),window.wiki.showResult(window.wiki.newPage(T),{$page:t.parents(".page")}),E=t.parents(".page").next(".page")},G=(O,T)=>{let Gt=O.slice(0,g),Vt=T.running?`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${O.length} results \u2014 searching\u2026`:T.converged?`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${O.length} results \u2014 the top ${g} stopped changing`:`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${O.length} results`,pt=T.total-T.searched,gt=[...new Set(O.map(H=>H.via).filter(Boolean))],Jt=`<small class="sim-tier">semantic \xB7 nearest sites first${gt.length?` \xB7 off-farm sites answered by ${gt.join(", ")}`:""}</small>`;f.innerHTML=`<h3>${Vt}</h3>${Jt}<ul>${Gt.map(H=>`<li>${at(H.site,H.slug,H.title,H.semantic)}`+(H.siblings?.length?` <small>+${H.siblings.length}</small>`:"")+"</li>").join("")}</ul><p class="sim-count sim-batch-controls">`+(T.running?'<button class="sim-stop">Stop</button>':"")+(!T.running&&pt>0?`<button class="sim-more">Search the remaining ${pt.toLocaleString()} sites</button>`:"")+(!T.running&&O.length?'<button class="sim-open">Open as page</button>':"")+(T.unindexed?.length&&!T.running?`<br><small>Sites that look relevant but carry no page vectors yet: ${T.unindexed.slice(0,8).join(", ")}</small>`:"")+"</p>",f.querySelector(".sim-stop")?.addEventListener("click",()=>T.stop()),f.querySelector(".sim-more")?.addEventListener("click",()=>T.continueAll()),f.querySelector(".sim-open")?.addEventListener("click",()=>z(O)),f.querySelectorAll(".sim-link").forEach(H=>H.addEventListener("click",Kt=>{Kt.preventDefault();let{site:wt,slug:$e,title:Yt}=H.dataset;ot(wt,"clicked"),window.wiki.pageHandler.context={site:window.location.hostname,slug:"search-tool"},window.wiki.doInternalLink(Yt,t.parents(".page"),wt)}))};a.textContent="";let J=await It({origin:v,query:x,seeded:D,specs:j.length?j:["GALAXY"],limit:g,threshold:u,thresholdSet:A,batch:U||50,roster:I,algorithm:P,render:G,status:O=>{a.textContent=O}});return a.textContent=c,J},L=async()=>{let x=m.value.trim();if(x){p.disabled=!0,a.textContent=r.length?"Generating report (asking peer farms)\u2026":"Generating report\u2026";try{let j=await C;if(o(j)){let G=d&&x===d.title?V():{};await S(x,j,G);return}let D=d&&x===d.title?V():{},P={query:x,domains:j.length?j:["*"],limit:g,live:k,...D};r.length&&(P.farms=r),A&&(P.threshold=u);let I=await fetch(`${v}/system/search-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(h.has(I.status)){let J=((await I.json().catch(()=>({}))).error||`status ${I.status}`).replace(/^embedding unavailable: /,"");a.textContent="Semantic search unavailable \u2014 searching by keyword instead\u2026",await l(x,j),a.textContent=`Semantic search unavailable (${J}) \u2014 these are keyword matches, ranked by word not meaning.`;return}if(!I.ok)throw new Error(`search-report failed: ${I.status}`);let E=await I.json(),z=window.wiki.newPage(E);window.wiki.showResult(z,{$page:t.parents(".page")}),a.textContent=c}catch(j){a.textContent=`Error: ${j.message}`}finally{p.disabled=!1}}};if(p.addEventListener("click",L),m.addEventListener("keydown",x=>{x.key==="Enter"&&L()}),n==="report"&&s.join(",")==="*"){let x=zt();x&&(m.value=x,L())}}else if(n==="sites"){let m=t.find(".sim-input")[0],p=t.find(".sim-btn")[0],c=`Domains: ${s.length?s.join(", "):"*"}`;d&&!m.value&&(m.value=d.title),(async()=>{try{let l=await C,o=await K(l.length?l:["*"],v),f=o.reduce((S,L)=>S+(L.page_count||0),0);c=_("Site report ready",f,o.length),d&&(c=`${B(d)} \xB7 ${c}`),a.textContent=c}catch(l){a.textContent=`Domain listing unavailable: ${l.message}`}})();let h=async()=>{let l=m.value.trim();if(l){p.disabled=!0,a.textContent="Ranking sites\u2026";try{let o=await C,f=d&&l===d.title?V():{},S=await fetch(`${v}/system/site-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:l,domains:o.length?o:["*"],limit:g,...f})});if(!S.ok)throw new Error(`site-report failed: ${S.status}`);let L=await S.json();window.wiki.showResult(window.wiki.newPage(L),{$page:t.parents(".page")}),a.textContent=c}catch(o){a.textContent=`Error: ${o.message}`}finally{p.disabled=!1}}};p.addEventListener("click",h),m.addEventListener("keydown",l=>{l.key==="Enter"&&h()})}else if(n==="keyword"){let m=t.find(".sim-input")[0],p=t.find(".sim-btn")[0];d&&!m.value&&(m.value=d.title),a.textContent=(d?`${B(d)} \xB7 `:"")+`Keyword search ready \u2014 domains: ${s.length?s.join(", "):"*"} \xB7 limit ${g}`;let c=async()=>{let h=m.value.trim();if(h){p.disabled=!0,a.textContent="Searching live site indexes\u2026";try{let l=await C,o=encodeURIComponent((l.length?l:["*"]).join(",")),f=r.length?`&farms=${encodeURIComponent(r.join(","))}`:"",S=await fetch(`${v}/system/farm-search.json?q=${encodeURIComponent(h)}&pattern=${o}&limit=${g}${f}`);if(!S.ok)throw new Error(`farm-search failed: ${S.status}`);let L=await S.json();window.wiki.showResult(window.wiki.newPage(L),{$page:t.parents(".page")}),a.textContent=`Keyword search ready \u2014 domains: ${s.length?s.join(", "):"*"} \xB7 limit ${g}`}catch(l){a.textContent=`Error: ${l.message}`}finally{p.disabled=!1}}};p.addEventListener("click",c),m.addEventListener("keydown",h=>{h.key==="Enter"&&c()})}else if(n==="author"){let m=t.find(".sim-input")[0],p=t.find(".sim-btn")[0],c=t.find(".sim-results")[0],h=null;d&&!m.value&&(m.value=d.title),(async()=>{try{y||(a.textContent="Resolving domains\u2026"),h=await tt(await C,v);let o=h.reduce((f,S)=>f+S.pages.length,0);a.textContent=(d?`${B(d)} \xB7 `:"")+_("Author ready",o,h.length)}catch(o){a.textContent=`Load error: ${o.message}`}})();let l=async()=>{let o=m.value.trim();if(!(!o||!h)){p.disabled=!0,a.textContent="Embedding query\u2026",c.innerHTML="";try{let f=await X(o,v),S=Q(f,h,{threshold:u,limit:g,excludeSlug:null,excludeDomain:null}),L=new Set,x=[];for(let{title:E}of S)L.has(E)||(L.add(E),x.push(E));let j=()=>Math.floor(Math.random()*18446744073709552e3).toString(16).padStart(16,"0"),D=x.map(E=>`- [[${E}]]`).join(`
119
+ `),P=[{type:"markdown",id:j(),text:`# Similar Pages
103
120
 
104
- ${I}`},{type:"markdown",id:L(),text:"# Reference Links"},...f.map(({domain:S,slug:_,title:wt,score:$t})=>({type:"reference",id:L(),site:S,slug:_,title:wt,text:`score ${$t.toFixed(3)}`}))],H=window.wiki.newPage({title:`${s} Results`,story:P,journal:[]});window.wiki.showResult(H,{$page:t.parents(".page")}),r.textContent=`${f.length} pages found`,A(e,{scored:f,query:s})}catch(a){r.textContent=`Error: ${a.message}`}finally{h.disabled=!1}}};h.addEventListener("click",l),d.addEventListener("keydown",s=>{s.key==="Enter"&&l()})}else{let d=t.find(".sim-input")[0],h=t.find(".sim-btn")[0],i=t.find(".sim-results")[0],u=null;g?.scored&&(d.value=g.query||"",i.innerHTML=g.scored.map(({domain:s,slug:a,title:f,score:w})=>`<div class="sim-result">${Z(s,a,f,w)}</div>`).join("")+`<p class="sim-count">Top ${g.scored.length} for "${g.query||""}"${B(g.ts)}</p>`,r.textContent=""),c&&!d.value&&(d.value=c.title),(async()=>{try{g||(r.textContent="Resolving domains\u2026"),u=await z(await j,y);let s=u.reduce((a,f)=>a+f.pages.length,0);r.textContent=(c?`${D(c)} \xB7 `:"")+U("Search ready",s,u.length)}catch(s){r.textContent=`Load error: ${s.message}`}})();let l=async()=>{let s=d.value.trim();if(!(!s||!u)){h.disabled=!0,r.textContent="Embedding query\u2026",i.innerHTML="";try{let a=await q(s,y),f=N(a,u,{threshold:m,limit:x,excludeSlug:null,excludeDomain:null});i.innerHTML=f.map(({domain:w,slug:E,title:L,score:I})=>`<div class="sim-result">${Z(w,E,L,I)}</div>`).join("")+`<p class="sim-count">Top ${f.length} for "${s}"</p>`,r.textContent="",A(e,{scored:f,query:s})}catch(a){r.textContent=`Error: ${a.message}`}finally{h.disabled=!1}}};h.addEventListener("click",l),d.addEventListener("keydown",s=>{s.key==="Enter"&&l()})}};typeof window<"u"&&(window.plugins=window.plugins||{},window.plugins.similarity={emit:Rt,bind:It,editor:(t,e)=>window.wiki.textEditor(t,e)},pt());})();
121
+ ${D}`},{type:"markdown",id:j(),text:"# Reference Links"},...S.map(({domain:E,slug:z,title:G,score:J})=>({type:"reference",id:j(),site:E,slug:z,title:G,text:`score ${J.toFixed(3)}`}))],I=window.wiki.newPage({title:`${o} Results`,story:P,journal:[]});window.wiki.showResult(I,{$page:t.parents(".page")}),a.textContent=`${S.length} pages found`,Y(e,{scored:S,query:o})}catch(f){a.textContent=`Error: ${f.message}`}finally{p.disabled=!1}}};p.addEventListener("click",l),m.addEventListener("keydown",o=>{o.key==="Enter"&&l()})}else{let m=t.find(".sim-input")[0],p=t.find(".sim-btn")[0],c=t.find(".sim-results")[0],h=null;y?.scored&&(m.value=y.query||"",c.innerHTML=y.scored.map(({domain:o,slug:f,title:S,score:L})=>`<div class="sim-result">${at(o,f,S,L)}</div>`).join("")+`<p class="sim-count">Top ${y.scored.length} for "${y.query||""}"${F(y.ts)}</p>`,a.textContent=""),d&&!m.value&&(m.value=d.title),(async()=>{try{y||(a.textContent="Resolving domains\u2026"),h=await tt(await C,v);let o=h.reduce((f,S)=>f+S.pages.length,0);a.textContent=(d?`${B(d)} \xB7 `:"")+_("Search ready",o,h.length)}catch(o){a.textContent=`Load error: ${o.message}`}})();let l=async()=>{let o=m.value.trim();if(!(!o||!h)){p.disabled=!0,a.textContent="Embedding query\u2026",c.innerHTML="";try{let f=await X(o,v),S=Q(f,h,{threshold:u,limit:g,excludeSlug:null,excludeDomain:null});c.innerHTML=S.map(({domain:L,slug:x,title:j,score:D})=>`<div class="sim-result">${at(L,x,j,D)}</div>`).join("")+`<p class="sim-count">Top ${S.length} for "${o}"</p>`,a.textContent="",Y(e,{scored:S,query:o})}catch(f){a.textContent=`Error: ${f.message}`}finally{p.disabled=!1}}};p.addEventListener("click",l),m.addEventListener("keydown",o=>{o.key==="Enter"&&l()})}};typeof window<"u"&&(window.plugins=window.plugins||{},window.plugins.similarity={emit:ge,bind:we,editor:(t,e)=>window.wiki.textEditor(t,e)},_t());})();
105
122
  //# sourceMappingURL=similarity.js.map