wiki-plugin-similarity 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/similarity.js +33 -33
- package/client/similarity.js.map +3 -3
- package/package.json +1 -1
- package/pages/about-similarity-plugin +33 -23
- package/server/server.js +91 -9
package/client/similarity.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/* wiki-plugin-similarity - 0.
|
|
2
|
-
(()=>{var
|
|
3
|
-
`)){let r=
|
|
4
|
-
`).slice(0,2e3);return{slug:
|
|
1
|
+
/* wiki-plugin-similarity - 0.15.0 - Thu, 03 Sep 2026 21:09:58 GMT */
|
|
2
|
+
(()=>{var _={high:.78,medium:.68,low:.58},q=_.medium,Y=10,B=t=>{let e=[],s=[],n=[],m=null,b=null,u="search",y=!1,k=!1,S=!1,R=null,j=null,E=(i,r)=>i===r||i.startsWith(r)&&/^[\s:]/.test(i.slice(r.length)),w=(i,r)=>i.slice(r.length).replace(/^\s*:?\s*/,"").trim();for(let i of t.split(`
|
|
3
|
+
`)){let r=i.trim();if(!r||r.startsWith("#"))continue;let p=r.toUpperCase();if(E(p,"LIVE")){y=!0;continue}if(E(p,"SUBJECT")){k=!0;continue}if(E(p,"AUTHOR")){!e.length&&u==="search"&&(u="author");continue}if(E(p,"REPORT")){u==="search"&&(u="report");continue}if(E(p,"KEYWORD")){u==="search"&&(u="keyword");continue}if(E(p,"SITES")){u==="search"&&(u="sites");continue}if(E(p,"BUILD")){u==="search"&&(u="build");continue}if(E(p,"FORCE")){S=!0;continue}if(E(p,"GHOST")){R=w(r,"GHOST"),u==="search"&&(u="ghost");continue}if(E(p,"BUTTON")){j=w(r,"BUTTON");continue}if(E(p,"ROSTER")){let v=w(r,"ROSTER");v&&s.push(v);continue}if(E(p,"FARM")){let v=w(r,"FARM");v&&n.push(v);continue}if(E(p,"LIST")){!e.length&&u==="search"&&(u="list");continue}if(E(p,"SIMILAR")){let v=w(p,"SIMILAR").toLowerCase();m=_[v]||q,!e.length&&u==="search"&&(u="similar");continue}if(E(p,"THRESHOLD")){let v=w(r,"THRESHOLD");m=_[v.toLowerCase()]??(parseFloat(v)||q);continue}if(E(p,"LIMIT")){b=parseInt(w(r,"LIMIT"))||Y;continue}e.push(["PUBLIC","LOCAL","PRIVATE","GALAXY"].includes(p)?p:r)}return{mode:u,specs:e,rosterRefs:s,farms:n,threshold:m??q,limit:b??Y,live:y,subject:k,force:S,ghostUrl:R,label:j,thresholdSet:m!==null}},Z=t=>t.includes("*")||t.includes("?"),X=t=>t==="PUBLIC"||t==="LOCAL"||t==="PRIVATE"||t==="GALAXY";var tt=t=>t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),G=new Map,pt=async(t,e)=>{if(G.has(t))return G.get(t);let s=`${e}/system/indexed-domains.json?pattern=${encodeURIComponent(t)}`,n=await fetch(s);if(!n.ok)throw new Error(`indexed-domains failed: ${n.status}`);let m=await n.json();return G.set(t,m),m},P=async(t,e)=>{t.length||(t=[window.location.hostname]);let s=new Set,n=[];for(let m of t)if(m==="*"||Z(m)||X(m))for(let b of await pt(m,e))s.has(b.domain)||(s.add(b.domain),n.push(b));else s.has(m)||(s.add(m),n.push({domain:m,page_count:null}));return n},gt=/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+|localhost)(:\d+)?$/,ht=/^ROSTER ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,wt=/^REFERENCES ([A-Za-z0-9.\-:]+\/[a-z0-9-]+)$/,Q=async t=>{let e=t.indexOf("/"),s=await fetch(`//${t.slice(0,e)}/${t.slice(e+1)}.json`);if(!s.ok)throw new Error(`roster page ${t} failed: ${s.status}`);return s.json()},et=async(t,e,s)=>{if(s.has(t))return;s.add(t);let n;try{n=await Q(t)}catch(m){console.warn(m.message);return}for(let m of n.story||[])if(m.type==="roster")for(let b of(m.text||"").split(/\r?\n/)){let u=b.trim();if(!u)continue;let y=u.match(gt);if(y){e.add(y[0]);continue}let k=u.match(ht);if(k){await et(k[1],e,s);continue}let S=u.match(wt);if(S)try{let R=await Q(S[1]);for(let j of R.story||[])j.type==="reference"&&j.site&&e.add(j.site)}catch(R){console.warn(R.message)}}},yt=async t=>{let e=new Set,s=new Set;for(let n of t)await et(n,e,s);return[...e]},st=async(t,e)=>e.length?[...t,...await yt(e)]:t;var V=new Map,$t=t=>`${window.location.origin}/system/semantic-vectors.json?domain=${encodeURIComponent(t)}`,nt=async t=>{if(V.has(t))return V.get(t);let e=await fetch($t(t));if(!e.ok)return[];let s=await e.json();return V.set(t,s),s},M=async(t,e)=>{let s=await fetch(`${e}/system/embed.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t})});if(!s.ok)throw new Error(`embed failed: ${s.status}`);return(await s.json()).vector},it=async(t,e)=>{let n=(await nt(e)).find(m=>m.slug===t);return n?n.vector:null},z=(t,e,{threshold:s,limit:n,excludeSlug:m,excludeDomain:b})=>{let u=[];for(let{domain:y,pages:k}of e)for(let{slug:S,title:R,vector:j}of k){if(S===m&&y===b)continue;let E=0;for(let w=0;w<t.length;w++)E+=t[w]*j[w];E>=s&&u.push({domain:y,slug:S,title:R,score:E})}return u.sort((y,k)=>k.score-y.score),u.slice(0,n)},F=async(t,e)=>{let s=await P(t,e);return(await Promise.all(s.map(async({domain:m})=>({domain:m,pages:await nt(m)})))).filter(m=>m.pages.length>0)};var ot=t=>{let e=t.parents(".page:first"),s=e.prev(".page"),n=s.length?s:e,m=(n.attr("id")||"").split("_rev")[0],b=n.data("site")||window.location.hostname,u=n.data("data")||{},y=u.title||n.find(".title").text().trim()||m,k=[y,...(u.story||[]).filter(S=>S.type==="markdown"||S.type==="paragraph").map(S=>(S.text||"").trim()).filter(Boolean)].join(`
|
|
4
|
+
`).slice(0,2e3);return{slug:m,site:b,title:y,text:k,isSelf:!s.length}},I=t=>`Subject: ${t.title}${t.isSelf?" (this page)":` @ ${t.site}`}`;var at=t=>`sim-cache-${t}`,rt=t=>{try{let e=JSON.parse(localStorage.getItem(at(t.id))||"null");return e?.text===(t.text||"")?e:null}catch{return null}},U=(t,e)=>{try{localStorage.setItem(at(t.id),JSON.stringify({text:t.text||"",ts:Date.now(),...e}))}catch{}},lt=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=`
|
|
5
5
|
.sim-form { display:flex; gap:6px; margin-bottom:8px; }
|
|
6
6
|
.sim-input { flex:1; padding:6px 8px; font-size:14px; border:1px solid #ccc; border-radius:3px; }
|
|
7
7
|
.sim-btn { padding:6px 14px; background:#c4561d; color:white; border:none;
|
|
@@ -25,63 +25,63 @@
|
|
|
25
25
|
.sim-list td { padding:3px 8px 3px 0; border-bottom:1px solid #f0f0f0; vertical-align:middle; }
|
|
26
26
|
.sim-list td:last-child { text-align:right; color:#999; font-size:11px; }
|
|
27
27
|
.sim-list .sim-flag { margin-right:6px; }
|
|
28
|
-
`,
|
|
28
|
+
`,ct=(t,e)=>`<img class="sim-flag remote" src="${window.wiki.site(t).flag()}"
|
|
29
29
|
title="${t} \u2014 score ${e.toFixed(3)}"
|
|
30
|
-
data-site="${t}">`;var
|
|
31
|
-
<style>${
|
|
30
|
+
data-site="${t}">`;var K=(t,e,s,n)=>`<a class="sim-link" data-title="${s}" data-slug="${e}" data-site="${t}" href="#">${ct(t,n)} ${s}</a>`,xt=(t,e)=>{let{mode:s,specs:n,threshold:m,limit:b,force:u,ghostUrl:y,label:k}=B(e?.text||"");if(s==="ghost")t.html(`
|
|
31
|
+
<style>${O}</style>
|
|
32
32
|
<div class="similarity" data-id="${e.id}">
|
|
33
33
|
<div class="sim-form">
|
|
34
|
-
<button class="sim-btn">${
|
|
34
|
+
<button class="sim-btn">${k||"Open"}</button>
|
|
35
35
|
</div>
|
|
36
36
|
<div class="sim-status"></div>
|
|
37
37
|
</div>`);else if(s==="build")t.html(`
|
|
38
|
-
<style>${
|
|
38
|
+
<style>${O}</style>
|
|
39
39
|
<div class="similarity" data-id="${e.id}">
|
|
40
40
|
<div class="sim-form">
|
|
41
|
-
<button class="sim-btn">${
|
|
41
|
+
<button class="sim-btn">${k||`Index ${n.length?n.join(", "):"*"}${u?" (force)":""}`}</button>
|
|
42
42
|
</div>
|
|
43
43
|
<div class="sim-status"></div>
|
|
44
|
-
</div>`);else if(s==="list"){let
|
|
45
|
-
<style>${
|
|
44
|
+
</div>`);else if(s==="list"){let S=n.length?n.join(", "):"*";t.html(`
|
|
45
|
+
<style>${O}</style>
|
|
46
46
|
<div class="similarity" data-id="${e.id}">
|
|
47
|
-
<div class="sim-status">Loading indexed domains (${
|
|
47
|
+
<div class="sim-status">Loading indexed domains (${S})\u2026</div>
|
|
48
48
|
<div class="sim-list"></div>
|
|
49
|
-
</div>`)}else if(s==="similar"){let
|
|
50
|
-
<style>${
|
|
49
|
+
</div>`)}else if(s==="similar"){let S=n.length?n.join(", "):"current domain";t.html(`
|
|
50
|
+
<style>${O}</style>
|
|
51
51
|
<div class="similarity" data-id="${e.id}">
|
|
52
|
-
<div class="sim-status">Finding similar pages across ${
|
|
52
|
+
<div class="sim-status">Finding similar pages across ${S}\u2026</div>
|
|
53
53
|
<div class="sim-results"></div>
|
|
54
|
-
</div>`)}else if(s==="author"||s==="report"||s==="keyword"||s==="sites"){let
|
|
55
|
-
<style>${
|
|
54
|
+
</div>`)}else if(s==="author"||s==="report"||s==="keyword"||s==="sites"){let S=n.length?n.join(", "):"(current domain)",R=s==="report"?"Report":s==="keyword"?"Keyword":s==="sites"?"Sites":"Author",j=s==="sites"?"Where should this page go? Title + first paragraph\u2026":"Search wiki pages\u2026";t.html(`
|
|
55
|
+
<style>${O}</style>
|
|
56
56
|
<div class="similarity" data-id="${e.id}">
|
|
57
57
|
<div class="sim-form">
|
|
58
|
-
<input class="sim-input" type="text" placeholder="${
|
|
59
|
-
<button class="sim-btn">${
|
|
58
|
+
<input class="sim-input" type="text" placeholder="${j}" />
|
|
59
|
+
<button class="sim-btn">${R}</button>
|
|
60
60
|
</div>
|
|
61
|
-
<div class="sim-status">Domains: ${
|
|
61
|
+
<div class="sim-status">Domains: ${S}</div>
|
|
62
62
|
<div class="sim-results"></div>
|
|
63
|
-
</div>`)}else{let
|
|
64
|
-
<style>${
|
|
63
|
+
</div>`)}else{let S=n.length?n.join(", "):"(current domain)";t.html(`
|
|
64
|
+
<style>${O}</style>
|
|
65
65
|
<div class="similarity" data-id="${e.id}">
|
|
66
66
|
<div class="sim-form">
|
|
67
67
|
<input class="sim-input" type="text" placeholder="Search wiki pages\u2026" />
|
|
68
68
|
<button class="sim-btn">Search</button>
|
|
69
69
|
</div>
|
|
70
|
-
<div class="sim-status">Domains: ${
|
|
70
|
+
<div class="sim-status">Domains: ${S}</div>
|
|
71
71
|
<div class="sim-results"></div>
|
|
72
|
-
</div>`)}},bt=(t,e)=>{let{mode:s,specs:
|
|
72
|
+
</div>`)}},bt=(t,e)=>{let{mode:s,specs:n,rosterRefs:m,farms:b,threshold:u,limit:y,live:k,subject:S,force:R,ghostUrl:j,thresholdSet:E}=B(e?.text||""),w=window.location.origin,i=t.find(".sim-status")[0],r=S?ot(t):null,p=k||r?null:rt(e),v=st(n,m),J=()=>r?{seed:{site:r.site,slug:r.slug},text:r.text,excludePage:{site:r.site,slug:r.slug}}:{},A=(d,g,o)=>{let l=[`${d} \u2014 ${g.toLocaleString()} pages across ${o} domains`];return E&&l.push(`threshold ${u}`),l.push(`limit ${y}`),k&&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 g=$(this),o=d.shiftKey?null:t.parents(".page");window.wiki.doInternalLink(g.data("title"),o,g.data("site"))});let dt=!n.length||n.length===1&&n[0]==="*"?"on farm":n.length===1?`on ${n[0]}`:"in domains",H=d=>d?` \xB7 cached ${lt(d)}`:"";if(s==="list"){let d=t.find(".sim-list")[0],g=(o,l)=>{let h=o.reduce((a,c)=>a+(c.page_count||0),0);i.style.display="none",d.innerHTML=`<h3>Indexed Farm Domains</h3>
|
|
73
73
|
<table>
|
|
74
74
|
<tr><th>Domain</th><th>Pages</th></tr>
|
|
75
|
-
${o.map(({domain:
|
|
75
|
+
${o.map(({domain:a,page_count:c})=>`
|
|
76
76
|
<tr>
|
|
77
|
-
<td><img class="sim-flag remote" src="${window.wiki.site(
|
|
78
|
-
title="${
|
|
79
|
-
<td>${
|
|
77
|
+
<td><img class="sim-flag remote" src="${window.wiki.site(a).flag()}"
|
|
78
|
+
title="${a}" data-site="${a}"> ${a}</td>
|
|
79
|
+
<td>${c!=null?c.toLocaleString():"\u2014"}</td>
|
|
80
80
|
</tr>`).join("")}
|
|
81
81
|
</table>
|
|
82
|
-
<p class="sim-count">${o.length} domains \u2014 ${
|
|
83
|
-
`);
|
|
84
|
-
`),
|
|
82
|
+
<p class="sim-count">${o.length} domains \u2014 ${h.toLocaleString()} pages${H(l)}</p>`};p?.domains?g(p.domains,p.ts):(async()=>{try{let o=await v,l=o.length?o.join(","):"*",h=`${w}/system/indexed-domains.json?pattern=${encodeURIComponent(l)}&limit=${y}`,a=await fetch(h);if(!a.ok)throw new Error(`indexed-domains failed: ${a.status}`);let c=await a.json();if(!c.length){i.textContent="No indexed domains found";return}g(c,null),U(e,{domains:c})}catch(o){i.textContent=`Error: ${o.message}`}})()}else if(s==="similar"){let d=t.find(".sim-results")[0],g=(o,l)=>{if(!o.length){i.textContent=`No similar pages found above threshold ${u}`;return}d.innerHTML=`<h3>Similar Pages</h3><ul>${o.map(({domain:h,slug:a,title:c,score:f})=>`<li>${K(h,a,c,f)}</li>`).join("")}</ul><p class="sim-count">${o.length} found ${dt}${H(l)}</p>`,i.style.display="none"};p?.scored?g(p.scored,p.ts):(async()=>{try{let o=t.parents(".page"),l=r||(()=>{let x=o.find(".title").text().trim()||document.title;return{slug:tt(x),site:window.location.hostname,title:x,text:null,isSelf:!0}})(),h=await F(await v,w),a=h.reduce((x,L)=>x+L.pages.length,0);i.textContent=(r?`${I(l)} \xB7 `:"")+`Searching ${a.toLocaleString()} pages\u2026`;let c=await it(l.slug,l.site);if(!c){i.textContent="Embedding page (not yet indexed)\u2026";let x=l.text||o.find(".item").map((L,C)=>$(C).text().trim()).get().filter(Boolean).join(`
|
|
83
|
+
`);c=await M(x||l.title,w)}let f=z(c,h,{threshold:u,limit:y,excludeSlug:l.slug,excludeDomain:l.site});g(f,null),r&&(i.textContent=I(l),i.style.display=""),f.length&&!r&&U(e,{scored:f})}catch(o){i.textContent=`Error: ${o.message}`}})()}else if(s==="ghost"){let d=t.find(".sim-btn")[0],g=async()=>{if(!j){i.textContent="No URL \u2014 GHOST needs a page-json URL";return}d.disabled=!0,i.textContent="Fetching\u2026";try{let o=await fetch(j);if(!o.ok)throw new Error(`fetch failed: ${o.status}`);let l=await o.json();window.wiki.showResult(window.wiki.newPage(l),{$page:t.parents(".page")}),i.textContent=""}catch(o){i.textContent=`Error: ${o.message}`}finally{d.disabled=!1}};d.addEventListener("click",g)}else if(s==="build"){let d=t.find(".sim-btn")[0],g=async()=>{d.disabled=!0,i.textContent="Building index\u2026 (may take a while for large scopes)";try{let o=encodeURIComponent((n.length?n:["*"]).join(",")),l=await fetch(`${w}/system/build-index.json?domains=${o}&force=${R?1:0}`);if(l.status===501){let a=await l.json().catch(()=>({}));throw new Error(a.hint||"indexing runs on the farm indexer, not this server")}if(!l.ok)throw new Error(`build-index failed: ${l.status}`);let h=await l.json();window.wiki.showResult(window.wiki.newPage(h),{$page:t.parents(".page")}),i.textContent=""}catch(o){i.textContent=`Error: ${o.message}`}finally{d.disabled=!1}};d.addEventListener("click",g)}else if(s==="report"){let d=t.find(".sim-input")[0],g=t.find(".sim-btn")[0],o=`Domains: ${n.length?n.join(", "):"*"}`;r&&!d.value&&(d.value=r.title),(async()=>{try{let c=await v,f=await P(c.length?c:["*"],w),x=f.reduce((L,C)=>L+(C.page_count||0),0);o=A("Report ready",x,f.length),b.length&&(o+=` \xB7 +${b.length} peer farm${b.length>1?"s":""}`),r&&(o=`${I(r)} \xB7 ${o}`),i.textContent=o}catch(c){i.textContent=`Domain listing unavailable: ${c.message}`}})();let l=new Set([502,503]),h=async(c,f)=>{let x=encodeURIComponent((f.length?f:["*"]).join(",")),L=b.length?`&farms=${encodeURIComponent(b.join(","))}`:"",C=await fetch(`${w}/system/farm-search.json?q=${encodeURIComponent(c)}&pattern=${x}&limit=${y}${L}`);if(!C.ok)throw new Error(`keyword search also failed: ${C.status}`);let D=await C.json();window.wiki.showResult(window.wiki.newPage(D),{$page:t.parents(".page")})},a=async()=>{let c=d.value.trim();if(c){g.disabled=!0,i.textContent=b.length?"Generating report (asking peer farms)\u2026":"Generating report\u2026";try{let f=await v,x=r&&c===r.title?J():{},L={query:c,domains:f.length?f:["*"],limit:y,live:k,...x};b.length&&(L.farms=b),E&&(L.threshold=u);let C=await fetch(`${w}/system/search-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(l.has(C.status)){let T=((await C.json().catch(()=>({}))).error||`status ${C.status}`).replace(/^embedding unavailable: /,"");i.textContent="Semantic search unavailable \u2014 searching by keyword instead\u2026",await h(c,f),i.textContent=`Semantic search unavailable (${T}) \u2014 these are keyword matches, ranked by word not meaning.`;return}if(!C.ok)throw new Error(`search-report failed: ${C.status}`);let D=await C.json(),N=window.wiki.newPage(D);window.wiki.showResult(N,{$page:t.parents(".page")}),i.textContent=o}catch(f){i.textContent=`Error: ${f.message}`}finally{g.disabled=!1}}};g.addEventListener("click",a),d.addEventListener("keydown",c=>{c.key==="Enter"&&a()})}else if(s==="sites"){let d=t.find(".sim-input")[0],g=t.find(".sim-btn")[0],o=`Domains: ${n.length?n.join(", "):"*"}`;r&&!d.value&&(d.value=r.title),(async()=>{try{let h=await v,a=await P(h.length?h:["*"],w),c=a.reduce((f,x)=>f+(x.page_count||0),0);o=A("Site report ready",c,a.length),r&&(o=`${I(r)} \xB7 ${o}`),i.textContent=o}catch(h){i.textContent=`Domain listing unavailable: ${h.message}`}})();let l=async()=>{let h=d.value.trim();if(h){g.disabled=!0,i.textContent="Ranking sites\u2026";try{let a=await v,c=r&&h===r.title?J():{},f=await fetch(`${w}/system/site-report.json`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:h,domains:a.length?a:["*"],limit:y,...c})});if(!f.ok)throw new Error(`site-report failed: ${f.status}`);let x=await f.json();window.wiki.showResult(window.wiki.newPage(x),{$page:t.parents(".page")}),i.textContent=o}catch(a){i.textContent=`Error: ${a.message}`}finally{g.disabled=!1}}};g.addEventListener("click",l),d.addEventListener("keydown",h=>{h.key==="Enter"&&l()})}else if(s==="keyword"){let d=t.find(".sim-input")[0],g=t.find(".sim-btn")[0];r&&!d.value&&(d.value=r.title),i.textContent=(r?`${I(r)} \xB7 `:"")+`Keyword search ready \u2014 domains: ${n.length?n.join(", "):"*"} \xB7 limit ${y}`;let o=async()=>{let l=d.value.trim();if(l){g.disabled=!0,i.textContent="Searching live site indexes\u2026";try{let h=await v,a=encodeURIComponent((h.length?h:["*"]).join(",")),c=b.length?`&farms=${encodeURIComponent(b.join(","))}`:"",f=await fetch(`${w}/system/farm-search.json?q=${encodeURIComponent(l)}&pattern=${a}&limit=${y}${c}`);if(!f.ok)throw new Error(`farm-search failed: ${f.status}`);let x=await f.json();window.wiki.showResult(window.wiki.newPage(x),{$page:t.parents(".page")}),i.textContent=`Keyword search ready \u2014 domains: ${n.length?n.join(", "):"*"} \xB7 limit ${y}`}catch(h){i.textContent=`Error: ${h.message}`}finally{g.disabled=!1}}};g.addEventListener("click",o),d.addEventListener("keydown",l=>{l.key==="Enter"&&o()})}else if(s==="author"){let d=t.find(".sim-input")[0],g=t.find(".sim-btn")[0],o=t.find(".sim-results")[0],l=null;r&&!d.value&&(d.value=r.title),(async()=>{try{p||(i.textContent="Resolving domains\u2026"),l=await F(await v,w);let a=l.reduce((c,f)=>c+f.pages.length,0);i.textContent=(r?`${I(r)} \xB7 `:"")+A("Author ready",a,l.length)}catch(a){i.textContent=`Load error: ${a.message}`}})();let h=async()=>{let a=d.value.trim();if(!(!a||!l)){g.disabled=!0,i.textContent="Embedding query\u2026",o.innerHTML="";try{let c=await M(a,w),f=z(c,l,{threshold:u,limit:y,excludeSlug:null,excludeDomain:null}),x=new Set,L=[];for(let{title:T}of f)x.has(T)||(x.add(T),L.push(T));let C=()=>Math.floor(Math.random()*18446744073709552e3).toString(16).padStart(16,"0"),D=L.map(T=>`- [[${T}]]`).join(`
|
|
84
|
+
`),N=[{type:"markdown",id:C(),text:`# Similar Pages
|
|
85
85
|
|
|
86
|
-
${
|
|
86
|
+
${D}`},{type:"markdown",id:C(),text:"# Reference Links"},...f.map(({domain:T,slug:ft,title:ut,score:mt})=>({type:"reference",id:C(),site:T,slug:ft,title:ut,text:`score ${mt.toFixed(3)}`}))],W=window.wiki.newPage({title:`${a} Results`,story:N,journal:[]});window.wiki.showResult(W,{$page:t.parents(".page")}),i.textContent=`${f.length} pages found`,U(e,{scored:f,query:a})}catch(c){i.textContent=`Error: ${c.message}`}finally{g.disabled=!1}}};g.addEventListener("click",h),d.addEventListener("keydown",a=>{a.key==="Enter"&&h()})}else{let d=t.find(".sim-input")[0],g=t.find(".sim-btn")[0],o=t.find(".sim-results")[0],l=null;p?.scored&&(d.value=p.query||"",o.innerHTML=p.scored.map(({domain:a,slug:c,title:f,score:x})=>`<div class="sim-result">${K(a,c,f,x)}</div>`).join("")+`<p class="sim-count">Top ${p.scored.length} for "${p.query||""}"${H(p.ts)}</p>`,i.textContent=""),r&&!d.value&&(d.value=r.title),(async()=>{try{p||(i.textContent="Resolving domains\u2026"),l=await F(await v,w);let a=l.reduce((c,f)=>c+f.pages.length,0);i.textContent=(r?`${I(r)} \xB7 `:"")+A("Search ready",a,l.length)}catch(a){i.textContent=`Load error: ${a.message}`}})();let h=async()=>{let a=d.value.trim();if(!(!a||!l)){g.disabled=!0,i.textContent="Embedding query\u2026",o.innerHTML="";try{let c=await M(a,w),f=z(c,l,{threshold:u,limit:y,excludeSlug:null,excludeDomain:null});o.innerHTML=f.map(({domain:x,slug:L,title:C,score:D})=>`<div class="sim-result">${K(x,L,C,D)}</div>`).join("")+`<p class="sim-count">Top ${f.length} for "${a}"</p>`,i.textContent="",U(e,{scored:f,query:a})}catch(c){i.textContent=`Error: ${c.message}`}finally{g.disabled=!1}}};g.addEventListener("click",h),d.addEventListener("keydown",a=>{a.key==="Enter"&&h()})}};typeof window<"u"&&(window.plugins=window.plugins||{},window.plugins.similarity={emit:xt,bind:bt});})();
|
|
87
87
|
//# sourceMappingURL=similarity.js.map
|
package/client/similarity.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client/dsl.js", "../src/client/scope.js", "../src/client/vectors.js", "../src/client/subject.js", "../src/client/cache.js", "../src/client/styles.js", "../src/client/similarity.js"],
|
|
4
|
-
"sourcesContent": ["// wiki-plugin-similarity \u2014 the item's line-oriented DSL: parse it, and classify a spec\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 DSL Parser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst SIMILAR_THRESHOLDS = { high: 0.78, medium: 0.68, low: 0.58 }\nconst DEFAULT_THRESHOLD = SIMILAR_THRESHOLDS.medium\nconst DEFAULT_LIMIT = 10\n\n// parseDSL returns { mode, specs, threshold, limit }\n//\n// mode: 'similar' if SIMILAR: is the first meaningful line (ambient auto-run),\n// 'search' otherwise (interactive search form).\n//\n// Ward's convention: ALL-CAPS keyword as first word signals a mode switch.\n// Placing SIMILAR: first makes the item ambient; placing domain specs first\n// (or leaving text empty) keeps it as an interactive search form.\n\nconst parseDSL = text => {\n const specs = []\n const rosterRefs = [] // ROSTER site/slug \u2014 roster pages whose sites join the scope\n const farms = [] // FARM domain \u2014 peer farms asked to continue the search\n let threshold = null\n let limit = null\n let mode = 'search' // default: interactive search form\n let live = false // default: cache results in localStorage\n let subject = false // SUBJECT modifier: act on the previous lineup page\n let force = false // BUILD mode: re-embed even when index is fresh\n let ghostUrl = null // GHOST mode: page-json URL to open as a ghost page\n let label = null // BUTTON: custom button caption (GHOST / BUILD modes)\n\n // Match a keyword at the start of a line (case-insensitive), requiring it to\n // be followed by end-of-string, whitespace, or colon \u2014 not by more word chars.\n // This prevents domain specs like \"similarity.example.com\" matching SIMILAR.\n const isCmd = (upper, kw) => upper === kw || (upper.startsWith(kw) && /^[\\s:]/.test(upper.slice(kw.length)))\n // Extract the value after the keyword, tolerating optional colon and whitespace.\n // Returns '' for bare commands (e.g. \"SIMILAR\" alone), callers use their default.\n const val = (line, kw) => line.slice(kw.length).replace(/^\\s*:?\\s*/, '').trim()\n\n for (const raw of text.split('\\n')) {\n const line = raw.trim()\n if (!line || line.startsWith('#')) continue\n\n const upper = line.toUpperCase()\n if (isCmd(upper, 'LIVE')) { live = true; continue }\n if (isCmd(upper, 'SUBJECT')) { subject = true; continue }\n if (isCmd(upper, 'AUTHOR')) {\n if (!specs.length && mode === 'search') mode = 'author'\n continue\n }\n if (isCmd(upper, 'REPORT')) {\n if (mode === 'search') mode = 'report'\n continue\n }\n if (isCmd(upper, 'KEYWORD')) {\n if (mode === 'search') mode = 'keyword'\n continue\n }\n if (isCmd(upper, 'SITES')) {\n if (mode === 'search') mode = 'sites'\n continue\n }\n if (isCmd(upper, 'BUILD')) {\n if (mode === 'search') mode = 'build'\n continue\n }\n if (isCmd(upper, 'FORCE')) { force = true; continue }\n if (isCmd(upper, 'GHOST')) {\n ghostUrl = val(line, 'GHOST')\n if (mode === 'search') mode = 'ghost'\n continue\n }\n if (isCmd(upper, 'BUTTON')) { label = val(line, 'BUTTON'); continue }\n if (isCmd(upper, 'ROSTER')) {\n const ref = val(line, 'ROSTER')\n if (ref) rosterRefs.push(ref)\n continue\n }\n if (isCmd(upper, 'FARM')) {\n const peer = val(line, 'FARM')\n if (peer) farms.push(peer)\n continue\n }\n if (isCmd(upper, 'LIST')) {\n if (!specs.length && mode === 'search') mode = 'list'\n continue\n }\n if (isCmd(upper, 'SIMILAR')) {\n const level = val(upper, 'SIMILAR').toLowerCase()\n threshold = SIMILAR_THRESHOLDS[level] || DEFAULT_THRESHOLD // '' \u2192 medium\n if (!specs.length && mode === 'search') mode = 'similar'\n continue\n }\n if (isCmd(upper, 'THRESHOLD')) {\n const tv = val(line, 'THRESHOLD')\n threshold = SIMILAR_THRESHOLDS[tv.toLowerCase()] ?? (parseFloat(tv) || DEFAULT_THRESHOLD)\n continue\n }\n if (isCmd(upper, 'LIMIT')) {\n limit = parseInt(val(line, 'LIMIT')) || DEFAULT_LIMIT // '' \u2192 10\n continue\n }\n // Anything else is a domain spec (glob, explicit domain, or scope keyword)\n specs.push(['PUBLIC', 'LOCAL', 'PRIVATE', 'GALAXY'].includes(upper) ? upper : line)\n }\n\n return {\n mode,\n specs,\n rosterRefs,\n farms,\n threshold: threshold ?? DEFAULT_THRESHOLD,\n limit: limit ?? DEFAULT_LIMIT,\n live,\n subject,\n force,\n ghostUrl,\n label,\n thresholdSet: threshold !== null, // explicit THRESHOLD/SIMILAR in the DSL\n }\n}\n\nconst isGlob = spec => spec.includes('*') || spec.includes('?')\n\n// Scope keywords expand server-side: PUBLIC (Nextcloud mirror farms),\n// LOCAL (primary farm), PRIVATE (public domains with restricted: true),\n// GALAXY (off-farm federation sites indexed into the galaxy tree)\nconst isScope = spec => spec === 'PUBLIC' || spec === 'LOCAL' || spec === 'PRIVATE' ||\n spec === 'GALAXY'\n\nexport { parseDSL, isGlob, isScope, SIMILAR_THRESHOLDS, DEFAULT_THRESHOLD, DEFAULT_LIMIT }\n", "// wiki-plugin-similarity \u2014 turning DSL specs into a concrete list of domains\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\nimport { isGlob, isScope } from './dsl.js'\n\n// \u2500\u2500 Slug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst slugify = title => title.toLowerCase().replace(/\\s+/g, '-').replace(/[^a-z0-9-]/g, '')\n\n// \u2500\u2500 Domain resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst domainCache = new Map()\n\nconst resolveDomainsForSpec = async (spec, origin) => {\n if (domainCache.has(spec)) return domainCache.get(spec)\n const url = `${origin}/system/indexed-domains.json?pattern=${encodeURIComponent(spec)}`\n const res = await fetch(url)\n if (!res.ok) throw new Error(`indexed-domains failed: ${res.status}`)\n const list = await res.json()\n domainCache.set(spec, list)\n return list\n}\n\nconst resolveDomains = async (specs, origin) => {\n if (!specs.length) specs = [window.location.hostname]\n const seen = new Set()\n const result = []\n for (const spec of specs) {\n if (spec === '*' || isGlob(spec) || isScope(spec)) {\n for (const item of await resolveDomainsForSpec(spec, origin)) {\n if (!seen.has(item.domain)) { seen.add(item.domain); result.push(item) }\n }\n } else if (!seen.has(spec)) {\n seen.add(spec); result.push({ domain: spec, page_count: null })\n }\n }\n return result\n}\n\n// \u2500\u2500 Roster resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// ROSTER site/slug resolves a roster page into domain names, following the\n// roster plugin's own line semantics: bare domains are sites; category and\n// blank lines are skipped; nested `ROSTER site/slug` includes another roster\n// page; `REFERENCES site/slug` collects the .site of a page's reference items.\n// Includes are followed transitively with a visited-set loop guard.\n\nconst SITE_LINE = /^([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+|localhost)(:\\d+)?$/\nconst ROSTER_LINE = /^ROSTER ([A-Za-z0-9.\\-:]+\\/[a-z0-9-]+)$/\nconst REFS_LINE = /^REFERENCES ([A-Za-z0-9.\\-:]+\\/[a-z0-9-]+)$/\n\nconst fetchPage = async ref => { // ref = site/slug\n const i = ref.indexOf('/')\n const res = await fetch(`//${ref.slice(0, i)}/${ref.slice(i + 1)}.json`)\n if (!res.ok) throw new Error(`roster page ${ref} failed: ${res.status}`)\n return res.json()\n}\n\nconst resolveRoster = async (ref, out, visited) => {\n if (visited.has(ref)) return\n visited.add(ref)\n let page\n try { page = await fetchPage(ref) } catch (e) { console.warn(e.message); return }\n for (const item of page.story || []) {\n if (item.type !== 'roster') continue\n for (const raw of (item.text || '').split(/\\r?\\n/)) {\n const line = raw.trim()\n if (!line) continue\n const site = line.match(SITE_LINE)\n if (site) { out.add(site[0]); continue }\n const nested = line.match(ROSTER_LINE)\n if (nested) { await resolveRoster(nested[1], out, visited); continue }\n const refs = line.match(REFS_LINE)\n if (refs) {\n try {\n const refPage = await fetchPage(refs[1])\n for (const it of refPage.story || []) {\n if (it.type === 'reference' && it.site) out.add(it.site)\n }\n } catch (e) { console.warn(e.message) }\n }\n // anything else is a category name \u2014 skipped\n }\n }\n}\n\nconst resolveRosters = async rosterRefs => {\n const out = new Set()\n const visited = new Set()\n for (const ref of rosterRefs) await resolveRoster(ref, out, visited)\n return [...out]\n}\n\n// Effective specs: DSL specs plus any domains contributed by ROSTER lines.\nconst effectiveSpecs = async (specs, rosterRefs) =>\n rosterRefs.length ? [...specs, ...await resolveRosters(rosterRefs)] : specs\n\nexport { slugify, resolveDomains, resolveRosters, effectiveSpecs, SITE_LINE, ROSTER_LINE, REFS_LINE }\n", "// wiki-plugin-similarity \u2014 page vectors, embedding, and the cosine scan over them\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\nimport { resolveDomains } from './scope.js'\n\n// \u2500\u2500 Vector loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst vectorCache = new Map()\n\n// Route vector requests through the current wiki's plugin server. This keeps\n// public HTTPS pages same-origin, avoids CORS failures, and lets the server read\n// indices from its configured farm roots.\nconst vectorUrl = domain =>\n `${window.location.origin}/system/semantic-vectors.json?domain=${encodeURIComponent(domain)}`\n\nconst loadVectors = async domain => {\n if (vectorCache.has(domain)) return vectorCache.get(domain)\n const res = await fetch(vectorUrl(domain))\n if (!res.ok) return []\n const data = await res.json()\n vectorCache.set(domain, data)\n return data\n}\n\n// \u2500\u2500 Embedding \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// POST, never GET: page-length text in a query string overflows Node's header\n// limit and dies with 431 before any handler runs (server \u2265 0.11.0).\nconst getEmbedding = async (text, origin) => {\n const res = await fetch(`${origin}/system/embed.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text }),\n })\n if (!res.ok) throw new Error(`embed failed: ${res.status}`)\n return (await res.json()).vector\n}\n\n// Look up an existing page vector from the current domain's cached index.\n// Returns the float[] vector if found, null otherwise.\nconst lookupPageVector = async (slug, domain) => {\n const pages = await loadVectors(domain)\n const entry = pages.find(p => p.slug === slug)\n return entry ? entry.vector : null\n}\n// \u2500\u2500 Cosine search \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst cosineScan = (queryVec, domainEntries, { threshold, limit, excludeSlug, excludeDomain }) => {\n const results = []\n for (const { domain, pages } of domainEntries) {\n for (const { slug, title, vector } of pages) {\n if (slug === excludeSlug && domain === excludeDomain) continue\n let dot = 0\n for (let i = 0; i < queryVec.length; i++) dot += queryVec[i] * vector[i]\n if (dot >= threshold) results.push({ domain, slug, title, score: dot })\n }\n }\n results.sort((a, b) => b.score - a.score)\n return results.slice(0, limit)\n}\n\n// \u2500\u2500 Shared domain loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst loadDomainEntries = async (specs, origin) => {\n const domains = await resolveDomains(specs, origin)\n const entries = await Promise.all(\n domains.map(async ({ domain }) => ({ domain, pages: await loadVectors(domain) }))\n )\n return entries.filter(e => e.pages.length > 0)\n}\n\nexport { loadVectors, vectorUrl, getEmbedding, lookupPageVector, cosineScan, loadDomainEntries }\n", "// wiki-plugin-similarity \u2014 SUBJECT \u2014 the page an item acts on\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Subject resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// SUBJECT makes an item act on the page BEFORE its own in the lineup \u2014 the\n// host a tool page was opened beside \u2014 falling back to the containing page so\n// a tool page opened alone still works (and announces the fallback).\n// The page div's id IS the slug (possibly _rev-suffixed on a historical view);\n// data('data') carries the full raw page JSON; data('site') is set only on\n// remote pages. `text` is title + opening prose, capped: the BGE-small\n// embedder truncates around 512 tokens, so more would be discarded anyway.\n\nconst resolveSubject = div => {\n const $self = div.parents('.page:first')\n const $host = $self.prev('.page')\n const $page = $host.length ? $host : $self\n const slug = ($page.attr('id') || '').split('_rev')[0]\n const site = $page.data('site') || window.location.hostname\n const data = $page.data('data') || {}\n const title = data.title || $page.find('.title').text().trim() || slug\n const text = [title, ...(data.story || [])\n .filter(i => i.type === 'markdown' || i.type === 'paragraph')\n .map(i => (i.text || '').trim()).filter(Boolean)].join('\\n').slice(0, 2000)\n return { slug, site, title, text, isSelf: !$host.length }\n}\n\nconst subjectNote = s =>\n `Subject: ${s.title}${s.isSelf ? ' (this page)' : ` @ ${s.site}`}`\n\nexport { resolveSubject, subjectNote }\n", "// wiki-plugin-similarity \u2014 per-item result cache in localStorage\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Result cache (localStorage) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Cache is keyed by item id. Invalidated when item.text changes (DSL edited).\n// LIVE mode bypasses the cache entirely.\n\nconst cacheKey = id => `sim-cache-${id}`\n\nconst readCache = item => {\n try {\n const c = JSON.parse(localStorage.getItem(cacheKey(item.id)) || 'null')\n return c?.text === (item.text || '') ? c : null\n } catch { return null }\n}\n\nconst writeCache = (item, data) => {\n try {\n localStorage.setItem(cacheKey(item.id), JSON.stringify({\n text: item.text || '',\n ts: Date.now(),\n ...data,\n }))\n } catch { /* storage unavailable or full */ }\n}\n\nconst cacheAge = ts => {\n const s = Math.floor((Date.now() - ts) / 1000)\n if (s < 60) return `${s}s ago`\n if (s < 3600) return `${Math.floor(s / 60)}m ago`\n if (s < 86400) return `${Math.floor(s / 3600)}h ago`\n return `${Math.floor(s / 86400)}d ago`\n}\n\nexport { readCache, writeCache, cacheAge }\n", "// wiki-plugin-similarity \u2014 item styles and the site flag\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Styles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst STYLES = `\n .sim-form { display:flex; gap:6px; margin-bottom:8px; }\n .sim-input { flex:1; padding:6px 8px; font-size:14px; border:1px solid #ccc; border-radius:3px; }\n .sim-btn { padding:6px 14px; background:#c4561d; color:white; border:none;\n border-radius:3px; cursor:pointer; font-size:14px; }\n .sim-btn:disabled { opacity:0.5; cursor:not-allowed; }\n .sim-status { font-size:12px; color:#888; margin-bottom:6px; min-height:16px; }\n .sim-results { margin-top:4px; }\n .sim-result { display:flex; align-items:center; gap:8px; padding:3px 0;\n border-bottom:1px solid #f0f0f0; }\n .sim-flag { width:16px; height:16px; vertical-align:middle; margin-right:4px; }\n .sim-link { font-size:14px; color:#406; flex:1; }\n .sim-domain { font-size:11px; color:#999; }\n .similar-results h3, .sim-list h3 { margin:4px 0 6px; font-size:14px; color:#555; }\n .similar-results ul { margin:0; padding-left:18px; }\n .similar-results li { font-size:14px; padding:2px 0; }\n .similar-results .sim-domain { margin-left:6px; }\n .sim-count { font-size:12px; color:#888; margin:4px 0 0; }\n .sim-list table { border-collapse:collapse; width:100%; font-size:13px; }\n .sim-list th { text-align:left; font-size:11px; color:#888; padding:2px 8px 4px 0;\n border-bottom:1px solid #ddd; }\n .sim-list td { padding:3px 8px 3px 0; border-bottom:1px solid #f0f0f0; vertical-align:middle; }\n .sim-list td:last-child { text-align:right; color:#999; font-size:11px; }\n .sim-list .sim-flag { margin-right:6px; }\n`\n\nconst siteFlag = (domain, score) =>\n `<img class=\"sim-flag remote\" src=\"${window.wiki.site(domain).flag()}\"\n title=\"${domain} \u2014 score ${score.toFixed(3)}\"\n data-site=\"${domain}\">`\n\nexport { STYLES, siteFlag }\n", "// wiki-plugin-similarity\n//\n// One item type: similarity\n//\n// DSL in item.text (newline-separated lines):\n// * all indexed domains on this server\n// david.* glob pattern\n// *.fish glob pattern\n// david.hitchhikers.earth explicit domain name\n// # comment ignored\n// LIST list indexed domains (mode directive)\n// SIMILAR: high threshold preset AND ambient mode trigger\n// SUBJECT modifier: act on the PREVIOUS page in the lineup\n// (the host a tool page was opened beside; falls\n// back to the containing page when none)\n// THRESHOLD: 0.72 exact cosine threshold (overrides SIMILAR:)\n// LIMIT: 8 max results shown (default 10)\n// ROSTER site/slug add the sites of a roster page to the scope\n// FARM other.farm.tld ask a peer farm to continue the search (experimental)\n//\n// Mode is determined by the FIRST meaningful line (Ward's ALL-CAPS convention):\n// LIST \u2192 show a table of all indexed domains and their page counts;\n// optional glob patterns on subsequent lines filter the list\n// SIMILAR: \u2192 ambient mode \u2014 automatically find pages similar to this page\n// REPORT \u2192 server-side ranked/bundled semantic report (ghost page)\n// KEYWORD \u2192 galactic MiniSearch over live site-index.json files (ghost page)\n// SITES \u2192 which site should this page go on? \u2014 per-domain aggregation of\n// the page-vector scan (ghost page)\n// (other) \u2192 search form mode \u2014 user types a query, results appear\n//\n// Server endpoints required (all same-origin, served by this plugin's server\n// component \u2014 works on any host, including the public farm):\n// GET /system/indexed-domains.json?pattern=glob1,glob2\n// GET /system/semantic-vectors.json?domain=\n// POST /system/embed.json {text}\n// POST /system/search-report.json\n// POST /system/site-report.json\n// GET /system/farm-search.json?q=&pattern=&limit=\n// GET /system/build-index.json?domains=&force=\n\nimport { parseDSL, DEFAULT_LIMIT } from './dsl.js'\nimport { slugify, effectiveSpecs, resolveDomains } from './scope.js'\nimport { loadVectors, getEmbedding, lookupPageVector, cosineScan, loadDomainEntries } from './vectors.js'\nimport { resolveSubject, subjectNote } from './subject.js'\nimport { readCache, writeCache, cacheAge } from './cache.js'\nimport { STYLES, siteFlag } from './styles.js'\n\n// \u2500\u2500 similarity item \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst simLink = (domain, slug, title, score) =>\n `<a class=\"sim-link\" data-title=\"${title}\" data-slug=\"${slug}\" data-site=\"${domain}\" href=\"#\">` +\n `${siteFlag(domain, score)} ${title}</a>`\n\nexport const emit = (div, item) => {\n const { mode, specs, threshold, limit, force, ghostUrl, label } = parseDSL(item?.text || '')\n if (mode === 'ghost') {\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <button class=\"sim-btn\">${label || 'Open'}</button>\n </div>\n <div class=\"sim-status\"></div>\n </div>`)\n } else if (mode === 'build') {\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <button class=\"sim-btn\">${label || `Index ${specs.length ? specs.join(', ') : '*'}${force ? ' (force)' : ''}`}</button>\n </div>\n <div class=\"sim-status\"></div>\n </div>`)\n } else if (mode === 'list') {\n const label = specs.length ? specs.join(', ') : '*'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-status\">Loading indexed domains (${label})\u2026</div>\n <div class=\"sim-list\"></div>\n </div>`)\n } else if (mode === 'similar') {\n const label = specs.length ? specs.join(', ') : 'current domain'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-status\">Finding similar pages across ${label}\u2026</div>\n <div class=\"sim-results\"></div>\n </div>`)\n } else if (mode === 'author' || mode === 'report' || mode === 'keyword' || mode === 'sites') {\n const label = specs.length ? specs.join(', ') : '(current domain)'\n const btnLabel = mode === 'report' ? 'Report' : mode === 'keyword' ? 'Keyword'\n : mode === 'sites' ? 'Sites' : 'Author'\n const hint = mode === 'sites' ? 'Where should this page go? Title + first paragraph\u2026'\n : 'Search wiki pages\u2026'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <input class=\"sim-input\" type=\"text\" placeholder=\"${hint}\" />\n <button class=\"sim-btn\">${btnLabel}</button>\n </div>\n <div class=\"sim-status\">Domains: ${label}</div>\n <div class=\"sim-results\"></div>\n </div>`)\n } else {\n const label = specs.length ? specs.join(', ') : '(current domain)'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <input class=\"sim-input\" type=\"text\" placeholder=\"Search wiki pages\u2026\" />\n <button class=\"sim-btn\">Search</button>\n </div>\n <div class=\"sim-status\">Domains: ${label}</div>\n <div class=\"sim-results\"></div>\n </div>`)\n }\n}\n\nexport const bind = (div, item) => {\n const { mode, specs, rosterRefs, farms, threshold, limit, live, subject: subjectFlag,\n force, ghostUrl, thresholdSet } = parseDSL(item?.text || '')\n const origin = window.location.origin\n const status = div.find('.sim-status')[0]\n // The subject depends on where in the lineup this page was opened, so\n // cached results from one host must never replay beside another.\n const subject = subjectFlag ? resolveSubject(div) : null\n const cache = (live || subject) ? null : readCache(item)\n // Scope = DSL specs plus roster-page domains (resolved once, shared by modes)\n const specsP = effectiveSpecs(specs, rosterRefs)\n // Seed params for the server report routes \u2014 the stored page vector wins\n // server-side; text is the fallback for remote or unindexed subjects.\n const seedParams = () => subject ? {\n seed: { site: subject.site, slug: subject.slug },\n text: subject.text,\n excludePage: { site: subject.site, slug: subject.slug },\n } : {}\n\n // Standardised pre-search status: what will run, over how much, with what config.\n // e.g. \"Report ready \u2014 18,583 pages across 267 domains \u00B7 threshold 0.68 \u00B7 limit 20 \u00B7 LIVE\"\n const configSummary = (verb, pages, nDomains) => {\n const parts = [`${verb} \u2014 ${pages.toLocaleString()} pages across ${nDomains} domains`]\n if (thresholdSet) parts.push(`threshold ${threshold}`)\n parts.push(`limit ${limit}`)\n if (live) parts.push('LIVE')\n return parts.join(' \u00B7 ')\n }\n\n div.on('dblclick', e => {\n if ($(e.target).closest('.sim-input').length) return\n window.wiki.textEditor(div, item)\n })\n div.on('click', '.sim-link', function (e) {\n e.preventDefault()\n const $a = $(this)\n // shift-click appends at the end of the lineup instead of truncating after this page\n const $page = e.shiftKey ? null : div.parents('.page')\n window.wiki.doInternalLink($a.data('title'), $page, $a.data('site'))\n })\n\n const scopeLabel = !specs.length || (specs.length === 1 && specs[0] === '*')\n ? 'on farm'\n : specs.length === 1 ? `on ${specs[0]}` : 'in domains'\n\n const cacheNote = ts => ts ? ` \u00B7 cached ${cacheAge(ts)}` : ''\n\n if (mode === 'list') {\n const listDiv = div.find('.sim-list')[0]\n\n const renderList = (domains, ts) => {\n const totalPages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n status.style.display = 'none'\n listDiv.innerHTML = `<h3>Indexed Farm Domains</h3>\n <table>\n <tr><th>Domain</th><th>Pages</th></tr>\n ${domains.map(({ domain, page_count }) => `\n <tr>\n <td><img class=\"sim-flag remote\" src=\"${window.wiki.site(domain).flag()}\"\n title=\"${domain}\" data-site=\"${domain}\"> ${domain}</td>\n <td>${page_count != null ? page_count.toLocaleString() : '\u2014'}</td>\n </tr>`).join('')}\n </table>\n <p class=\"sim-count\">${domains.length} domains \u2014 ${totalPages.toLocaleString()} pages${cacheNote(ts)}</p>`\n }\n\n if (cache?.domains) {\n renderList(cache.domains, cache.ts)\n } else {\n ;(async () => {\n try {\n const eff = await specsP\n const patterns = eff.length ? eff.join(',') : '*'\n const url = `${origin}/system/indexed-domains.json?pattern=${encodeURIComponent(patterns)}&limit=${limit}`\n const res = await fetch(url)\n if (!res.ok) throw new Error(`indexed-domains failed: ${res.status}`)\n const domains = await res.json()\n if (!domains.length) { status.textContent = 'No indexed domains found'; return }\n renderList(domains, null)\n writeCache(item, { domains })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n }\n })()\n }\n\n } else if (mode === 'similar') {\n const results = div.find('.sim-results')[0]\n\n const renderScored = (scored, ts) => {\n if (!scored.length) {\n status.textContent = `No similar pages found above threshold ${threshold}`\n return\n }\n results.innerHTML = `<h3>Similar Pages</h3><ul>${\n scored.map(({ domain, slug, title, score }) =>\n `<li>${simLink(domain, slug, title, score)}</li>`).join('')\n }</ul><p class=\"sim-count\">${scored.length} found ${scopeLabel}${cacheNote(ts)}</p>`\n status.style.display = 'none'\n }\n\n if (cache?.scored) {\n renderScored(cache.scored, cache.ts)\n } else {\n ;(async () => {\n try {\n // SUBJECT: act on the previous lineup page; otherwise this page.\n const $page = div.parents('.page')\n const s = subject || (() => {\n const pageTitle = $page.find('.title').text().trim() || document.title\n return { slug: slugify(pageTitle), site: window.location.hostname,\n title: pageTitle, text: null, isSelf: true }\n })()\n\n const domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(s)} \u00B7 ` : '') +\n `Searching ${total.toLocaleString()} pages\u2026`\n\n let qVec = await lookupPageVector(s.slug, s.site)\n if (!qVec) {\n status.textContent = 'Embedding page (not yet indexed)\u2026'\n const pageText = s.text || $page.find('.item')\n .map((_, el) => $(el).text().trim()).get().filter(Boolean).join('\\n')\n qVec = await getEmbedding(pageText || s.title, origin)\n }\n\n const scored = cosineScan(qVec, domainEntries, {\n threshold, limit, excludeSlug: s.slug, excludeDomain: s.site,\n })\n renderScored(scored, null)\n if (subject) { // keep the subject visible above the results\n status.textContent = subjectNote(s)\n status.style.display = ''\n }\n if (scored.length && !subject) writeCache(item, { scored })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n }\n })()\n }\n\n } else if (mode === 'ghost') {\n // Ghost mode \u2014 fetch page-json from any URL and open it as a ghost page\n const btn = div.find('.sim-btn')[0]\n\n const doGhost = async () => {\n if (!ghostUrl) { status.textContent = 'No URL \u2014 GHOST needs a page-json URL'; return }\n btn.disabled = true\n status.textContent = 'Fetching\u2026'\n try {\n const res = await fetch(ghostUrl)\n if (!res.ok) throw new Error(`fetch failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = ''\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doGhost)\n\n } else if (mode === 'build') {\n // Build mode \u2014 trigger a semantic index build; result opens as a ghost page\n const btn = div.find('.sim-btn')[0]\n\n const doBuild = async () => {\n btn.disabled = true\n status.textContent = 'Building index\u2026 (may take a while for large scopes)'\n try {\n const domains = encodeURIComponent((specs.length ? specs : ['*']).join(','))\n const res = await fetch(\n `${origin}/system/build-index.json?domains=${domains}&force=${force ? 1 : 0}`)\n if (res.status === 501) {\n const body = await res.json().catch(() => ({}))\n throw new Error(body.hint || 'indexing runs on the farm indexer, not this server')\n }\n if (!res.ok) throw new Error(`build-index failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = ''\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doBuild)\n\n } else if (mode === 'report') {\n // Report mode \u2014 server-side ranked/bundled search, opens result as ghost page\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n let readyLine = `Domains: ${specs.length ? specs.join(', ') : '*'}`\n\n // SUBJECT: the host page IS the query \u2014 prefill its title (editable) and\n // seed the server search with its stored vector.\n if (subject && !input.value) input.value = subject.title\n\n // Preload the lightweight domain listing (counts only, no vectors) so the\n // status line shows scope and config before any search is issued.\n ;(async () => {\n try {\n const eff = await specsP\n const domains = await resolveDomains(eff.length ? eff : ['*'], origin)\n const pages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n readyLine = configSummary('Report ready', pages, domains.length)\n if (farms.length) readyLine += ` \u00B7 +${farms.length} peer farm${farms.length > 1 ? 's' : ''}`\n if (subject) readyLine = `${subjectNote(subject)} \u00B7 ${readyLine}`\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Domain listing unavailable: ${e.message}`\n }\n })()\n\n const doReport = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = farms.length ? 'Generating report (asking peer farms)\u2026' : 'Generating report\u2026'\n try {\n const eff = await specsP\n // A hand-edited query is a new question \u2014 drop the page seed then.\n const seeded = subject && query === subject.title ? seedParams() : {}\n const body = { query, domains: eff.length ? eff : ['*'], limit, live, ...seeded }\n if (farms.length) body.farms = farms\n if (thresholdSet) body.threshold = threshold\n const res = await fetch(`${origin}/system/search-report.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw new Error(`search-report failed: ${res.status}`)\n const page = await res.json()\n const pageObj = window.wiki.newPage(page)\n window.wiki.showResult(pageObj, { $page: div.parents('.page') })\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doReport)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doReport() })\n\n } else if (mode === 'sites') {\n // Sites mode \u2014 which site should this page go on? Server aggregates the\n // page-vector scan per domain; result opens as a ghost page.\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n let readyLine = `Domains: ${specs.length ? specs.join(', ') : '*'}`\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n const eff = await specsP\n const domains = await resolveDomains(eff.length ? eff : ['*'], origin)\n const pages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n readyLine = configSummary('Site report ready', pages, domains.length)\n if (subject) readyLine = `${subjectNote(subject)} \u00B7 ${readyLine}`\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Domain listing unavailable: ${e.message}`\n }\n })()\n\n const doSites = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = 'Ranking sites\u2026'\n try {\n const eff = await specsP\n const seeded = subject && query === subject.title ? seedParams() : {}\n const res = await fetch(`${origin}/system/site-report.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ query, domains: eff.length ? eff : ['*'], limit, ...seeded }),\n })\n if (!res.ok) throw new Error(`site-report failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doSites)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doSites() })\n\n } else if (mode === 'keyword') {\n // Keyword mode \u2014 galactic MiniSearch: the server reads each site's own\n // per-edit site-index.json; result opens as a ghost page.\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n\n // SUBJECT: keyword search wants words, not vectors \u2014 the host title is\n // the prewired query (editable), finding forks and namesakes alike.\n if (subject && !input.value) input.value = subject.title\n\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n `Keyword search ready \u2014 domains: ${specs.length ? specs.join(', ') : '*'} \u00B7 limit ${limit}`\n\n const doKeyword = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = 'Searching live site indexes\u2026'\n try {\n const eff = await specsP\n const pattern = encodeURIComponent((eff.length ? eff : ['*']).join(','))\n const farmsParam = farms.length ? `&farms=${encodeURIComponent(farms.join(','))}` : ''\n const res = await fetch(\n `${origin}/system/farm-search.json?q=${encodeURIComponent(query)}&pattern=${pattern}&limit=${limit}${farmsParam}`)\n if (!res.ok) throw new Error(`farm-search failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = `Keyword search ready \u2014 domains: ${specs.length ? specs.join(', ') : '*'} \u00B7 limit ${limit}`\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doKeyword)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doKeyword() })\n\n } else if (mode === 'author') {\n // Author mode \u2014 same search form but creates a ghost page from results\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n const results = div.find('.sim-results')[0]\n let domainEntries = null\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n if (!cache) status.textContent = 'Resolving domains\u2026'\n domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n configSummary('Author ready', total, domainEntries.length)\n } catch (e) {\n status.textContent = `Load error: ${e.message}`\n }\n })()\n\n const doAuthor = async () => {\n const query = input.value.trim()\n if (!query || !domainEntries) return\n btn.disabled = true\n status.textContent = 'Embedding query\u2026'\n results.innerHTML = ''\n try {\n const qVec = await getEmbedding(query, origin)\n const scored = cosineScan(qVec, domainEntries,\n { threshold, limit, excludeSlug: null, excludeDomain: null })\n\n // Unique titles for wiki-link list\n const seenTitles = new Set()\n const uniqueTitles = []\n for (const { title } of scored) {\n if (!seenTitles.has(title)) { seenTitles.add(title); uniqueTitles.push(title) }\n }\n\n const hexId = () => Math.floor(Math.random() * 0xffffffffffffffff).toString(16).padStart(16, '0')\n const primaryLines = uniqueTitles.map(t => `- [[${t}]]`).join('\\n')\n\n const story = [\n { type: 'markdown', id: hexId(), text: `# Similar Pages\\n\\n${primaryLines}` },\n { type: 'markdown', id: hexId(), text: '# Reference Links' },\n ...scored.map(({ domain, slug, title, score }) => ({\n type: 'reference', id: hexId(), site: domain, slug, title,\n text: `score ${score.toFixed(3)}`,\n })),\n ]\n\n const pageObj = window.wiki.newPage({ title: `${query} Results`, story, journal: [] })\n window.wiki.showResult(pageObj, { $page: div.parents('.page') })\n\n status.textContent = `${scored.length} pages found`\n writeCache(item, { scored, query })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doAuthor)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doAuthor() })\n\n } else {\n // Search form mode\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n const results = div.find('.sim-results')[0]\n let domainEntries = null\n\n // Show cached results immediately while domains preload in background\n if (cache?.scored) {\n input.value = cache.query || ''\n results.innerHTML = cache.scored.map(({ domain, slug, title, score }) =>\n `<div class=\"sim-result\">${simLink(domain, slug, title, score)}</div>`).join('') +\n `<p class=\"sim-count\">Top ${cache.scored.length} for \"${cache.query || ''}\"${cacheNote(cache.ts)}</p>`\n status.textContent = ''\n }\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n if (!cache) status.textContent = 'Resolving domains\u2026'\n domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n configSummary('Search ready', total, domainEntries.length)\n } catch (e) {\n status.textContent = `Load error: ${e.message}`\n }\n })()\n\n const doSearch = async () => {\n const query = input.value.trim()\n if (!query || !domainEntries) return\n btn.disabled = true\n status.textContent = 'Embedding query\u2026'\n results.innerHTML = ''\n try {\n const qVec = await getEmbedding(query, origin)\n const scored = cosineScan(qVec, domainEntries,\n { threshold, limit, excludeSlug: null, excludeDomain: null })\n results.innerHTML = scored.map(({ domain, slug, title, score }) =>\n `<div class=\"sim-result\">${simLink(domain, slug, title, score)}</div>`).join('') +\n `<p class=\"sim-count\">Top ${scored.length} for \"${query}\"</p>`\n status.textContent = ''\n writeCache(item, { scored, query })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doSearch)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doSearch() })\n }\n}\n\n// \u2500\u2500 Register item type with the wiki \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nif (typeof window !== 'undefined') {\n window.plugins = window.plugins || {}\n window.plugins.similarity = { emit, bind }\n}\n"],
|
|
5
|
-
"mappings": ";MAKA,IAAMA,EAAqB,CAAE,KAAM,IAAM,OAAQ,IAAM,IAAK,GAAK,EAC3DC,EAAqBD,EAAmB,OACxCE,EAAqB,GAWrBC,EAAWC,GAAQ,CACvB,IAAMC,EAAU,CAAC,EACXC,EAAa,CAAC,EACdC,EAAU,CAAC,EACbC,EAAY,KACZC,EAAY,KACZC,EAAY,SACZC,EAAY,GACZC,EAAY,GACZC,EAAY,GACZC,EAAY,KACZC,EAAY,KAKVC,EAAS,CAACC,EAAOC,IAAOD,IAAUC,GAAOD,EAAM,WAAWC,CAAE,GAAK,SAAS,KAAKD,EAAM,MAAMC,EAAG,MAAM,CAAC,EAGrGC,EAAS,CAACC,EAAMF,IAAOE,EAAK,MAAMF,EAAG,MAAM,EAAE,QAAQ,YAAa,EAAE,EAAE,KAAK,EAEjF,QAAWG,KAAOjB,EAAK,MAAM;AAAA,CAAI,EAAG,CAClC,IAAMgB,EAAOC,EAAI,KAAK,EACtB,GAAI,CAACD,GAAQA,EAAK,WAAW,GAAG,EAAG,SAEnC,IAAMH,EAAQG,EAAK,YAAY,EAC/B,GAA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C,EACpC,OAAO,QAAQ,WAAa,CAAE,KAAA7F,GAAM,KAAAc,EAAK",
|
|
6
|
-
"names": ["SIMILAR_THRESHOLDS", "DEFAULT_THRESHOLD", "DEFAULT_LIMIT", "parseDSL", "text", "specs", "rosterRefs", "farms", "threshold", "limit", "mode", "live", "subject", "force", "ghostUrl", "label", "isCmd", "upper", "kw", "val", "line", "raw", "ref", "peer", "level", "tv", "isGlob", "spec", "isScope", "slugify", "title", "domainCache", "resolveDomainsForSpec", "spec", "origin", "url", "res", "list", "resolveDomains", "specs", "seen", "result", "isGlob", "isScope", "item", "SITE_LINE", "ROSTER_LINE", "REFS_LINE", "fetchPage", "ref", "i", "resolveRoster", "out", "visited", "page", "e", "raw", "line", "site", "nested", "refs", "refPage", "it", "resolveRosters", "rosterRefs", "effectiveSpecs", "vectorCache", "vectorUrl", "domain", "loadVectors", "res", "data", "getEmbedding", "text", "origin", "lookupPageVector", "slug", "entry", "cosineScan", "queryVec", "domainEntries", "threshold", "limit", "excludeSlug", "excludeDomain", "results", "pages", "title", "vector", "dot", "i", "a", "b", "loadDomainEntries", "specs", "domains", "resolveDomains", "e", "resolveSubject", "div", "$self", "$host", "$page", "slug", "site", "data", "title", "text", "i", "subjectNote", "s", "cacheKey", "id", "readCache", "item", "c", "writeCache", "data", "cacheAge", "ts", "s", "STYLES", "siteFlag", "domain", "score", "simLink", "domain", "slug", "title", "score", "siteFlag", "emit", "div", "item", "mode", "specs", "threshold", "limit", "force", "ghostUrl", "label", "parseDSL", "STYLES", "btnLabel", "hint", "bind", "rosterRefs", "farms", "live", "subjectFlag", "thresholdSet", "origin", "status", "subject", "resolveSubject", "cache", "readCache", "specsP", "effectiveSpecs", "seedParams", "configSummary", "verb", "pages", "nDomains", "parts", "e", "$a", "$page", "scopeLabel", "cacheNote", "ts", "cacheAge", "listDiv", "renderList", "domains", "totalPages", "d", "page_count", "eff", "patterns", "url", "res", "writeCache", "results", "renderScored", "scored", "s", "pageTitle", "slugify", "domainEntries", "loadDomainEntries", "total", "
|
|
4
|
+
"sourcesContent": ["// wiki-plugin-similarity \u2014 the item's line-oriented DSL: parse it, and classify a spec\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 DSL Parser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst SIMILAR_THRESHOLDS = { high: 0.78, medium: 0.68, low: 0.58 }\nconst DEFAULT_THRESHOLD = SIMILAR_THRESHOLDS.medium\nconst DEFAULT_LIMIT = 10\n\n// parseDSL returns { mode, specs, threshold, limit }\n//\n// mode: 'similar' if SIMILAR: is the first meaningful line (ambient auto-run),\n// 'search' otherwise (interactive search form).\n//\n// Ward's convention: ALL-CAPS keyword as first word signals a mode switch.\n// Placing SIMILAR: first makes the item ambient; placing domain specs first\n// (or leaving text empty) keeps it as an interactive search form.\n\nconst parseDSL = text => {\n const specs = []\n const rosterRefs = [] // ROSTER site/slug \u2014 roster pages whose sites join the scope\n const farms = [] // FARM domain \u2014 peer farms asked to continue the search\n let threshold = null\n let limit = null\n let mode = 'search' // default: interactive search form\n let live = false // default: cache results in localStorage\n let subject = false // SUBJECT modifier: act on the previous lineup page\n let force = false // BUILD mode: re-embed even when index is fresh\n let ghostUrl = null // GHOST mode: page-json URL to open as a ghost page\n let label = null // BUTTON: custom button caption (GHOST / BUILD modes)\n\n // Match a keyword at the start of a line (case-insensitive), requiring it to\n // be followed by end-of-string, whitespace, or colon \u2014 not by more word chars.\n // This prevents domain specs like \"similarity.example.com\" matching SIMILAR.\n const isCmd = (upper, kw) => upper === kw || (upper.startsWith(kw) && /^[\\s:]/.test(upper.slice(kw.length)))\n // Extract the value after the keyword, tolerating optional colon and whitespace.\n // Returns '' for bare commands (e.g. \"SIMILAR\" alone), callers use their default.\n const val = (line, kw) => line.slice(kw.length).replace(/^\\s*:?\\s*/, '').trim()\n\n for (const raw of text.split('\\n')) {\n const line = raw.trim()\n if (!line || line.startsWith('#')) continue\n\n const upper = line.toUpperCase()\n if (isCmd(upper, 'LIVE')) { live = true; continue }\n if (isCmd(upper, 'SUBJECT')) { subject = true; continue }\n if (isCmd(upper, 'AUTHOR')) {\n if (!specs.length && mode === 'search') mode = 'author'\n continue\n }\n if (isCmd(upper, 'REPORT')) {\n if (mode === 'search') mode = 'report'\n continue\n }\n if (isCmd(upper, 'KEYWORD')) {\n if (mode === 'search') mode = 'keyword'\n continue\n }\n if (isCmd(upper, 'SITES')) {\n if (mode === 'search') mode = 'sites'\n continue\n }\n if (isCmd(upper, 'BUILD')) {\n if (mode === 'search') mode = 'build'\n continue\n }\n if (isCmd(upper, 'FORCE')) { force = true; continue }\n if (isCmd(upper, 'GHOST')) {\n ghostUrl = val(line, 'GHOST')\n if (mode === 'search') mode = 'ghost'\n continue\n }\n if (isCmd(upper, 'BUTTON')) { label = val(line, 'BUTTON'); continue }\n if (isCmd(upper, 'ROSTER')) {\n const ref = val(line, 'ROSTER')\n if (ref) rosterRefs.push(ref)\n continue\n }\n if (isCmd(upper, 'FARM')) {\n const peer = val(line, 'FARM')\n if (peer) farms.push(peer)\n continue\n }\n if (isCmd(upper, 'LIST')) {\n if (!specs.length && mode === 'search') mode = 'list'\n continue\n }\n if (isCmd(upper, 'SIMILAR')) {\n const level = val(upper, 'SIMILAR').toLowerCase()\n threshold = SIMILAR_THRESHOLDS[level] || DEFAULT_THRESHOLD // '' \u2192 medium\n if (!specs.length && mode === 'search') mode = 'similar'\n continue\n }\n if (isCmd(upper, 'THRESHOLD')) {\n const tv = val(line, 'THRESHOLD')\n threshold = SIMILAR_THRESHOLDS[tv.toLowerCase()] ?? (parseFloat(tv) || DEFAULT_THRESHOLD)\n continue\n }\n if (isCmd(upper, 'LIMIT')) {\n limit = parseInt(val(line, 'LIMIT')) || DEFAULT_LIMIT // '' \u2192 10\n continue\n }\n // Anything else is a domain spec (glob, explicit domain, or scope keyword)\n specs.push(['PUBLIC', 'LOCAL', 'PRIVATE', 'GALAXY'].includes(upper) ? upper : line)\n }\n\n return {\n mode,\n specs,\n rosterRefs,\n farms,\n threshold: threshold ?? DEFAULT_THRESHOLD,\n limit: limit ?? DEFAULT_LIMIT,\n live,\n subject,\n force,\n ghostUrl,\n label,\n thresholdSet: threshold !== null, // explicit THRESHOLD/SIMILAR in the DSL\n }\n}\n\nconst isGlob = spec => spec.includes('*') || spec.includes('?')\n\n// Scope keywords expand server-side: PUBLIC (Nextcloud mirror farms),\n// LOCAL (primary farm), PRIVATE (public domains with restricted: true),\n// GALAXY (off-farm federation sites indexed into the galaxy tree)\nconst isScope = spec => spec === 'PUBLIC' || spec === 'LOCAL' || spec === 'PRIVATE' ||\n spec === 'GALAXY'\n\nexport { parseDSL, isGlob, isScope, SIMILAR_THRESHOLDS, DEFAULT_THRESHOLD, DEFAULT_LIMIT }\n", "// wiki-plugin-similarity \u2014 turning DSL specs into a concrete list of domains\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\nimport { isGlob, isScope } from './dsl.js'\n\n// \u2500\u2500 Slug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst slugify = title => title.toLowerCase().replace(/\\s+/g, '-').replace(/[^a-z0-9-]/g, '')\n\n// \u2500\u2500 Domain resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst domainCache = new Map()\n\nconst resolveDomainsForSpec = async (spec, origin) => {\n if (domainCache.has(spec)) return domainCache.get(spec)\n const url = `${origin}/system/indexed-domains.json?pattern=${encodeURIComponent(spec)}`\n const res = await fetch(url)\n if (!res.ok) throw new Error(`indexed-domains failed: ${res.status}`)\n const list = await res.json()\n domainCache.set(spec, list)\n return list\n}\n\nconst resolveDomains = async (specs, origin) => {\n if (!specs.length) specs = [window.location.hostname]\n const seen = new Set()\n const result = []\n for (const spec of specs) {\n if (spec === '*' || isGlob(spec) || isScope(spec)) {\n for (const item of await resolveDomainsForSpec(spec, origin)) {\n if (!seen.has(item.domain)) { seen.add(item.domain); result.push(item) }\n }\n } else if (!seen.has(spec)) {\n seen.add(spec); result.push({ domain: spec, page_count: null })\n }\n }\n return result\n}\n\n// \u2500\u2500 Roster resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// ROSTER site/slug resolves a roster page into domain names, following the\n// roster plugin's own line semantics: bare domains are sites; category and\n// blank lines are skipped; nested `ROSTER site/slug` includes another roster\n// page; `REFERENCES site/slug` collects the .site of a page's reference items.\n// Includes are followed transitively with a visited-set loop guard.\n\nconst SITE_LINE = /^([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+|localhost)(:\\d+)?$/\nconst ROSTER_LINE = /^ROSTER ([A-Za-z0-9.\\-:]+\\/[a-z0-9-]+)$/\nconst REFS_LINE = /^REFERENCES ([A-Za-z0-9.\\-:]+\\/[a-z0-9-]+)$/\n\nconst fetchPage = async ref => { // ref = site/slug\n const i = ref.indexOf('/')\n const res = await fetch(`//${ref.slice(0, i)}/${ref.slice(i + 1)}.json`)\n if (!res.ok) throw new Error(`roster page ${ref} failed: ${res.status}`)\n return res.json()\n}\n\nconst resolveRoster = async (ref, out, visited) => {\n if (visited.has(ref)) return\n visited.add(ref)\n let page\n try { page = await fetchPage(ref) } catch (e) { console.warn(e.message); return }\n for (const item of page.story || []) {\n if (item.type !== 'roster') continue\n for (const raw of (item.text || '').split(/\\r?\\n/)) {\n const line = raw.trim()\n if (!line) continue\n const site = line.match(SITE_LINE)\n if (site) { out.add(site[0]); continue }\n const nested = line.match(ROSTER_LINE)\n if (nested) { await resolveRoster(nested[1], out, visited); continue }\n const refs = line.match(REFS_LINE)\n if (refs) {\n try {\n const refPage = await fetchPage(refs[1])\n for (const it of refPage.story || []) {\n if (it.type === 'reference' && it.site) out.add(it.site)\n }\n } catch (e) { console.warn(e.message) }\n }\n // anything else is a category name \u2014 skipped\n }\n }\n}\n\nconst resolveRosters = async rosterRefs => {\n const out = new Set()\n const visited = new Set()\n for (const ref of rosterRefs) await resolveRoster(ref, out, visited)\n return [...out]\n}\n\n// Effective specs: DSL specs plus any domains contributed by ROSTER lines.\nconst effectiveSpecs = async (specs, rosterRefs) =>\n rosterRefs.length ? [...specs, ...await resolveRosters(rosterRefs)] : specs\n\nexport { slugify, resolveDomains, resolveRosters, effectiveSpecs, SITE_LINE, ROSTER_LINE, REFS_LINE }\n", "// wiki-plugin-similarity \u2014 page vectors, embedding, and the cosine scan over them\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\nimport { resolveDomains } from './scope.js'\n\n// \u2500\u2500 Vector loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst vectorCache = new Map()\n\n// Route vector requests through the current wiki's plugin server. This keeps\n// public HTTPS pages same-origin, avoids CORS failures, and lets the server read\n// indices from its configured farm roots.\nconst vectorUrl = domain =>\n `${window.location.origin}/system/semantic-vectors.json?domain=${encodeURIComponent(domain)}`\n\nconst loadVectors = async domain => {\n if (vectorCache.has(domain)) return vectorCache.get(domain)\n const res = await fetch(vectorUrl(domain))\n if (!res.ok) return []\n const data = await res.json()\n vectorCache.set(domain, data)\n return data\n}\n\n// \u2500\u2500 Embedding \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// POST, never GET: page-length text in a query string overflows Node's header\n// limit and dies with 431 before any handler runs (server \u2265 0.11.0).\nconst getEmbedding = async (text, origin) => {\n const res = await fetch(`${origin}/system/embed.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text }),\n })\n if (!res.ok) throw new Error(`embed failed: ${res.status}`)\n return (await res.json()).vector\n}\n\n// Look up an existing page vector from the current domain's cached index.\n// Returns the float[] vector if found, null otherwise.\nconst lookupPageVector = async (slug, domain) => {\n const pages = await loadVectors(domain)\n const entry = pages.find(p => p.slug === slug)\n return entry ? entry.vector : null\n}\n// \u2500\u2500 Cosine search \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst cosineScan = (queryVec, domainEntries, { threshold, limit, excludeSlug, excludeDomain }) => {\n const results = []\n for (const { domain, pages } of domainEntries) {\n for (const { slug, title, vector } of pages) {\n if (slug === excludeSlug && domain === excludeDomain) continue\n let dot = 0\n for (let i = 0; i < queryVec.length; i++) dot += queryVec[i] * vector[i]\n if (dot >= threshold) results.push({ domain, slug, title, score: dot })\n }\n }\n results.sort((a, b) => b.score - a.score)\n return results.slice(0, limit)\n}\n\n// \u2500\u2500 Shared domain loading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst loadDomainEntries = async (specs, origin) => {\n const domains = await resolveDomains(specs, origin)\n const entries = await Promise.all(\n domains.map(async ({ domain }) => ({ domain, pages: await loadVectors(domain) }))\n )\n return entries.filter(e => e.pages.length > 0)\n}\n\nexport { loadVectors, vectorUrl, getEmbedding, lookupPageVector, cosineScan, loadDomainEntries }\n", "// wiki-plugin-similarity \u2014 SUBJECT \u2014 the page an item acts on\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Subject resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// SUBJECT makes an item act on the page BEFORE its own in the lineup \u2014 the\n// host a tool page was opened beside \u2014 falling back to the containing page so\n// a tool page opened alone still works (and announces the fallback).\n// The page div's id IS the slug (possibly _rev-suffixed on a historical view);\n// data('data') carries the full raw page JSON; data('site') is set only on\n// remote pages. `text` is title + opening prose, capped: the BGE-small\n// embedder truncates around 512 tokens, so more would be discarded anyway.\n\nconst resolveSubject = div => {\n const $self = div.parents('.page:first')\n const $host = $self.prev('.page')\n const $page = $host.length ? $host : $self\n const slug = ($page.attr('id') || '').split('_rev')[0]\n const site = $page.data('site') || window.location.hostname\n const data = $page.data('data') || {}\n const title = data.title || $page.find('.title').text().trim() || slug\n const text = [title, ...(data.story || [])\n .filter(i => i.type === 'markdown' || i.type === 'paragraph')\n .map(i => (i.text || '').trim()).filter(Boolean)].join('\\n').slice(0, 2000)\n return { slug, site, title, text, isSelf: !$host.length }\n}\n\nconst subjectNote = s =>\n `Subject: ${s.title}${s.isSelf ? ' (this page)' : ` @ ${s.site}`}`\n\nexport { resolveSubject, subjectNote }\n", "// wiki-plugin-similarity \u2014 per-item result cache in localStorage\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Result cache (localStorage) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Cache is keyed by item id. Invalidated when item.text changes (DSL edited).\n// LIVE mode bypasses the cache entirely.\n\nconst cacheKey = id => `sim-cache-${id}`\n\nconst readCache = item => {\n try {\n const c = JSON.parse(localStorage.getItem(cacheKey(item.id)) || 'null')\n return c?.text === (item.text || '') ? c : null\n } catch { return null }\n}\n\nconst writeCache = (item, data) => {\n try {\n localStorage.setItem(cacheKey(item.id), JSON.stringify({\n text: item.text || '',\n ts: Date.now(),\n ...data,\n }))\n } catch { /* storage unavailable or full */ }\n}\n\nconst cacheAge = ts => {\n const s = Math.floor((Date.now() - ts) / 1000)\n if (s < 60) return `${s}s ago`\n if (s < 3600) return `${Math.floor(s / 60)}m ago`\n if (s < 86400) return `${Math.floor(s / 3600)}h ago`\n return `${Math.floor(s / 86400)}d ago`\n}\n\nexport { readCache, writeCache, cacheAge }\n", "// wiki-plugin-similarity \u2014 item styles and the site flag\n// Split out of similarity.js; see the Splitting the Server phase of the plan.\n\n// \u2500\u2500 Styles \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst STYLES = `\n .sim-form { display:flex; gap:6px; margin-bottom:8px; }\n .sim-input { flex:1; padding:6px 8px; font-size:14px; border:1px solid #ccc; border-radius:3px; }\n .sim-btn { padding:6px 14px; background:#c4561d; color:white; border:none;\n border-radius:3px; cursor:pointer; font-size:14px; }\n .sim-btn:disabled { opacity:0.5; cursor:not-allowed; }\n .sim-status { font-size:12px; color:#888; margin-bottom:6px; min-height:16px; }\n .sim-results { margin-top:4px; }\n .sim-result { display:flex; align-items:center; gap:8px; padding:3px 0;\n border-bottom:1px solid #f0f0f0; }\n .sim-flag { width:16px; height:16px; vertical-align:middle; margin-right:4px; }\n .sim-link { font-size:14px; color:#406; flex:1; }\n .sim-domain { font-size:11px; color:#999; }\n .similar-results h3, .sim-list h3 { margin:4px 0 6px; font-size:14px; color:#555; }\n .similar-results ul { margin:0; padding-left:18px; }\n .similar-results li { font-size:14px; padding:2px 0; }\n .similar-results .sim-domain { margin-left:6px; }\n .sim-count { font-size:12px; color:#888; margin:4px 0 0; }\n .sim-list table { border-collapse:collapse; width:100%; font-size:13px; }\n .sim-list th { text-align:left; font-size:11px; color:#888; padding:2px 8px 4px 0;\n border-bottom:1px solid #ddd; }\n .sim-list td { padding:3px 8px 3px 0; border-bottom:1px solid #f0f0f0; vertical-align:middle; }\n .sim-list td:last-child { text-align:right; color:#999; font-size:11px; }\n .sim-list .sim-flag { margin-right:6px; }\n`\n\nconst siteFlag = (domain, score) =>\n `<img class=\"sim-flag remote\" src=\"${window.wiki.site(domain).flag()}\"\n title=\"${domain} \u2014 score ${score.toFixed(3)}\"\n data-site=\"${domain}\">`\n\nexport { STYLES, siteFlag }\n", "// wiki-plugin-similarity\n//\n// One item type: similarity\n//\n// DSL in item.text (newline-separated lines):\n// * all indexed domains on this server\n// david.* glob pattern\n// *.fish glob pattern\n// david.hitchhikers.earth explicit domain name\n// # comment ignored\n// LIST list indexed domains (mode directive)\n// SIMILAR: high threshold preset AND ambient mode trigger\n// SUBJECT modifier: act on the PREVIOUS page in the lineup\n// (the host a tool page was opened beside; falls\n// back to the containing page when none)\n// THRESHOLD: 0.72 exact cosine threshold (overrides SIMILAR:)\n// LIMIT: 8 max results shown (default 10)\n// ROSTER site/slug add the sites of a roster page to the scope\n// FARM other.farm.tld ask a peer farm to continue the search (experimental)\n//\n// Mode is determined by the FIRST meaningful line (Ward's ALL-CAPS convention):\n// LIST \u2192 show a table of all indexed domains and their page counts;\n// optional glob patterns on subsequent lines filter the list\n// SIMILAR: \u2192 ambient mode \u2014 automatically find pages similar to this page\n// REPORT \u2192 server-side ranked/bundled semantic report (ghost page)\n// KEYWORD \u2192 galactic MiniSearch over live site-index.json files (ghost page)\n// SITES \u2192 which site should this page go on? \u2014 per-domain aggregation of\n// the page-vector scan (ghost page)\n// (other) \u2192 search form mode \u2014 user types a query, results appear\n//\n// Server endpoints required (all same-origin, served by this plugin's server\n// component \u2014 works on any host, including the public farm):\n// GET /system/indexed-domains.json?pattern=glob1,glob2\n// GET /system/semantic-vectors.json?domain=\n// POST /system/embed.json {text}\n// POST /system/search-report.json\n// POST /system/site-report.json\n// GET /system/farm-search.json?q=&pattern=&limit=\n// GET /system/build-index.json?domains=&force=\n\nimport { parseDSL, DEFAULT_LIMIT } from './dsl.js'\nimport { slugify, effectiveSpecs, resolveDomains } from './scope.js'\nimport { loadVectors, getEmbedding, lookupPageVector, cosineScan, loadDomainEntries } from './vectors.js'\nimport { resolveSubject, subjectNote } from './subject.js'\nimport { readCache, writeCache, cacheAge } from './cache.js'\nimport { STYLES, siteFlag } from './styles.js'\n\n// \u2500\u2500 similarity item \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst simLink = (domain, slug, title, score) =>\n `<a class=\"sim-link\" data-title=\"${title}\" data-slug=\"${slug}\" data-site=\"${domain}\" href=\"#\">` +\n `${siteFlag(domain, score)} ${title}</a>`\n\nexport const emit = (div, item) => {\n const { mode, specs, threshold, limit, force, ghostUrl, label } = parseDSL(item?.text || '')\n if (mode === 'ghost') {\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <button class=\"sim-btn\">${label || 'Open'}</button>\n </div>\n <div class=\"sim-status\"></div>\n </div>`)\n } else if (mode === 'build') {\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <button class=\"sim-btn\">${label || `Index ${specs.length ? specs.join(', ') : '*'}${force ? ' (force)' : ''}`}</button>\n </div>\n <div class=\"sim-status\"></div>\n </div>`)\n } else if (mode === 'list') {\n const label = specs.length ? specs.join(', ') : '*'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-status\">Loading indexed domains (${label})\u2026</div>\n <div class=\"sim-list\"></div>\n </div>`)\n } else if (mode === 'similar') {\n const label = specs.length ? specs.join(', ') : 'current domain'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-status\">Finding similar pages across ${label}\u2026</div>\n <div class=\"sim-results\"></div>\n </div>`)\n } else if (mode === 'author' || mode === 'report' || mode === 'keyword' || mode === 'sites') {\n const label = specs.length ? specs.join(', ') : '(current domain)'\n const btnLabel = mode === 'report' ? 'Report' : mode === 'keyword' ? 'Keyword'\n : mode === 'sites' ? 'Sites' : 'Author'\n const hint = mode === 'sites' ? 'Where should this page go? Title + first paragraph\u2026'\n : 'Search wiki pages\u2026'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <input class=\"sim-input\" type=\"text\" placeholder=\"${hint}\" />\n <button class=\"sim-btn\">${btnLabel}</button>\n </div>\n <div class=\"sim-status\">Domains: ${label}</div>\n <div class=\"sim-results\"></div>\n </div>`)\n } else {\n const label = specs.length ? specs.join(', ') : '(current domain)'\n div.html(`\n <style>${STYLES}</style>\n <div class=\"similarity\" data-id=\"${item.id}\">\n <div class=\"sim-form\">\n <input class=\"sim-input\" type=\"text\" placeholder=\"Search wiki pages\u2026\" />\n <button class=\"sim-btn\">Search</button>\n </div>\n <div class=\"sim-status\">Domains: ${label}</div>\n <div class=\"sim-results\"></div>\n </div>`)\n }\n}\n\nexport const bind = (div, item) => {\n const { mode, specs, rosterRefs, farms, threshold, limit, live, subject: subjectFlag,\n force, ghostUrl, thresholdSet } = parseDSL(item?.text || '')\n const origin = window.location.origin\n const status = div.find('.sim-status')[0]\n // The subject depends on where in the lineup this page was opened, so\n // cached results from one host must never replay beside another.\n const subject = subjectFlag ? resolveSubject(div) : null\n const cache = (live || subject) ? null : readCache(item)\n // Scope = DSL specs plus roster-page domains (resolved once, shared by modes)\n const specsP = effectiveSpecs(specs, rosterRefs)\n // Seed params for the server report routes \u2014 the stored page vector wins\n // server-side; text is the fallback for remote or unindexed subjects.\n const seedParams = () => subject ? {\n seed: { site: subject.site, slug: subject.slug },\n text: subject.text,\n excludePage: { site: subject.site, slug: subject.slug },\n } : {}\n\n // Standardised pre-search status: what will run, over how much, with what config.\n // e.g. \"Report ready \u2014 18,583 pages across 267 domains \u00B7 threshold 0.68 \u00B7 limit 20 \u00B7 LIVE\"\n const configSummary = (verb, pages, nDomains) => {\n const parts = [`${verb} \u2014 ${pages.toLocaleString()} pages across ${nDomains} domains`]\n if (thresholdSet) parts.push(`threshold ${threshold}`)\n parts.push(`limit ${limit}`)\n if (live) parts.push('LIVE')\n return parts.join(' \u00B7 ')\n }\n\n div.on('dblclick', e => {\n if ($(e.target).closest('.sim-input').length) return\n window.wiki.textEditor(div, item)\n })\n div.on('click', '.sim-link', function (e) {\n e.preventDefault()\n const $a = $(this)\n // shift-click appends at the end of the lineup instead of truncating after this page\n const $page = e.shiftKey ? null : div.parents('.page')\n window.wiki.doInternalLink($a.data('title'), $page, $a.data('site'))\n })\n\n const scopeLabel = !specs.length || (specs.length === 1 && specs[0] === '*')\n ? 'on farm'\n : specs.length === 1 ? `on ${specs[0]}` : 'in domains'\n\n const cacheNote = ts => ts ? ` \u00B7 cached ${cacheAge(ts)}` : ''\n\n if (mode === 'list') {\n const listDiv = div.find('.sim-list')[0]\n\n const renderList = (domains, ts) => {\n const totalPages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n status.style.display = 'none'\n listDiv.innerHTML = `<h3>Indexed Farm Domains</h3>\n <table>\n <tr><th>Domain</th><th>Pages</th></tr>\n ${domains.map(({ domain, page_count }) => `\n <tr>\n <td><img class=\"sim-flag remote\" src=\"${window.wiki.site(domain).flag()}\"\n title=\"${domain}\" data-site=\"${domain}\"> ${domain}</td>\n <td>${page_count != null ? page_count.toLocaleString() : '\u2014'}</td>\n </tr>`).join('')}\n </table>\n <p class=\"sim-count\">${domains.length} domains \u2014 ${totalPages.toLocaleString()} pages${cacheNote(ts)}</p>`\n }\n\n if (cache?.domains) {\n renderList(cache.domains, cache.ts)\n } else {\n ;(async () => {\n try {\n const eff = await specsP\n const patterns = eff.length ? eff.join(',') : '*'\n const url = `${origin}/system/indexed-domains.json?pattern=${encodeURIComponent(patterns)}&limit=${limit}`\n const res = await fetch(url)\n if (!res.ok) throw new Error(`indexed-domains failed: ${res.status}`)\n const domains = await res.json()\n if (!domains.length) { status.textContent = 'No indexed domains found'; return }\n renderList(domains, null)\n writeCache(item, { domains })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n }\n })()\n }\n\n } else if (mode === 'similar') {\n const results = div.find('.sim-results')[0]\n\n const renderScored = (scored, ts) => {\n if (!scored.length) {\n status.textContent = `No similar pages found above threshold ${threshold}`\n return\n }\n results.innerHTML = `<h3>Similar Pages</h3><ul>${\n scored.map(({ domain, slug, title, score }) =>\n `<li>${simLink(domain, slug, title, score)}</li>`).join('')\n }</ul><p class=\"sim-count\">${scored.length} found ${scopeLabel}${cacheNote(ts)}</p>`\n status.style.display = 'none'\n }\n\n if (cache?.scored) {\n renderScored(cache.scored, cache.ts)\n } else {\n ;(async () => {\n try {\n // SUBJECT: act on the previous lineup page; otherwise this page.\n const $page = div.parents('.page')\n const s = subject || (() => {\n const pageTitle = $page.find('.title').text().trim() || document.title\n return { slug: slugify(pageTitle), site: window.location.hostname,\n title: pageTitle, text: null, isSelf: true }\n })()\n\n const domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(s)} \u00B7 ` : '') +\n `Searching ${total.toLocaleString()} pages\u2026`\n\n let qVec = await lookupPageVector(s.slug, s.site)\n if (!qVec) {\n status.textContent = 'Embedding page (not yet indexed)\u2026'\n const pageText = s.text || $page.find('.item')\n .map((_, el) => $(el).text().trim()).get().filter(Boolean).join('\\n')\n qVec = await getEmbedding(pageText || s.title, origin)\n }\n\n const scored = cosineScan(qVec, domainEntries, {\n threshold, limit, excludeSlug: s.slug, excludeDomain: s.site,\n })\n renderScored(scored, null)\n if (subject) { // keep the subject visible above the results\n status.textContent = subjectNote(s)\n status.style.display = ''\n }\n if (scored.length && !subject) writeCache(item, { scored })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n }\n })()\n }\n\n } else if (mode === 'ghost') {\n // Ghost mode \u2014 fetch page-json from any URL and open it as a ghost page\n const btn = div.find('.sim-btn')[0]\n\n const doGhost = async () => {\n if (!ghostUrl) { status.textContent = 'No URL \u2014 GHOST needs a page-json URL'; return }\n btn.disabled = true\n status.textContent = 'Fetching\u2026'\n try {\n const res = await fetch(ghostUrl)\n if (!res.ok) throw new Error(`fetch failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = ''\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doGhost)\n\n } else if (mode === 'build') {\n // Build mode \u2014 trigger a semantic index build; result opens as a ghost page\n const btn = div.find('.sim-btn')[0]\n\n const doBuild = async () => {\n btn.disabled = true\n status.textContent = 'Building index\u2026 (may take a while for large scopes)'\n try {\n const domains = encodeURIComponent((specs.length ? specs : ['*']).join(','))\n const res = await fetch(\n `${origin}/system/build-index.json?domains=${domains}&force=${force ? 1 : 0}`)\n if (res.status === 501) {\n const body = await res.json().catch(() => ({}))\n throw new Error(body.hint || 'indexing runs on the farm indexer, not this server')\n }\n if (!res.ok) throw new Error(`build-index failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = ''\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doBuild)\n\n } else if (mode === 'report') {\n // Report mode \u2014 server-side ranked/bundled search, opens result as ghost page\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n let readyLine = `Domains: ${specs.length ? specs.join(', ') : '*'}`\n\n // SUBJECT: the host page IS the query \u2014 prefill its title (editable) and\n // seed the server search with its stored vector.\n if (subject && !input.value) input.value = subject.title\n\n // Preload the lightweight domain listing (counts only, no vectors) so the\n // status line shows scope and config before any search is issued.\n ;(async () => {\n try {\n const eff = await specsP\n const domains = await resolveDomains(eff.length ? eff : ['*'], origin)\n const pages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n readyLine = configSummary('Report ready', pages, domains.length)\n if (farms.length) readyLine += ` \u00B7 +${farms.length} peer farm${farms.length > 1 ? 's' : ''}`\n if (subject) readyLine = `${subjectNote(subject)} \u00B7 ${readyLine}`\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Domain listing unavailable: ${e.message}`\n }\n })()\n\n // The embedder and the keyword index share nothing: one can be down while\n // the other is perfectly healthy. A report that cannot embed its query\n // should say so and answer with words, not leave an error and no results.\n // 502/503 are what the server sends when embedding is unavailable \u2014 a\n // missing local embedder, or the circuit breaker open after crashes.\n const EMBEDDER_DOWN = new Set([502, 503])\n\n const keywordInstead = async (query, eff) => {\n const pattern = encodeURIComponent((eff.length ? eff : ['*']).join(','))\n const farmsParam = farms.length ? `&farms=${encodeURIComponent(farms.join(','))}` : ''\n const res = await fetch(\n `${origin}/system/farm-search.json?q=${encodeURIComponent(query)}&pattern=${pattern}&limit=${limit}${farmsParam}`)\n if (!res.ok) throw new Error(`keyword search also failed: ${res.status}`)\n const page = await res.json()\n // The server titles this page \"\u2026 Keyword Search\", so the reader can see\n // which tier answered without being told twice.\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n }\n\n const doReport = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = farms.length ? 'Generating report (asking peer farms)\u2026' : 'Generating report\u2026'\n try {\n const eff = await specsP\n // A hand-edited query is a new question \u2014 drop the page seed then.\n const seeded = subject && query === subject.title ? seedParams() : {}\n const body = { query, domains: eff.length ? eff : ['*'], limit, live, ...seeded }\n if (farms.length) body.farms = farms\n if (thresholdSet) body.threshold = threshold\n const res = await fetch(`${origin}/system/search-report.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (EMBEDDER_DOWN.has(res.status)) {\n const body = await res.json().catch(() => ({}))\n const why = (body.error || `status ${res.status}`).replace(/^embedding unavailable: /, '')\n status.textContent = 'Semantic search unavailable \u2014 searching by keyword instead\u2026'\n await keywordInstead(query, eff)\n status.textContent = `Semantic search unavailable (${why}) \u2014 these are keyword matches, ranked by word not meaning.`\n return\n }\n if (!res.ok) throw new Error(`search-report failed: ${res.status}`)\n const page = await res.json()\n const pageObj = window.wiki.newPage(page)\n window.wiki.showResult(pageObj, { $page: div.parents('.page') })\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doReport)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doReport() })\n\n } else if (mode === 'sites') {\n // Sites mode \u2014 which site should this page go on? Server aggregates the\n // page-vector scan per domain; result opens as a ghost page.\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n let readyLine = `Domains: ${specs.length ? specs.join(', ') : '*'}`\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n const eff = await specsP\n const domains = await resolveDomains(eff.length ? eff : ['*'], origin)\n const pages = domains.reduce((n, d) => n + (d.page_count || 0), 0)\n readyLine = configSummary('Site report ready', pages, domains.length)\n if (subject) readyLine = `${subjectNote(subject)} \u00B7 ${readyLine}`\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Domain listing unavailable: ${e.message}`\n }\n })()\n\n const doSites = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = 'Ranking sites\u2026'\n try {\n const eff = await specsP\n const seeded = subject && query === subject.title ? seedParams() : {}\n const res = await fetch(`${origin}/system/site-report.json`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ query, domains: eff.length ? eff : ['*'], limit, ...seeded }),\n })\n if (!res.ok) throw new Error(`site-report failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = readyLine\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doSites)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doSites() })\n\n } else if (mode === 'keyword') {\n // Keyword mode \u2014 galactic MiniSearch: the server reads each site's own\n // per-edit site-index.json; result opens as a ghost page.\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n\n // SUBJECT: keyword search wants words, not vectors \u2014 the host title is\n // the prewired query (editable), finding forks and namesakes alike.\n if (subject && !input.value) input.value = subject.title\n\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n `Keyword search ready \u2014 domains: ${specs.length ? specs.join(', ') : '*'} \u00B7 limit ${limit}`\n\n const doKeyword = async () => {\n const query = input.value.trim()\n if (!query) return\n btn.disabled = true\n status.textContent = 'Searching live site indexes\u2026'\n try {\n const eff = await specsP\n const pattern = encodeURIComponent((eff.length ? eff : ['*']).join(','))\n const farmsParam = farms.length ? `&farms=${encodeURIComponent(farms.join(','))}` : ''\n const res = await fetch(\n `${origin}/system/farm-search.json?q=${encodeURIComponent(query)}&pattern=${pattern}&limit=${limit}${farmsParam}`)\n if (!res.ok) throw new Error(`farm-search failed: ${res.status}`)\n const page = await res.json()\n window.wiki.showResult(window.wiki.newPage(page), { $page: div.parents('.page') })\n status.textContent = `Keyword search ready \u2014 domains: ${specs.length ? specs.join(', ') : '*'} \u00B7 limit ${limit}`\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doKeyword)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doKeyword() })\n\n } else if (mode === 'author') {\n // Author mode \u2014 same search form but creates a ghost page from results\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n const results = div.find('.sim-results')[0]\n let domainEntries = null\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n if (!cache) status.textContent = 'Resolving domains\u2026'\n domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n configSummary('Author ready', total, domainEntries.length)\n } catch (e) {\n status.textContent = `Load error: ${e.message}`\n }\n })()\n\n const doAuthor = async () => {\n const query = input.value.trim()\n if (!query || !domainEntries) return\n btn.disabled = true\n status.textContent = 'Embedding query\u2026'\n results.innerHTML = ''\n try {\n const qVec = await getEmbedding(query, origin)\n const scored = cosineScan(qVec, domainEntries,\n { threshold, limit, excludeSlug: null, excludeDomain: null })\n\n // Unique titles for wiki-link list\n const seenTitles = new Set()\n const uniqueTitles = []\n for (const { title } of scored) {\n if (!seenTitles.has(title)) { seenTitles.add(title); uniqueTitles.push(title) }\n }\n\n const hexId = () => Math.floor(Math.random() * 0xffffffffffffffff).toString(16).padStart(16, '0')\n const primaryLines = uniqueTitles.map(t => `- [[${t}]]`).join('\\n')\n\n const story = [\n { type: 'markdown', id: hexId(), text: `# Similar Pages\\n\\n${primaryLines}` },\n { type: 'markdown', id: hexId(), text: '# Reference Links' },\n ...scored.map(({ domain, slug, title, score }) => ({\n type: 'reference', id: hexId(), site: domain, slug, title,\n text: `score ${score.toFixed(3)}`,\n })),\n ]\n\n const pageObj = window.wiki.newPage({ title: `${query} Results`, story, journal: [] })\n window.wiki.showResult(pageObj, { $page: div.parents('.page') })\n\n status.textContent = `${scored.length} pages found`\n writeCache(item, { scored, query })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doAuthor)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doAuthor() })\n\n } else {\n // Search form mode\n const input = div.find('.sim-input')[0]\n const btn = div.find('.sim-btn')[0]\n const results = div.find('.sim-results')[0]\n let domainEntries = null\n\n // Show cached results immediately while domains preload in background\n if (cache?.scored) {\n input.value = cache.query || ''\n results.innerHTML = cache.scored.map(({ domain, slug, title, score }) =>\n `<div class=\"sim-result\">${simLink(domain, slug, title, score)}</div>`).join('') +\n `<p class=\"sim-count\">Top ${cache.scored.length} for \"${cache.query || ''}\"${cacheNote(cache.ts)}</p>`\n status.textContent = ''\n }\n\n if (subject && !input.value) input.value = subject.title\n\n ;(async () => {\n try {\n if (!cache) status.textContent = 'Resolving domains\u2026'\n domainEntries = await loadDomainEntries(await specsP, origin)\n const total = domainEntries.reduce((n, e) => n + e.pages.length, 0)\n status.textContent = (subject ? `${subjectNote(subject)} \u00B7 ` : '') +\n configSummary('Search ready', total, domainEntries.length)\n } catch (e) {\n status.textContent = `Load error: ${e.message}`\n }\n })()\n\n const doSearch = async () => {\n const query = input.value.trim()\n if (!query || !domainEntries) return\n btn.disabled = true\n status.textContent = 'Embedding query\u2026'\n results.innerHTML = ''\n try {\n const qVec = await getEmbedding(query, origin)\n const scored = cosineScan(qVec, domainEntries,\n { threshold, limit, excludeSlug: null, excludeDomain: null })\n results.innerHTML = scored.map(({ domain, slug, title, score }) =>\n `<div class=\"sim-result\">${simLink(domain, slug, title, score)}</div>`).join('') +\n `<p class=\"sim-count\">Top ${scored.length} for \"${query}\"</p>`\n status.textContent = ''\n writeCache(item, { scored, query })\n } catch (e) {\n status.textContent = `Error: ${e.message}`\n } finally {\n btn.disabled = false\n }\n }\n\n btn.addEventListener('click', doSearch)\n input.addEventListener('keydown', e => { if (e.key === 'Enter') doSearch() })\n }\n}\n\n// \u2500\u2500 Register item type with the wiki \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nif (typeof window !== 'undefined') {\n window.plugins = window.plugins || {}\n window.plugins.similarity = { emit, bind }\n}\n"],
|
|
5
|
+
"mappings": ";MAKA,IAAMA,EAAqB,CAAE,KAAM,IAAM,OAAQ,IAAM,IAAK,GAAK,EAC3DC,EAAqBD,EAAmB,OACxCE,EAAqB,GAWrBC,EAAWC,GAAQ,CACvB,IAAMC,EAAU,CAAC,EACXC,EAAa,CAAC,EACdC,EAAU,CAAC,EACbC,EAAY,KACZC,EAAY,KACZC,EAAY,SACZC,EAAY,GACZC,EAAY,GACZC,EAAY,GACZC,EAAY,KACZC,EAAY,KAKVC,EAAS,CAACC,EAAOC,IAAOD,IAAUC,GAAOD,EAAM,WAAWC,CAAE,GAAK,SAAS,KAAKD,EAAM,MAAMC,EAAG,MAAM,CAAC,EAGrGC,EAAS,CAACC,EAAMF,IAAOE,EAAK,MAAMF,EAAG,MAAM,EAAE,QAAQ,YAAa,EAAE,EAAE,KAAK,EAEjF,QAAWG,KAAOjB,EAAK,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ghostUrl", "label", "isCmd", "upper", "kw", "val", "line", "raw", "ref", "peer", "level", "tv", "isGlob", "spec", "isScope", "slugify", "title", "domainCache", "resolveDomainsForSpec", "spec", "origin", "url", "res", "list", "resolveDomains", "specs", "seen", "result", "isGlob", "isScope", "item", "SITE_LINE", "ROSTER_LINE", "REFS_LINE", "fetchPage", "ref", "i", "resolveRoster", "out", "visited", "page", "e", "raw", "line", "site", "nested", "refs", "refPage", "it", "resolveRosters", "rosterRefs", "effectiveSpecs", "vectorCache", "vectorUrl", "domain", "loadVectors", "res", "data", "getEmbedding", "text", "origin", "lookupPageVector", "slug", "entry", "p", "cosineScan", "queryVec", "domainEntries", "threshold", "limit", "excludeSlug", "excludeDomain", "results", "pages", "title", "vector", "dot", "i", "a", "b", "loadDomainEntries", "specs", "domains", "resolveDomains", "e", "resolveSubject", "div", "$self", "$host", "$page", "slug", "site", "data", "title", "text", "i", "subjectNote", "s", "cacheKey", "id", "readCache", "item", "c", "writeCache", "data", "cacheAge", "ts", "s", "STYLES", "siteFlag", "domain", "score", "simLink", "domain", "slug", "title", "score", "siteFlag", "emit", "div", "item", "mode", "specs", "threshold", "limit", "force", "ghostUrl", "label", "parseDSL", "STYLES", "btnLabel", "hint", "bind", "rosterRefs", "farms", "live", "subjectFlag", "thresholdSet", "origin", "status", "subject", "resolveSubject", "cache", "readCache", "specsP", "effectiveSpecs", "seedParams", "configSummary", "verb", "pages", "nDomains", "parts", "e", "$a", "$page", "scopeLabel", "cacheNote", "ts", "cacheAge", "listDiv", "renderList", "domains", "totalPages", "n", "d", "page_count", "eff", "patterns", "url", "res", "writeCache", "results", "renderScored", "scored", "s", "pageTitle", "slugify", "domainEntries", "loadDomainEntries", "total", "subjectNote", "qVec", "lookupPageVector", "pageText", "_", "el", "getEmbedding", "cosineScan", "btn", "doGhost", "page", "doBuild", "body", "input", "readyLine", "resolveDomains", "EMBEDDER_DOWN", "keywordInstead", "query", "pattern", "farmsParam", "doReport", "seeded", "why", "pageObj", "doSites", "doKeyword", "doAuthor", "seenTitles", "uniqueTitles", "hexId", "primaryLines", "t", "story", "doSearch"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
{
|
|
5
5
|
"type": "markdown",
|
|
6
6
|
"id": "aec1dfcd5f2bc42b",
|
|
7
|
-
"text": "The Similarity plugin adds search to a Federated Wiki farm
|
|
7
|
+
"text": "The Similarity plugin adds search to a Federated Wiki farm \u2014 semantic similarity over prebuilt vector indexes, ranked search reports, galactic keyword search over each site's own MiniSearch index, and semantic search across the wider federation. One item type \u2014 **similarity** \u2014 with a line-oriented DSL, plus a server component that serves every search same-origin. Works on any host: embedding runs in-process (native ONNX where available, WASM everywhere else)."
|
|
8
8
|
},
|
|
9
9
|
{
|
|
10
10
|
"type": "markdown",
|
|
11
11
|
"id": "28edff984cc5334d",
|
|
12
|
-
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE / GALAXY):\n\n- (no keyword)
|
|
12
|
+
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE / GALAXY):\n\n- (no keyword) \u2014 interactive semantic search form\n- `SIMILAR: high|medium|low` \u2014 ambient: pages similar to this page\n- `REPORT` \u2014 server-side ranked, stub-filtered, fork-bundled report\n- `KEYWORD` \u2014 galactic MiniSearch over live site-index.json files\n- `SITES` \u2014 which site should this page go on? Per-domain aggregation of the page-vector scan: 0.7 \u00d7 mean of the top 5 page similarities + 0.3 \u00d7 site-centroid similarity. Forked pages count for every site that carries them\n- `LIST` \u2014 table of indexed domains\n- `AUTHOR` \u2014 search results as a draggable ghost page\n- `BUILD` / `FORCE` \u2014 proxy to the farm indexer, where configured\n- `GHOST url` / `BUTTON label` \u2014 open any page-json as a ghost page\n- `ROSTER site/slug` \u2014 add a roster page's sites to the scope (off-farm sites searched via the galaxy cache)\n- `FARM domain` \u2014 ask a peer farm to continue the search. The peer answers from exactly the sites whose own [[Federated Farm Search]] page grants your origin (`FROM` lines; `FROM *` needs the peer admin's `WIKI_PEER_FEDERATION=open`)\n- `GALAXY` \u2014 search the off-farm federation sites indexed into this host's galaxy tree. A scope, not a mode: `GALAXY` alone answers only from the federation (the farm's own pages are never swept in, and `*` never includes galaxy sites); `*` and `GALAXY` together search farm and federation as one\n- `SUBJECT` \u2014 act on the previous page in the lineup, the host a tool page was opened beside\n- `THRESHOLD: 0.72` \u00b7 `LIMIT: 8` \u00b7 `LIVE` \u2014 tuning"
|
|
13
13
|
},
|
|
14
14
|
{
|
|
15
15
|
"type": "markdown",
|
|
@@ -64,12 +64,22 @@
|
|
|
64
64
|
{
|
|
65
65
|
"type": "markdown",
|
|
66
66
|
"id": "d9a96dfebb9d1692",
|
|
67
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`
|
|
67
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json` \u2014 accepts an optional `author`: a display name or account username, resolved against this farm's own site ownership (each site's `owner.json`) and intersected with the requested scope. An ambiguous name answers 409 with the competing usernames rather than guessing\n- `POST /system/site-report.json` \u2014 which site should this page go on? Per-domain aggregation of the page-vector scan: 0.7 \u00d7 mean of the top 5 page similarities + 0.3 \u00d7 site-centroid similarity; forked pages count for every site that carries them\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `GET /system/galaxy-registry.json` \u2014 the galaxy site registry: every federation site known to this host, with provenance, liveness, page counts and scraped site owner (read-only; written by the galaxy indexer host)\n- `GET /system/peer-hello.json` \u2014 capability probe: version, model, federation status (404 = plugin absent)\n- `GET /system/similarity-health.json` \u2014 embedder supervisor state: child-process / semindex / url, breaker status, recent crashes\n- `POST /system/peer-search.json` \u2014 answer another farm's search. An optional `author` travels as the plain name asked for, never a resolved username: the answering farm resolves it against its OWN records and reports `applied`, `ignored` (no records kept) or `ambiguous`. Two keys: the admin's `WIKI_PEER_FEDERATION` ceiling (off / grants / open) and each site's Federated Farm Search grants page; scope = union of granting sites; hop limit, replay dedup, IP-keyed + global rate limits; restricted sites always excluded\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder.\n\nSince 0.9.0 all query embedding runs in a supervised child process, never in the wiki server itself: a crash in the ONNX runtime fails that one search, and repeated crashes trip a circuit breaker that answers 503 while cooling down. The worst case for a wiki running this plugin is \"semantic search temporarily unavailable\" \u2014 never a dead wiki.\n\nSince 0.11.0 a third index tier sits beside the farm: the **galaxy** \u2014 a farm-shaped tree of off-farm federation sites, built by a separate indexer and read through a byte-capped vector cache (`WIKI_GALAXY_VECTOR_CACHE_MB`, default 512). Galaxy entries carry their enrichment precomputed, because off-farm pages have no local page JSON to read; the stub filter, fork bundling and scoring then run unchanged, so federation results rank directly against farm results.\n\nSince 0.12.0 the plugin also offers a **Semantic Search** page through the wiki's \u2630 menu, declared by a `pages` entry in `factory.json` and shipped in the package.\n\nSince 0.13.0 restricted sites are hidden from **every** route unless the caller is trusted, not only from peer answers. Restricted = the local farm's `wikiDomains` entries marked `restricted`, the globs in `WIKI_RESTRICTED_DOMAINS` (e.g. `*.private.fish`), and extra farms' config files. Trusted = an owner or admin session, a tool on the same host (loopback, no `X-Forwarded-For`), or a client the reverse proxy vouches for from `WIKI_TRUSTED_NETS` (default: the Tailscale ranges and loopback; the header is believed only when the direct peer is loopback). Cross-origin browser requests are never trusted. Untrusted callers get the public view: `semantic-vectors.json` answers 403 for a restricted domain, and the scans simply do not include it. `similarity-health.json` reports the policy and `callerTrusted`."
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"type": "markdown",
|
|
71
|
+
"id": "b4e1c0d2a7f39e56",
|
|
72
|
+
"text": "0.14.0 decides where the query embedder lives, and says so out loud. `WIKI_EMBED_URL` is now validated: a value that is not an http(s) URL \u2014 the public farm had the literal string `disabled` \u2014 is ignored with a warning instead of being POSTed to, which is what whoever typed it meant. Where the environment is not yours to set, the address can come from `{farmRoot}/similarity.json` (`{\"embedUrl\": \"\u2026\"}`) instead, read mtime-cached so a retarget needs no restart. `/system/similarity-health.json` now reports which `source` won and whether a `localEmbedderAvailable` \u2014 the local path is never exercised while a proxy is set, so that question was otherwise unanswerable from outside. Both HTTP helpers also learned `https`: before this they were http-only on port 80, so an https proxy could never have worked."
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"type": "markdown",
|
|
76
|
+
"id": "c72e1a4f08b5d693",
|
|
77
|
+
"text": "0.15.0 makes a dead embedder degrade honestly. The embedder and the keyword index share nothing, so one can be down while the other is fine \u2014 but a report that could not embed its query used to leave a bare status code and no results. It now says semantic search is unavailable, gives the reason, and answers the same query by keyword instead. The result page is titled \u201cKeyword Search\u201d by the server, so the reader can see which tier answered."
|
|
68
78
|
},
|
|
69
79
|
{
|
|
70
80
|
"type": "markdown",
|
|
71
81
|
"id": "21eb5354d2adb29e",
|
|
72
|
-
"text": "**Version:** 0.
|
|
82
|
+
"text": "**Version:** 0.15.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
73
83
|
}
|
|
74
84
|
],
|
|
75
85
|
"plugin": "similarity",
|
|
@@ -82,12 +92,12 @@
|
|
|
82
92
|
{
|
|
83
93
|
"type": "markdown",
|
|
84
94
|
"id": "aec1dfcd5f2bc42b",
|
|
85
|
-
"text": "The Similarity plugin adds search to a Federated Wiki farm
|
|
95
|
+
"text": "The Similarity plugin adds search to a Federated Wiki farm \u2014 semantic similarity over prebuilt vector indexes, ranked search reports, and galactic keyword search over each site's own MiniSearch index. One item type \u2014 **similarity** \u2014 with a line-oriented DSL, plus a server component that serves every search same-origin. Works on any host: embedding runs in-process (native ONNX where available, WASM everywhere else)."
|
|
86
96
|
},
|
|
87
97
|
{
|
|
88
98
|
"type": "markdown",
|
|
89
99
|
"id": "28edff984cc5334d",
|
|
90
|
-
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword)
|
|
100
|
+
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword) \u2014 interactive semantic search form\n- `SIMILAR: high|medium|low` \u2014 ambient: pages similar to this page\n- `REPORT` \u2014 server-side ranked, stub-filtered, fork-bundled report\n- `KEYWORD` \u2014 galactic MiniSearch over live site-index.json files\n- `LIST` \u2014 table of indexed domains\n- `AUTHOR` \u2014 search results as a draggable ghost page\n- `BUILD` / `FORCE` \u2014 proxy to the farm indexer, where configured\n- `GHOST url` / `BUTTON label` \u2014 open any page-json as a ghost page\n- `THRESHOLD: 0.72` \u00b7 `LIMIT: 8` \u00b7 `LIVE` \u2014 tuning"
|
|
91
101
|
},
|
|
92
102
|
{
|
|
93
103
|
"type": "markdown",
|
|
@@ -132,17 +142,17 @@
|
|
|
132
142
|
{
|
|
133
143
|
"type": "markdown",
|
|
134
144
|
"id": "d9a96dfebb9d1692",
|
|
135
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n\nIndexes are `status/semantic-vectors.json` per domain
|
|
145
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder."
|
|
136
146
|
},
|
|
137
147
|
{
|
|
138
148
|
"type": "markdown",
|
|
139
149
|
"id": "21eb5354d2adb29e",
|
|
140
|
-
"text": "**Version:** 0.5.1\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
150
|
+
"text": "**Version:** 0.5.1\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
141
151
|
}
|
|
142
152
|
]
|
|
143
153
|
},
|
|
144
154
|
"date": 1783782734556,
|
|
145
|
-
"provenance": "Authored by an AI agent
|
|
155
|
+
"provenance": "Authored by an AI agent \u2014 Claude Fable 5 via the [[fedwiki-page]] skill. [https://claude.com/claude-code Claude Code]"
|
|
146
156
|
},
|
|
147
157
|
{
|
|
148
158
|
"type": "edit",
|
|
@@ -150,7 +160,7 @@
|
|
|
150
160
|
"item": {
|
|
151
161
|
"type": "markdown",
|
|
152
162
|
"id": "28edff984cc5334d",
|
|
153
|
-
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword)
|
|
163
|
+
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword) \u2014 interactive semantic search form\n- `SIMILAR: high|medium|low` \u2014 ambient: pages similar to this page\n- `REPORT` \u2014 server-side ranked, stub-filtered, fork-bundled report\n- `KEYWORD` \u2014 galactic MiniSearch over live site-index.json files\n- `LIST` \u2014 table of indexed domains\n- `AUTHOR` \u2014 search results as a draggable ghost page\n- `BUILD` / `FORCE` \u2014 proxy to the farm indexer, where configured\n- `GHOST url` / `BUTTON label` \u2014 open any page-json as a ghost page\n- `ROSTER site/slug` \u2014 add a roster page's sites to the scope (off-farm sites searched via the galaxy cache)\n- `FARM domain` \u2014 ask a peer farm to continue the search (experimental; requires the peer's `search-peers` roster to allow you)\n- `THRESHOLD: 0.72` \u00b7 `LIMIT: 8` \u00b7 `LIVE` \u2014 tuning"
|
|
154
164
|
},
|
|
155
165
|
"date": 1783800718188
|
|
156
166
|
},
|
|
@@ -160,7 +170,7 @@
|
|
|
160
170
|
"item": {
|
|
161
171
|
"type": "markdown",
|
|
162
172
|
"id": "d9a96dfebb9d1692",
|
|
163
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=`
|
|
173
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `POST /system/peer-search.json` \u2014 answer another farm's search (guarded: allowlist roster, hop limit, replay dedup, rate limit; restricted sites always excluded)\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder."
|
|
164
174
|
},
|
|
165
175
|
"date": 1783800718188
|
|
166
176
|
},
|
|
@@ -170,7 +180,7 @@
|
|
|
170
180
|
"item": {
|
|
171
181
|
"type": "markdown",
|
|
172
182
|
"id": "21eb5354d2adb29e",
|
|
173
|
-
"text": "**Version:** 0.6.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
183
|
+
"text": "**Version:** 0.6.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
174
184
|
},
|
|
175
185
|
"date": 1783800718188
|
|
176
186
|
},
|
|
@@ -180,7 +190,7 @@
|
|
|
180
190
|
"item": {
|
|
181
191
|
"type": "markdown",
|
|
182
192
|
"id": "28edff984cc5334d",
|
|
183
|
-
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword)
|
|
193
|
+
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE):\n\n- (no keyword) \u2014 interactive semantic search form\n- `SIMILAR: high|medium|low` \u2014 ambient: pages similar to this page\n- `REPORT` \u2014 server-side ranked, stub-filtered, fork-bundled report\n- `KEYWORD` \u2014 galactic MiniSearch over live site-index.json files\n- `LIST` \u2014 table of indexed domains\n- `AUTHOR` \u2014 search results as a draggable ghost page\n- `BUILD` / `FORCE` \u2014 proxy to the farm indexer, where configured\n- `GHOST url` / `BUTTON label` \u2014 open any page-json as a ghost page\n- `ROSTER site/slug` \u2014 add a roster page's sites to the scope (off-farm sites searched via the galaxy cache)\n- `FARM domain` \u2014 ask a peer farm to continue the search. The peer answers from exactly the sites whose own [[Federated Farm Search]] page grants your origin (`FROM` lines; `FROM *` needs the peer admin's `WIKI_PEER_FEDERATION=open`)\n- `THRESHOLD: 0.72` \u00b7 `LIMIT: 8` \u00b7 `LIVE` \u2014 tuning"
|
|
184
194
|
},
|
|
185
195
|
"date": 1784591495272
|
|
186
196
|
},
|
|
@@ -190,7 +200,7 @@
|
|
|
190
200
|
"item": {
|
|
191
201
|
"type": "markdown",
|
|
192
202
|
"id": "d9a96dfebb9d1692",
|
|
193
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=`
|
|
203
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `GET /system/peer-hello.json` \u2014 capability probe: version, model, federation status (404 = plugin absent)\n- `POST /system/peer-search.json` \u2014 answer another farm's search. Two keys: the admin's `WIKI_PEER_FEDERATION` ceiling (off / grants / open) and each site's Federated Farm Search grants page; scope = union of granting sites; hop limit, replay dedup, IP-keyed + global rate limits; restricted sites always excluded\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder."
|
|
194
204
|
},
|
|
195
205
|
"date": 1784591495272
|
|
196
206
|
},
|
|
@@ -200,7 +210,7 @@
|
|
|
200
210
|
"item": {
|
|
201
211
|
"type": "markdown",
|
|
202
212
|
"id": "21eb5354d2adb29e",
|
|
203
|
-
"text": "**Version:** 0.7.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
213
|
+
"text": "**Version:** 0.7.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
204
214
|
},
|
|
205
215
|
"date": 1784591495272
|
|
206
216
|
},
|
|
@@ -210,7 +220,7 @@
|
|
|
210
220
|
"item": {
|
|
211
221
|
"type": "markdown",
|
|
212
222
|
"id": "d9a96dfebb9d1692",
|
|
213
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=`
|
|
223
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `GET /system/peer-hello.json` \u2014 capability probe: version, model, federation status (404 = plugin absent)\n- `GET /system/similarity-health.json` \u2014 embedder supervisor state: child-process / semindex / url, breaker status, recent crashes\n- `POST /system/peer-search.json` \u2014 answer another farm's search. Two keys: the admin's `WIKI_PEER_FEDERATION` ceiling (off / grants / open) and each site's Federated Farm Search grants page; scope = union of granting sites; hop limit, replay dedup, IP-keyed + global rate limits; restricted sites always excluded\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder.\n\nSince 0.9.0 all query embedding runs in a supervised child process, never in the wiki server itself: a crash in the ONNX runtime fails that one search, and repeated crashes trip a circuit breaker that answers 503 while cooling down. The worst case for a wiki running this plugin is \"semantic search temporarily unavailable\" \u2014 never a dead wiki."
|
|
214
224
|
},
|
|
215
225
|
"date": 1784706029671
|
|
216
226
|
},
|
|
@@ -220,7 +230,7 @@
|
|
|
220
230
|
"item": {
|
|
221
231
|
"type": "markdown",
|
|
222
232
|
"id": "21eb5354d2adb29e",
|
|
223
|
-
"text": "**Version:** 0.9.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
233
|
+
"text": "**Version:** 0.9.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
224
234
|
},
|
|
225
235
|
"date": 1784706029671
|
|
226
236
|
},
|
|
@@ -230,7 +240,7 @@
|
|
|
230
240
|
"item": {
|
|
231
241
|
"type": "markdown",
|
|
232
242
|
"id": "aec1dfcd5f2bc42b",
|
|
233
|
-
"text": "The Similarity plugin adds search to a Federated Wiki farm
|
|
243
|
+
"text": "The Similarity plugin adds search to a Federated Wiki farm \u2014 semantic similarity over prebuilt vector indexes, ranked search reports, galactic keyword search over each site's own MiniSearch index, and semantic search across the wider federation. One item type \u2014 **similarity** \u2014 with a line-oriented DSL, plus a server component that serves every search same-origin. Works on any host: embedding runs in-process (native ONNX where available, WASM everywhere else)."
|
|
234
244
|
},
|
|
235
245
|
"date": 1785280898931
|
|
236
246
|
},
|
|
@@ -240,7 +250,7 @@
|
|
|
240
250
|
"item": {
|
|
241
251
|
"type": "markdown",
|
|
242
252
|
"id": "28edff984cc5334d",
|
|
243
|
-
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE / GALAXY):\n\n- (no keyword)
|
|
253
|
+
"text": "## The DSL\n\nThe first ALL-CAPS keyword sets the mode; other lines are domain specs (globs, explicit domains, or the scope keywords PUBLIC / LOCAL / PRIVATE / GALAXY):\n\n- (no keyword) \u2014 interactive semantic search form\n- `SIMILAR: high|medium|low` \u2014 ambient: pages similar to this page\n- `REPORT` \u2014 server-side ranked, stub-filtered, fork-bundled report\n- `KEYWORD` \u2014 galactic MiniSearch over live site-index.json files\n- `SITES` \u2014 which site should this page go on? Per-domain aggregation of the page-vector scan: 0.7 \u00d7 mean of the top 5 page similarities + 0.3 \u00d7 site-centroid similarity. Forked pages count for every site that carries them\n- `LIST` \u2014 table of indexed domains\n- `AUTHOR` \u2014 search results as a draggable ghost page\n- `BUILD` / `FORCE` \u2014 proxy to the farm indexer, where configured\n- `GHOST url` / `BUTTON label` \u2014 open any page-json as a ghost page\n- `ROSTER site/slug` \u2014 add a roster page's sites to the scope (off-farm sites searched via the galaxy cache)\n- `FARM domain` \u2014 ask a peer farm to continue the search. The peer answers from exactly the sites whose own [[Federated Farm Search]] page grants your origin (`FROM` lines; `FROM *` needs the peer admin's `WIKI_PEER_FEDERATION=open`)\n- `GALAXY` \u2014 search the off-farm federation sites indexed into this host's galaxy tree. A scope, not a mode: `GALAXY` alone answers only from the federation (the farm's own pages are never swept in, and `*` never includes galaxy sites); `*` and `GALAXY` together search farm and federation as one\n- `SUBJECT` \u2014 act on the previous page in the lineup, the host a tool page was opened beside\n- `THRESHOLD: 0.72` \u00b7 `LIMIT: 8` \u00b7 `LIVE` \u2014 tuning"
|
|
244
254
|
},
|
|
245
255
|
"date": 1785280898931
|
|
246
256
|
},
|
|
@@ -250,7 +260,7 @@
|
|
|
250
260
|
"item": {
|
|
251
261
|
"type": "markdown",
|
|
252
262
|
"id": "d9a96dfebb9d1692",
|
|
253
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `POST /system/site-report.json`
|
|
263
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`\n- `POST /system/site-report.json` \u2014 which site should this page go on? Per-domain aggregation of the page-vector scan: 0.7 \u00d7 mean of the top 5 page similarities + 0.3 \u00d7 site-centroid similarity; forked pages count for every site that carries them\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `GET /system/galaxy-registry.json` \u2014 the galaxy site registry: every federation site known to this host, with provenance, liveness, page counts and scraped site owner (read-only; written by the galaxy indexer host)\n- `GET /system/peer-hello.json` \u2014 capability probe: version, model, federation status (404 = plugin absent)\n- `GET /system/similarity-health.json` \u2014 embedder supervisor state: child-process / semindex / url, breaker status, recent crashes\n- `POST /system/peer-search.json` \u2014 answer another farm's search. Two keys: the admin's `WIKI_PEER_FEDERATION` ceiling (off / grants / open) and each site's Federated Farm Search grants page; scope = union of granting sites; hop limit, replay dedup, IP-keyed + global rate limits; restricted sites always excluded\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder.\n\nSince 0.9.0 all query embedding runs in a supervised child process, never in the wiki server itself: a crash in the ONNX runtime fails that one search, and repeated crashes trip a circuit breaker that answers 503 while cooling down. The worst case for a wiki running this plugin is \"semantic search temporarily unavailable\" \u2014 never a dead wiki.\n\nSince 0.11.0 a third index tier sits beside the farm: the **galaxy** \u2014 a farm-shaped tree of off-farm federation sites, built by a separate indexer and read through a byte-capped vector cache (`WIKI_GALAXY_VECTOR_CACHE_MB`, default 512). Galaxy entries carry their enrichment precomputed, because off-farm pages have no local page JSON to read; the stub filter, fork bundling and scoring then run unchanged, so federation results rank directly against farm results."
|
|
254
264
|
},
|
|
255
265
|
"date": 1785280898931
|
|
256
266
|
},
|
|
@@ -260,7 +270,7 @@
|
|
|
260
270
|
"item": {
|
|
261
271
|
"type": "markdown",
|
|
262
272
|
"id": "21eb5354d2adb29e",
|
|
263
|
-
"text": "**Version:** 0.11.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
273
|
+
"text": "**Version:** 0.11.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
264
274
|
},
|
|
265
275
|
"date": 1785280898931
|
|
266
276
|
},
|
|
@@ -270,7 +280,7 @@
|
|
|
270
280
|
"item": {
|
|
271
281
|
"type": "markdown",
|
|
272
282
|
"id": "d9a96dfebb9d1692",
|
|
273
|
-
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json`
|
|
283
|
+
"text": "## Server Routes\n\nAll same-origin, registered by the plugin's server component:\n\n- `GET /system/indexed-domains.json?pattern=`\n- `GET /system/semantic-vectors.json?domain=`\n- `GET /system/embed.json?text=`\n- `POST /system/search-report.json` \u2014 accepts an optional `author`: a display name or account username, resolved against this farm's own site ownership (each site's `owner.json`) and intersected with the requested scope. An ambiguous name answers 409 with the competing usernames rather than guessing\n- `POST /system/site-report.json` \u2014 which site should this page go on? Per-domain aggregation of the page-vector scan: 0.7 \u00d7 mean of the top 5 page similarities + 0.3 \u00d7 site-centroid similarity; forked pages count for every site that carries them\n- `GET /system/farm-search.json?q=&pattern=&limit=`\n- `GET /system/build-index.json?domains=` (proxied to the farm indexer)\n- `GET /system/galaxy-search.json?q=&sites=` \u2014 keyword search over off-farm federation sites\n- `GET /system/galaxy-registry.json` \u2014 the galaxy site registry: every federation site known to this host, with provenance, liveness, page counts and scraped site owner (read-only; written by the galaxy indexer host)\n- `GET /system/peer-hello.json` \u2014 capability probe: version, model, federation status (404 = plugin absent)\n- `GET /system/similarity-health.json` \u2014 embedder supervisor state: child-process / semindex / url, breaker status, recent crashes\n- `POST /system/peer-search.json` \u2014 answer another farm's search. An optional `author` travels as the plain name asked for, never a resolved username: the answering farm resolves it against its OWN records and reports `applied`, `ignored` (no records kept) or `ambiguous`. Two keys: the admin's `WIKI_PEER_FEDERATION` ceiling (off / grants / open) and each site's Federated Farm Search grants page; scope = union of granting sites; hop limit, replay dedup, IP-keyed + global rate limits; restricted sites always excluded\n\nIndexes are `status/semantic-vectors.json` per domain \u2014 built by the farm indexer, distributed by sync, read from farm disk. Keyword search reads each site's per-edit `status/site-index.json`; no separate index is built. Query embedding is BAAI bge-small-en-v1.5, 384-dim, CLS-pooled, unit-normalised \u2014 byte-compatible with the index builder.\n\nSince 0.9.0 all query embedding runs in a supervised child process, never in the wiki server itself: a crash in the ONNX runtime fails that one search, and repeated crashes trip a circuit breaker that answers 503 while cooling down. The worst case for a wiki running this plugin is \"semantic search temporarily unavailable\" \u2014 never a dead wiki.\n\nSince 0.11.0 a third index tier sits beside the farm: the **galaxy** \u2014 a farm-shaped tree of off-farm federation sites, built by a separate indexer and read through a byte-capped vector cache (`WIKI_GALAXY_VECTOR_CACHE_MB`, default 512). Galaxy entries carry their enrichment precomputed, because off-farm pages have no local page JSON to read; the stub filter, fork bundling and scoring then run unchanged, so federation results rank directly against farm results.\n\nSince 0.12.0 the plugin also offers a **Semantic Search** page through the wiki's \u2630 menu, declared by a `pages` entry in `factory.json` and shipped in the package."
|
|
274
284
|
},
|
|
275
285
|
"date": 1785397304700
|
|
276
286
|
},
|
|
@@ -280,7 +290,7 @@
|
|
|
280
290
|
"item": {
|
|
281
291
|
"type": "markdown",
|
|
282
292
|
"id": "21eb5354d2adb29e",
|
|
283
|
-
"text": "**Version:** 0.12.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub]
|
|
293
|
+
"text": "**Version:** 0.12.0\n\n# Links\n\n- [https://github.com/Hitchhikers-Guide-to-the-Galaxy/wiki-plugin-similarity GitHub repository]\n- [https://www.npmjs.com/package/wiki-plugin-similarity npm package]\n- [https://plugin.fedwiki.club/similarity-plugin.html Plugin documentation]\n- [https://search.fedwiki.club/ Search hub] \u2014 architecture, indexing, freshness."
|
|
284
294
|
},
|
|
285
295
|
"date": 1785397304700
|
|
286
296
|
}
|
package/server/server.js
CHANGED
|
@@ -17,7 +17,11 @@
|
|
|
17
17
|
// Set WIKI_EMBED_URL to proxy to an external embedder instead.
|
|
18
18
|
// GET /system/similarity-health.json
|
|
19
19
|
// Embedder supervisor state (child-process | semindex | url, breaker,
|
|
20
|
-
// recent crashes) — 200 always; diagnosable from outside.
|
|
20
|
+
// recent crashes) — 200 always; diagnosable from outside. Since 0.14.0 a
|
|
21
|
+
// url embedder also reports the source it came from (env | file), and
|
|
22
|
+
// localEmbedderAvailable says whether this box could embed unaided — the
|
|
23
|
+
// local path is never exercised while a proxy is set, so nothing else
|
|
24
|
+
// answers that question from outside.
|
|
21
25
|
// POST /system/search-report.json {query, domains, limit, threshold, live,
|
|
22
26
|
// vector?, seed?, text?, excludePage?}
|
|
23
27
|
// Ranked, stub-filtered, fork-bundled semantic report (page JSON).
|
|
@@ -82,7 +86,30 @@ const PLUGIN_VERSION = (() => {
|
|
|
82
86
|
})()
|
|
83
87
|
|
|
84
88
|
// Optional external embedder (proxy) — unset means embed in-process.
|
|
85
|
-
|
|
89
|
+
//
|
|
90
|
+
// Validated since 0.14.0. The public farm was set to the literal string
|
|
91
|
+
// "disabled", which is truthy, so every query was POSTed to a URL that does
|
|
92
|
+
// not parse and semantic search was dead farm-wide. A value that is not an
|
|
93
|
+
// http(s) URL now means what whoever typed it meant: no proxy.
|
|
94
|
+
const httpUrlOrNull = raw => {
|
|
95
|
+
if (!raw) return null
|
|
96
|
+
try {
|
|
97
|
+
const u = new URL(raw)
|
|
98
|
+
if (u.protocol === 'http:' || u.protocol === 'https:') return raw
|
|
99
|
+
} catch { /* not a URL at all */ }
|
|
100
|
+
return null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const ENV_EMBED_URL = (() => {
|
|
104
|
+
const raw = process.env.WIKI_EMBED_URL
|
|
105
|
+
if (!raw) return null
|
|
106
|
+
const ok = httpUrlOrNull(raw)
|
|
107
|
+
if (!ok) {
|
|
108
|
+
console.log('[wiki-plugin-similarity] WIKI_EMBED_URL is not an http(s) URL ' +
|
|
109
|
+
`(${JSON.stringify(raw)}) — ignoring it and embedding in-process`)
|
|
110
|
+
}
|
|
111
|
+
return ok
|
|
112
|
+
})()
|
|
86
113
|
// Farm indexer for BUILD requests (HomeLab FastAPI, or unset on the public farm).
|
|
87
114
|
const INDEXER_URL = process.env.WIKI_INDEXER_URL || null
|
|
88
115
|
// Optional additional farm roots, colon-separated absolute paths.
|
|
@@ -96,13 +123,18 @@ const TRUSTED_NETS = parseNets()
|
|
|
96
123
|
|
|
97
124
|
// ── HTTP helpers ──────────────────────────────────────────────────────────────
|
|
98
125
|
|
|
126
|
+
// Pick the agent by protocol. Before 0.14.0 both helpers were http-only with
|
|
127
|
+
// port 80 hard-defaulted, so an https:// embed URL silently failed — the
|
|
128
|
+
// delegation path could never have worked across the public internet.
|
|
129
|
+
const agentFor = u => (u.protocol === 'https:' ? https : http)
|
|
130
|
+
|
|
99
131
|
const postJson = (url, body) =>
|
|
100
132
|
new Promise((resolve, reject) => {
|
|
101
133
|
const payload = JSON.stringify(body)
|
|
102
134
|
const u = new URL(url)
|
|
103
135
|
const opts = {
|
|
104
136
|
hostname: u.hostname,
|
|
105
|
-
port: u.port || 80,
|
|
137
|
+
port: u.port || (u.protocol === 'https:' ? 443 : 80),
|
|
106
138
|
path: u.pathname + u.search,
|
|
107
139
|
method: 'POST',
|
|
108
140
|
headers: {
|
|
@@ -110,7 +142,7 @@ const postJson = (url, body) =>
|
|
|
110
142
|
'Content-Length': Buffer.byteLength(payload),
|
|
111
143
|
},
|
|
112
144
|
}
|
|
113
|
-
const req =
|
|
145
|
+
const req = agentFor(u).request(opts, res => {
|
|
114
146
|
let data = ''
|
|
115
147
|
res.on('data', chunk => { data += chunk })
|
|
116
148
|
res.on('end', () => {
|
|
@@ -126,7 +158,7 @@ const postJson = (url, body) =>
|
|
|
126
158
|
const getJson = url =>
|
|
127
159
|
new Promise((resolve, reject) => {
|
|
128
160
|
const u = new URL(url)
|
|
129
|
-
|
|
161
|
+
agentFor(u).get(u, res => {
|
|
130
162
|
let data = ''
|
|
131
163
|
res.on('data', chunk => { data += chunk })
|
|
132
164
|
res.on('end', () => {
|
|
@@ -150,6 +182,45 @@ const readBody = req =>
|
|
|
150
182
|
})
|
|
151
183
|
|
|
152
184
|
|
|
185
|
+
// ── Embed URL from the farm root ──────────────────────────────────────────────
|
|
186
|
+
// Where the environment is not ours to set — the public farm's stack belongs to
|
|
187
|
+
// its host — the address may instead come from a file in the farm root:
|
|
188
|
+
//
|
|
189
|
+
// {farmRoot}/similarity.json { "embedUrl": "https://host/system/…" }
|
|
190
|
+
//
|
|
191
|
+
// Cached by mtime so a synced edit retargets the embedder with no restart, the
|
|
192
|
+
// same discipline wiki-plugin-farm's keys.js uses for status/api-keys.json.
|
|
193
|
+
// The file is never served over HTTP; writing it means write access to the farm.
|
|
194
|
+
let cfgCache = null // { mtimeMs, embedUrl }
|
|
195
|
+
|
|
196
|
+
const fileEmbedUrl = farmRoot => {
|
|
197
|
+
const file = path.join(farmRoot, 'similarity.json')
|
|
198
|
+
let stat
|
|
199
|
+
try { stat = fs.statSync(file) } catch { cfgCache = null; return null }
|
|
200
|
+
if (cfgCache && cfgCache.mtimeMs === stat.mtimeMs) return cfgCache.embedUrl
|
|
201
|
+
let embedUrl = null
|
|
202
|
+
try {
|
|
203
|
+
const cfg = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
204
|
+
embedUrl = httpUrlOrNull(cfg.embedUrl)
|
|
205
|
+
if (cfg.embedUrl && !embedUrl) {
|
|
206
|
+
console.log(`caution: ${file}: embedUrl is not an http(s) URL — ignoring it`)
|
|
207
|
+
}
|
|
208
|
+
} catch (e) {
|
|
209
|
+
console.log(`caution: ${file}: ${e.message}`)
|
|
210
|
+
}
|
|
211
|
+
cfgCache = { mtimeMs: stat.mtimeMs, embedUrl }
|
|
212
|
+
return embedUrl
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Can this process turn text into a vector without leaving the box? Reported by
|
|
216
|
+
// the health route even when a proxy is configured, because with a proxy set the
|
|
217
|
+
// local path is never exercised and the logs stay silent about it — which is
|
|
218
|
+
// exactly the question that was unanswerable on the public farm.
|
|
219
|
+
const localEmbedderAvailable = () => {
|
|
220
|
+
if (embedder.viaSemindex) return true
|
|
221
|
+
try { require.resolve('@xenova/transformers'); return true } catch { return false }
|
|
222
|
+
}
|
|
223
|
+
|
|
153
224
|
// ── startServer — called by wiki-server/lib/plugins.js ────────────────────────
|
|
154
225
|
|
|
155
226
|
setModelMeta(MODEL_META)
|
|
@@ -157,6 +228,10 @@ setModelMeta(MODEL_META)
|
|
|
157
228
|
const startServer = ({ argv, app }) => {
|
|
158
229
|
// Farm root: argv.status = {farm}/{thisDomain}/status → go up two levels
|
|
159
230
|
const farmRoot = path.dirname(path.dirname(argv.status))
|
|
231
|
+
|
|
232
|
+
// env wins; then the farm-root file; then embed in-process.
|
|
233
|
+
const embedUrl = () => ENV_EMBED_URL || fileEmbedUrl(farmRoot)
|
|
234
|
+
const embedUrlSource = () => (ENV_EMBED_URL ? 'env' : (fileEmbedUrl(farmRoot) ? 'file' : null))
|
|
160
235
|
// primary farm is 'local'; extra farms (Nextcloud mirror) are 'public'.
|
|
161
236
|
// The galaxy tree (off-farm federation sites, written by the galaxy
|
|
162
237
|
// indexer) joins as kind 'galaxy' when present — never matched by '*',
|
|
@@ -188,10 +263,11 @@ const startServer = ({ argv, app }) => {
|
|
|
188
263
|
`| trusted nets: ${TRUSTED_NETS.join(' ')}`)
|
|
189
264
|
|
|
190
265
|
// Warm the embedding model in the background so the first query is fast.
|
|
191
|
-
if (!
|
|
266
|
+
if (!embedUrl()) embedder.warm()
|
|
192
267
|
|
|
193
268
|
async function embedText(text) {
|
|
194
|
-
|
|
269
|
+
const url = embedUrl()
|
|
270
|
+
if (url) return (await postJson(url, { text })).vector
|
|
195
271
|
return embedder.embed(text)
|
|
196
272
|
}
|
|
197
273
|
|
|
@@ -319,7 +395,11 @@ const startServer = ({ argv, app }) => {
|
|
|
319
395
|
plugin: 'wiki-plugin-similarity',
|
|
320
396
|
version: PLUGIN_VERSION,
|
|
321
397
|
...MODEL_META,
|
|
322
|
-
embedder:
|
|
398
|
+
embedder: (() => {
|
|
399
|
+
const url = embedUrl()
|
|
400
|
+
return url ? { via: 'url', url, source: embedUrlSource() } : embedder.status()
|
|
401
|
+
})(),
|
|
402
|
+
localEmbedderAvailable: localEmbedderAvailable(),
|
|
323
403
|
galaxy: fs.existsSync(galaxyDir)
|
|
324
404
|
? { root: galaxyDir, cache: galaxyCacheStats() }
|
|
325
405
|
: null,
|
|
@@ -636,4 +716,6 @@ const startServer = ({ argv, app }) => {
|
|
|
636
716
|
console.log('[wiki-plugin-similarity] routes registered')
|
|
637
717
|
}
|
|
638
718
|
|
|
639
|
-
|
|
719
|
+
// httpUrlOrNull and fileEmbedUrl are exported for the tests: they decide whether
|
|
720
|
+
// this farm embeds for itself or delegates, which is worth pinning down.
|
|
721
|
+
module.exports = { startServer, httpUrlOrNull, fileEmbedUrl, localEmbedderAvailable }
|