wiki-plugin-similarity 0.20.0 → 0.20.2

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,9 +1,9 @@
1
- /* wiki-plugin-similarity - 0.20.0 - Fri, 04 Sep 2026 09:22:03 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=`
1
+ /* wiki-plugin-similarity - 0.20.2 - Fri, 04 Sep 2026 12:13:43 GMT */
2
+ (()=>{var lt={high:.78,medium:.68,low:.58},rt=lt.medium,$t=10,ct=t=>{let e=[],n=[],s=[],i=null,a=null,d="search",g=!1,k=!1,b=!1,D=null,R=null,A=null,H=null,w=(r,u)=>r===u||r.startsWith(u)&&/^[\s:]/.test(r.slice(u.length)),v=(r,u)=>r.slice(u.length).replace(/^\s*:?\s*/,"").trim();for(let r of t.split(`
3
+ `)){let u=r.trim();if(!u||u.startsWith("#"))continue;let y=u.toUpperCase();if(w(y,"LIVE")){g=!0;continue}if(w(y,"SUBJECT")){k=!0;continue}if(w(y,"AUTHOR")){!e.length&&d==="search"&&(d="author");continue}if(w(y,"REPORT")){d==="search"&&(d="report");continue}if(w(y,"KEYWORD")){d==="search"&&(d="keyword");continue}if(w(y,"SITES")){d==="search"&&(d="sites");continue}if(w(y,"BUILD")){d==="search"&&(d="build");continue}if(w(y,"FORCE")){b=!0;continue}if(w(y,"GHOST")){D=v(u,"GHOST"),d==="search"&&(d="ghost");continue}if(w(y,"BUTTON")){R=v(u,"BUTTON");continue}if(w(y,"BATCH")){let C=v(u,"BATCH").toLowerCase();A=C==="off"||C==="no"||C==="0"?0:parseInt(C)||50;continue}if(w(y,"ALGORITHM")){H=v(u,"ALGORITHM").replace(/^\[\[|\]\]$/g,"").trim()||"search-algorithm",d==="search"&&!e.length&&(d="algorithm");continue}if(w(y,"ROSTER")){let C=v(u,"ROSTER");C&&n.push(C);continue}if(w(y,"FARM")){let C=v(u,"FARM");C&&s.push(C);continue}if(w(y,"LIST")){!e.length&&d==="search"&&(d="list");continue}if(w(y,"STATUS")){d==="search"&&(d="status");continue}if(w(y,"SIMILAR")){let C=v(y,"SIMILAR").toLowerCase();i=lt[C]||rt,!e.length&&d==="search"&&(d="similar");continue}if(w(y,"THRESHOLD")){let C=v(u,"THRESHOLD");i=lt[C.toLowerCase()]??(parseFloat(C)||rt);continue}if(w(y,"LIMIT")){a=parseInt(v(u,"LIMIT"))||$t;continue}e.push(["PUBLIC","LOCAL","PRIVATE","GALAXY","SITE"].includes(y)?y:u)}return{mode:d,specs:e,rosterRefs:n,farms:s,threshold:i??rt,limit:a??$t,live:g,subject:k,force:b,ghostUrl:D,label:R,batch:A,algorithm:H,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 a of await Wt(i,e))n.has(a.domain)||(n.add(a.domain),s.push(a));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 a of(i.text||"").split(/\r?\n/)){let d=a.trim();if(!d)continue;let g=d.match(Zt);if(g){e.add(g[0]);continue}let k=d.match(Xt);if(k){await xt(k[1],e,n);continue}let b=d.match(Qt);if(b)try{let D=await yt(b[1]);for(let R of D.story||[])R.type==="reference"&&R.site&&e.add(R.site)}catch(D){console.warn(D.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:a})=>{let d=[];for(let{domain:g,pages:k}of e)for(let{slug:b,title:D,vector:R}of k){if(b===i&&g===a)continue;let A=0;for(let H=0;H<t.length;H++)A+=t[H]*R[H];A>=n&&d.push({domain:g,slug:b,title:D,score:A})}return d.sort((g,k)=>k.score-g.score),d.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],a=s.data("site")||window.location.hostname,d=s.data("data")||{},g=d.title||s.find(".title").text().trim()||i,k=[g,...(d.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:a,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(a=>`${a.site} ${a.slug}`).join("|"),i=e.slice(0,n).map(a=>`${a.site} ${a.slug}`).join("|");return s===i},It=async t=>{let{origin:e,query:n,seeded:s={},specs:i,limit:a,batch:d,algorithm:g,render:k}=t,b=q=>t.status&&t.status(q),D={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:D,algorithm:g||{},batch:d||50}),A=R.batches||[],w={searched:0,total:R.count||A.reduce((q,N)=>q+N.length,0),batches:A.length,done:0,stopped:!1,converged:!1,running:!0,unindexed:R.unindexed||[]},v=new Map,r=[],u=0,y=()=>{w.stopped=!0};w.stop=y;let C=async q=>{let N={query:n,...s,domains:q,limit:Math.max(a*3,30),flat:!0};t.thresholdSet&&(N.threshold=t.threshold);let m=await Tt(`${e}/system/search-report.json`,N);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(r,p,a);r=p,w.searched+=q.length,w.done+=1,u=c?u+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(r,w),!q&&u>=3&&w.done<A.length){w.converged=!0;break}return w.running=!1,k(r,w),r};return w.continueAll=()=>(w.converged=!1,u=-1/0,_(!0)),await _(!1),{results:r,state:w,remaining:V}};var nt="similarity:learned",oe=new Set(["liked","visited","neighbourhood","neighborhood","followed","centroid","fresh","reliable"]),et=/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+|localhost)(:\d+)?$/,ht=t=>{let e={weights:{},always:[],never:[],batch:null,trust:null};for(let n of(t||"").split(`
5
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let[i,...a]=s.split(/\s+/),d=i.toUpperCase().replace(/:$/,"");if(d==="WEIGHT"&&a.length>=2){let g=a[0].toLowerCase().replace("neighborhood","neighbourhood"),k=parseFloat(a[1]);oe.has(g)&&Number.isFinite(k)&&(e.weights[g]=k)}else d==="ALWAYS"&&a[0]&&et.test(a[0])?e.always.push(a[0].toLowerCase()):d==="NEVER"&&a[0]&&et.test(a[0])?e.never.push(a[0].toLowerCase()):d==="BATCH"&&a[0]?e.batch=parseInt(a[0])||null:d==="TRUST"&&a[0]&&["solid","flaky","any"].includes(a[0].toLowerCase())&&(e.trust=a[0].toLowerCase())}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,trust:null,page:null};try{let i=await fetch(n);if(i.ok){let a=await i.json(),d=(a.story||[]).find(g=>g.type==="similarity"&&/^\s*ALGORITHM\b/im.test(g.text||""));d&&Object.assign(s,ht(d.text)),s.liked=ae(a),s.page={url:n,title:a.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(),a=i[n]?st(i[n],s):0,d=Math.min(1,a+(re[e]||.1));i[n]={score:d,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),d},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})},Ft=(t,e=20)=>new Promise((n,s)=>{let a=((t.data("data")||{}).story||[]).find(b=>b.type==="roster"&&/^\s*sites i visit\b/i.test(b.text||""));if(!a)return s(new Error('no "Sites I visit" roster on this page'));let d=ce().slice(0,e);if(!d.length)return s(new Error("nothing learned yet"));let g=["Sites I visit",...d.map(([b])=>b)].join(`
6
+ `),k={...a,text:g};try{window.wiki.pageHandler.put(t,{type:"edit",id:a.id,item:k});let b=t.find(`.item[data-id="${a.id}"]`);b.length&&(b.data("item",k),window.wiki.plugins?.roster?.emit?.(b,k)),n(d.length)}catch(b){s(b)}});var F=`
7
7
  .sim-form { display:flex; gap:6px; margin-bottom:8px; }
8
8
  .sim-input { flex:1; padding:6px 8px; font-size:14px; border:1px solid #ccc; border-radius:3px; }
9
9
  .sim-btn { padding:6px 14px; background:#c4561d; color:white; border:none;
@@ -27,54 +27,54 @@
27
27
  .sim-list td { padding:3px 8px 3px 0; border-bottom:1px solid #f0f0f0; vertical-align:middle; }
28
28
  .sim-list td:last-child { text-align:right; color:#999; font-size:11px; }
29
29
  .sim-list .sim-flag { margin-right:6px; }
30
- `,Ft=(t,e)=>`<img class="sim-flag remote" src="${window.wiki.site(t).flag()}"
30
+ `,Nt=(t,e)=>`<img class="sim-flag remote" src="${window.wiki.site(t).flag()}"
31
31
  title="${t} \u2014 score ${e.toFixed(3)}"
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>
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="#">${Nt(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(a=>a.title))];i.length&&s.push({type:"markdown",id:n(),text:i.map(a=>`- [[${a}]]`).join(`
33
+ `)}),s.push({type:"markdown",id:n(),text:"# Results"});for(let a of e)s.push({type:"reference",id:n(),site:a.site,slug:a.slug,title:a.title,text:a.synopsis||`score ${a.score}`});return{title:`${t} Federated Search`,story:s}},ge=(t,e)=>{let{mode:n,specs:s,threshold:i,limit:a,force:d,ghostUrl:g,label:k}=ct(e?.text||"");if(n==="ghost")t.html(`
34
+ <style>${F}</style>
35
35
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
36
36
  <div class="sim-form">
37
37
  <button class="sim-btn">${k||"Open"}</button>
38
38
  </div>
39
39
  <div class="sim-status"></div>
40
40
  </div>`);else if(n==="build")t.html(`
41
- <style>${N}</style>
41
+ <style>${F}</style>
42
42
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
43
43
  <div class="sim-form">
44
- <button class="sim-btn">${k||`Index ${s.length?s.join(", "):"*"}${u?" (force)":""}`}</button>
44
+ <button class="sim-btn">${k||`Index ${s.length?s.join(", "):"*"}${d?" (force)":""}`}</button>
45
45
  </div>
46
46
  <div class="sim-status"></div>
47
47
  </div>`);else if(n==="list"){let b=s.length?s.join(", "):"*";t.html(`
48
- <style>${N}</style>
48
+ <style>${F}</style>
49
49
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
50
50
  <div class="sim-status">Loading indexed domains (${b})\u2026</div>
51
51
  <div class="sim-list"></div>
52
52
  </div>`)}else if(n==="algorithm")t.html(`
53
- <style>${N}</style>
53
+ <style>${F}</style>
54
54
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="">
55
55
  <div class="sim-status">Reading this search algorithm\u2026</div>
56
56
  <div class="sim-list"></div>
57
57
  </div>`);else if(n==="status")t.html(`
58
- <style>${N}</style>
58
+ <style>${F}</style>
59
59
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
60
60
  <div class="sim-status">Reading the state of the index\u2026</div>
61
61
  <div class="sim-list"></div>
62
62
  </div>`);else if(n==="similar"){let b=s.length?s.join(", "):"current domain";t.html(`
63
- <style>${N}</style>
63
+ <style>${F}</style>
64
64
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
65
65
  <div class="sim-status">Finding similar pages across ${b}\u2026</div>
66
66
  <div class="sim-results"></div>
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>
67
+ </div>`)}else if(n==="author"||n==="report"||n==="keyword"||n==="sites"){let b=s.length?s.join(", "):"(current domain)",D=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>${F}</style>
69
69
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
70
70
  <div class="sim-form">
71
71
  <input class="sim-input" type="text" placeholder="${R}" />
72
- <button class="sim-btn">${M}</button>
72
+ <button class="sim-btn">${D}</button>
73
73
  </div>
74
74
  <div class="sim-status">Domains: ${b}</div>
75
75
  <div class="sim-results"></div>
76
76
  </div>`)}else{let b=s.length?s.join(", "):"(current domain)";t.html(`
77
- <style>${N}</style>
77
+ <style>${F}</style>
78
78
  <div class="similarity" data-id="${e.id}" data-mode="${n}" data-scope="${s.join(",")||""}">
79
79
  <div class="sim-form">
80
80
  <input class="sim-input" type="text" placeholder="Search wiki pages\u2026" />
@@ -82,11 +82,11 @@
82
82
  </div>
83
83
  <div class="sim-status">Domains: ${b}</div>
84
84
  <div class="sim-results"></div>
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>
86
- <p>${P}</p>
85
+ </div>`)}},we=(t,e)=>{let{mode:n,specs:s,rosterRefs:i,farms:a,threshold:d,limit:g,live:k,subject:b,force:D,ghostUrl:R,thresholdSet:A,batch:H,algorithm:w}=ct(e?.text||""),v=window.location.origin,r=t.find(".sim-status")[0];qt();let u=b?Lt(t):null,y=k||u?null:jt(e),C=St(s,i),V=()=>u?{seed:{site:u.site,slug:u.slug},text:u.text,excludePage:{site:u.site,slug:u.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 ${d}`),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",N=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),P=!S.ok,U=P?`<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";r.style.display="none",m.innerHTML=`<h3>The Index Behind These Answers</h3>
86
+ <p>${U}</p>
87
87
  <table>
88
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>
89
+ <tr><th>Embedder</th><td>${I}${P?" \u2014 <strong>currently down</strong>":""}</td></tr>
90
90
  <tr><th>Indexed</th><td>${f.length.toLocaleString()} domains \xB7 ${j.toLocaleString()} pages</td></tr>
91
91
  <tr><th>Newest page vectors</th><td>${c(x[x.length-1])} (${p(x[x.length-1])})</td></tr>
92
92
  <tr><th>Oldest page vectors</th><td>${c(x[0])} (${p(x[0])})</td></tr>
@@ -95,7 +95,7 @@
95
95
  </table>
96
96
  <p class="sim-count">A domain's vectors are only rebuilt when its pages change, so an old
97
97
  date means a quiet site, not a broken one. Pages saved since the last build are findable
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>
98
+ by keyword but not yet by meaning.</p>`}catch(l){r.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);r.style.display="none",m.innerHTML=`<h3>This Search Algorithm</h3>
99
99
  <table>
100
100
  ${Object.entries(p.weights).map(([o,f])=>`<tr><th>weight ${o}</th><td>${f}</td></tr>`).join("")}
101
101
  <tr><th>always</th><td>${p.always.length?p.always.join(", "):"\u2014"}</td></tr>
@@ -104,7 +104,7 @@
104
104
  </table>
105
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
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>
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 Ft(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){r.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);r.style.display="none",m.innerHTML=`<h3>Indexed Farm Domains</h3>
108
108
  <table>
109
109
  <tr><th>Domain</th><th>Pages</th></tr>
110
110
  ${c.map(({domain:o,page_count:f})=>`
@@ -114,9 +114,9 @@
114
114
  <td>${f!=null?f.toLocaleString():"\u2014"}</td>
115
115
  </tr>`).join("")}
116
116
  </table>
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
117
+ <p class="sim-count">${c.length} domains \u2014 ${l.toLocaleString()} pages${N(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){r.textContent="No indexed domains found";return}p(f,null),Y(e,{domains:f})}catch(c){r.textContent=`Error: ${c.message}`}})()}else if(n==="similar"){let m=t.find(".sim-results")[0],p=(c,h)=>{if(!c.length){r.textContent=`No similar pages found above threshold ${d}`;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}${N(h)}</p>`,r.style.display="none"};y?.scored?p(y.scored,y.ts):(async()=>{try{let c=t.parents(".page"),h=u||(()=>{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);r.textContent=(u?`${B(h)} \xB7 `:"")+`Searching ${o.toLocaleString()} pages\u2026`;let f=await kt(h.slug,h.site);if(!f){r.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:d,limit:g,excludeSlug:h.slug,excludeDomain:h.site});p(S,null),u&&(r.textContent=B(h),r.style.display=""),S.length&&!u&&Y(e,{scored:S})}catch(c){r.textContent=`Error: ${c.message}`}})()}else if(n==="ghost"){let m=t.find(".sim-btn")[0],p=async()=>{if(!R){r.textContent="No URL \u2014 GHOST needs a page-json URL";return}m.disabled=!0,r.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")}),r.textContent=""}catch(c){r.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,r.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=${D?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")}),r.textContent=""}catch(c){r.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(", "):"*"}`;u&&!m.value&&(m.value=u.title),(async()=>{try{let x=await C,j=await K(x.length?x:["*"],v),P=j.reduce((U,I)=>U+(I.page_count||0),0);c=_("Report ready",P,j.length),a.length&&(c+=` \xB7 +${a.length} peer farm${a.length>1?"s":""}`),u&&(c=`${B(u)} \xB7 ${c}`),r.textContent=c}catch(x){r.textContent=`Domain listing unavailable: ${x.message}`}})();let h=new Set([502,503]),l=async(x,j)=>{let P=encodeURIComponent((j.length?j:["*"]).join(",")),U=a.length?`&farms=${encodeURIComponent(a.join(","))}`:"",I=await fetch(`${v}/system/farm-search.json?q=${encodeURIComponent(x)}&pattern=${P}&limit=${g}${U}`);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=>H!=null?H>0:x.some(j=>j.toUpperCase()==="GALAXY"),f=t.find(".sim-results")[0],S=async(x,j,P)=>{let U=await At(w,v),I=j.filter(M=>!Z(M)&&M!=="*"&&!W(M)),E=null,z=M=>{let T=pe(x,M);E&&E.remove(),window.wiki.showResult(window.wiki.newPage(T),{$page:t.parents(".page")}),E=t.parents(".page").next(".page")},G=(M,T)=>{let Gt=M.slice(0,g),Vt=T.running?`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${M.length} results \u2014 searching\u2026`:T.converged?`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${M.length} results \u2014 the top ${g} stopped changing`:`Searched ${T.searched.toLocaleString()} of ${T.total.toLocaleString()} sites \u2014 ${M.length} results`,pt=T.total-T.searched,gt=[...new Set(M.map(O=>O.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(O=>`<li>${at(O.site,O.slug,O.title,O.semantic)}`+(O.siblings?.length?` <small>+${O.siblings.length}</small>`:"")+(O.movedFrom?` <small>moved here from ${O.movedFrom}</small>`:"")+(O.gone?` <small>site ${O.gone}${O.movedTo?`, probably now ${O.movedTo}`:""}</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&&M.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(M)),f.querySelectorAll(".sim-link").forEach(O=>O.addEventListener("click",Kt=>{Kt.preventDefault();let{site:wt,slug:$e,title:Yt}=O.dataset;ot(wt,"clicked"),window.wiki.pageHandler.context={site:window.location.hostname,slug:"search-tool"},window.wiki.doInternalLink(Yt,t.parents(".page"),wt)}))};r.textContent="";let J=await It({origin:v,query:x,seeded:P,specs:j.length?j:["GALAXY"],limit:g,threshold:d,thresholdSet:A,batch:H||50,roster:I,algorithm:U,render:G,status:M=>{r.textContent=M}});return r.textContent=c,J},L=async()=>{let x=m.value.trim();if(x){p.disabled=!0,r.textContent=a.length?"Generating report (asking peer farms)\u2026":"Generating report\u2026";try{let j=await C;if(o(j)){let G=u&&x===u.title?V():{};await S(x,j,G);return}let P=u&&x===u.title?V():{},U={query:x,domains:j.length?j:["*"],limit:g,live:k,...P};a.length&&(U.farms=a),A&&(U.threshold=d);let I=await fetch(`${v}/system/search-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)});if(h.has(I.status)){let J=((await I.json().catch(()=>({}))).error||`status ${I.status}`).replace(/^embedding unavailable: /,"");r.textContent="Semantic search unavailable \u2014 searching by keyword instead\u2026",await l(x,j),r.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")}),r.textContent=c}catch(j){r.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(", "):"*"}`;u&&!m.value&&(m.value=u.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),u&&(c=`${B(u)} \xB7 ${c}`),r.textContent=c}catch(l){r.textContent=`Domain listing unavailable: ${l.message}`}})();let h=async()=>{let l=m.value.trim();if(l){p.disabled=!0,r.textContent="Ranking sites\u2026";try{let o=await C,f=u&&l===u.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")}),r.textContent=c}catch(o){r.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];u&&!m.value&&(m.value=u.title),r.textContent=(u?`${B(u)} \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,r.textContent="Searching live site indexes\u2026";try{let l=await C,o=encodeURIComponent((l.length?l:["*"]).join(",")),f=a.length?`&farms=${encodeURIComponent(a.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")}),r.textContent=`Keyword search ready \u2014 domains: ${s.length?s.join(", "):"*"} \xB7 limit ${g}`}catch(l){r.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;u&&!m.value&&(m.value=u.title),(async()=>{try{y||(r.textContent="Resolving domains\u2026"),h=await tt(await C,v);let o=h.reduce((f,S)=>f+S.pages.length,0);r.textContent=(u?`${B(u)} \xB7 `:"")+_("Author ready",o,h.length)}catch(o){r.textContent=`Load error: ${o.message}`}})();let l=async()=>{let o=m.value.trim();if(!(!o||!h)){p.disabled=!0,r.textContent="Embedding query\u2026",c.innerHTML="";try{let f=await X(o,v),S=Q(f,h,{threshold:d,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"),P=x.map(E=>`- [[${E}]]`).join(`
119
+ `),U=[{type:"markdown",id:j(),text:`# Similar Pages
120
120
 
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());})();
121
+ ${P}`},{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:U,journal:[]});window.wiki.showResult(I,{$page:t.parents(".page")}),r.textContent=`${S.length} pages found`,Y(e,{scored:S,query:o})}catch(f){r.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||""}"${N(y.ts)}</p>`,r.textContent=""),u&&!m.value&&(m.value=u.title),(async()=>{try{y||(r.textContent="Resolving domains\u2026"),h=await tt(await C,v);let o=h.reduce((f,S)=>f+S.pages.length,0);r.textContent=(u?`${B(u)} \xB7 `:"")+_("Search ready",o,h.length)}catch(o){r.textContent=`Load error: ${o.message}`}})();let l=async()=>{let o=m.value.trim();if(!(!o||!h)){p.disabled=!0,r.textContent="Embedding query\u2026",c.innerHTML="";try{let f=await X(o,v),S=Q(f,h,{threshold:d,limit:g,excludeSlug:null,excludeDomain:null});c.innerHTML=S.map(({domain:L,slug:x,title:j,score:P})=>`<div class="sim-result">${at(L,x,j,P)}</div>`).join("")+`<p class="sim-count">Top ${S.length} for "${o}"</p>`,r.textContent="",Y(e,{scored:S,query:o})}catch(f){r.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());})();
122
122
  //# sourceMappingURL=similarity.js.map