Smarter chatbot + support matching by meaning (Marty 2026-11-16): the hub's semantic match (free core2 embeddings)
Chatbot (chatbot.js + netkb.js route): a hand-off pattern still answers first; then the hub's POST /v1/kb/match answers with this site's entry when it is sure, keeps or overrules the CANNED regex hit, and picks the AI prompt context, this site's own entries first. 1.5 s timeout, then the hub is skipped for 30 s and the old pattern + BM25 path answers (NETKB_MATCH=0 = off). Support desk: while a signed-in member types a new ticket, POST /api/my/support/suggest shows the closest help answers (KB entries only, incl. ones written from past tickets, never another member's ticket; BM25 when the hub is down); Send is never blocked. support.js?v=20261116sg. Tests: qa/netkb-semantic.test.mjs (route/suggest decisions, fail soft, shared-file parity; run.sh kb) and qa/support-suggest.mjs (run.sh member). netkb.js is the same file in all eight network sites. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+10
-4
@@ -528,14 +528,20 @@ async function answerRaw(message, historyText) {
|
||||
const msg = String(message || '').trim();
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||
let hit = null, kbOk = true;
|
||||
let hit = null, kbOk = true, other = [];
|
||||
try {
|
||||
await kb.load();
|
||||
// another network site named (and this one not): this site's instant answers stand aside, except a hand-off (2026-11-15)
|
||||
const other = /instant ?ad ?pay|\biap\b/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'iap');
|
||||
other = /instant ?ad ?pay|\biap\b/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'iap');
|
||||
hit = await kb.fastPath(msg);
|
||||
if (hit && other.length && !hit.handoff) hit = null;
|
||||
} catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
// a hand-off answers from its exact pattern before anything else; then meaning (2026-11-16, netkb.route): the hub's semantic match
|
||||
// over the network KB answers, keeps or overrules the pattern hit and picks the prompt context. Hub or model slow or down: null,
|
||||
// and the pattern + BM25 path below runs exactly as before.
|
||||
let sem = null;
|
||||
if (kbOk && !(hit && hit.handoff)) { try { sem = await netkb.route(msg, { fast: hit, own: await kb.own(), prefer: other }); } catch (e) { sem = null; } }
|
||||
if (sem) hit = sem.hit;
|
||||
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
|
||||
@@ -544,13 +550,13 @@ async function answerRaw(message, historyText) {
|
||||
if (hit && (hit.id === 'warpwares' || hit.id === 'c-warpwares') && !wwLive()) return { reply: wwAnswer(), canned: true, kb: hit.id };
|
||||
if (hit && isBixId(hit.id) && !bixLive()) return { reply: BIX_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && (SYN_N() !== 4 || SYN_T() !== 10)) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'warpwares' && !wwLive() ? { reply: wwAnswer(), canned: true } : isBixId(c.id) && !bixLive() ? { reply: BIX_SOON_ANSWER, canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||
let kbBlock = '', kbIds = [];
|
||||
try {
|
||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||
const hits = await kb.context(query, 5);
|
||||
const hits = sem && sem.hits.length ? sem.hits : await kb.context(query, 5); // the semantic context when the hub answered (2026-11-16)
|
||||
const hitsOk = hits.filter(h => (pmLive() || !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))) && (wwLive() || !/^(c-)?warpwares$/.test(String(h.entry && h.entry.id))) && (bixLive() || !isBixId(h.entry && h.entry.id)) && (tdLive() || !/^(c-)?turkeydrop$/.test(String(h.entry && h.entry.id)))); // not live yet: keep its answer out of the prompt
|
||||
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
|
||||
} catch (e) { console.error('kb search', e.message); }
|
||||
|
||||
@@ -6,6 +6,17 @@
|
||||
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||
//
|
||||
// SEMANTIC MATCHING (Marty 2026-11-16): the hub matches a question by meaning against the whole network KB with the free core2
|
||||
// embeddings model (POST HUB_URL/v1/kb/match). match() asks it with a strict timeout (NETKB_MATCH_MS, default 1500) and fails
|
||||
// soft: an error or a timeout answers null and the next MATCH_PAUSE_MS skip the hub, so the chat never waits on a slow model and
|
||||
// the site's own BM25 retrieval (kb.js) answers as before. route() turns a match into the chatbot's decision:
|
||||
// - this site's own entry, raw score >= SEM.answer with a clear lead (or the instant-answer pattern agrees): the answer itself
|
||||
// - the instant-answer pattern hit kept when the match agrees (its entry within SEM.agree of the top), or when the match has
|
||||
// no idea (top below SEM.unsure); this site's own entries rank first unless another site is named or clearly closer
|
||||
// - otherwise no instant answer (the regex is overruled by meaning); the entries >= SEM.context feed the AI prompt
|
||||
// suggest() gives the support desk's new-ticket form the closest help answers (KB entries only) the same way, BM25 as the fallback.
|
||||
// Off with NETKB_MATCH=0. Thresholds measured on bge-large-en-v1.5 over the network KB (2026-11-16). Tests: qa/netkb-semantic.test.mjs
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||
// Banners, Stack POL). Keep them identical.
|
||||
'use strict';
|
||||
@@ -24,10 +35,10 @@ const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim(
|
||||
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||
|
||||
async function call(method, route, body, headers) {
|
||||
async function call(method, route, body, headers, timeoutMs) {
|
||||
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(timeoutMs || 15000),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||
return { status: r.status, body: j };
|
||||
@@ -90,6 +101,92 @@ function sites() {
|
||||
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||
}
|
||||
|
||||
// ---- semantic matching (2026-11-16)
|
||||
const SEM = { answer: Number(process.env.NETKB_SEM_ANSWER) || 0.84, margin: 0.02, context: Number(process.env.NETKB_SEM_CONTEXT) || 0.68, unsure: 0.70, band: 0.08, away: 0.06, agree: 0.10, floor: 0.60 };
|
||||
const MATCH_PAUSE_MS = 30000;
|
||||
let matchDownUntil = 0;
|
||||
const mstats = { matches: 0, matchErrors: 0, matchSkipped: 0, matchLastMs: 0, matchLastError: null, semAnswer: 0, semAgree: 0, semRegex: 0, semVeto: 0, semContext: 0 };
|
||||
const matchOn = () => enabled() && process.env.NETKB_MATCH !== '0';
|
||||
// -> the hub's answer {confidence, margin, hits: [{site, id, title, answer, score, boosted, home}]} or null (off, down, slow)
|
||||
async function match(q, o) {
|
||||
o = o || {};
|
||||
if (!matchOn()) return null;
|
||||
if (Date.now() < matchDownUntil) { mstats.matchSkipped++; return null; }
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const body = { q: String(q || '').slice(0, 600), k: o.k || 6 };
|
||||
if (o.prefer && o.prefer.length) body.prefer = o.prefer;
|
||||
if (o.only && o.only.length) body.only = o.only;
|
||||
const r = await call('POST', '/v1/kb/match', body, undefined, o.timeoutMs || Number(process.env.NETKB_MATCH_MS) || 1500);
|
||||
mstats.matchLastMs = Date.now() - t0;
|
||||
if (r.status !== 200 || !r.body || !Array.isArray(r.body.hits)) throw new Error('match ' + r.status + ' ' + ((r.body && r.body.error) || ''));
|
||||
mstats.matches++;
|
||||
return r.body;
|
||||
} catch (e) { mstats.matchErrors++; mstats.matchLastError = e.message; matchDownUntil = Date.now() + MATCH_PAUSE_MS; return null; }
|
||||
}
|
||||
// msg + { fast: the instant-answer pattern hit (or null), own: this site's entries, prefer: [site ids the question names] }
|
||||
// -> null (no match: the caller keeps its old path) or { via, hit: own entry to answer with | null, hits: [{entry, score}] for the prompt }
|
||||
async function route(msg, o) {
|
||||
o = o || {};
|
||||
// a question that names another site but asks about "here" is about this site (e.g. "I am on InstantAdPay, does my team carry over here?")
|
||||
const prefer = (o.prefer || []).length && !/\b(here|this site|this one)\b/i.test(msg) ? o.prefer : [];
|
||||
const m = await match(msg, { k: 8, prefer });
|
||||
if (!m) return null;
|
||||
const me = siteName();
|
||||
const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||
const rem = new Map(remote().map(e => [e.id, e]));
|
||||
const all = m.hits.map(h => ({ entry: h.site === me ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id), score: Number(h.score) || 0, home: h.site === me })).filter(h => h.entry);
|
||||
let hits = all;
|
||||
const named = prefer.length > 0, fast = o.fast || null;
|
||||
if (!named) { // home-site first: this site's own entries lead; another site's ride behind them only when clearly closer (a thing only that site has)
|
||||
const mine = hits.filter(h => h.home && h.score >= SEM.context);
|
||||
const homeTop = mine.length ? mine[0].score : 0;
|
||||
hits = mine.concat(hits.filter(h => !h.home && h.score >= homeTop + SEM.away));
|
||||
}
|
||||
const top = hits[0];
|
||||
const ctx = top ? hits.filter(h => h.score >= SEM.context && (h.score >= top.score - SEM.band || !h.home)).map(h => ({ entry: h.entry, score: Math.round(h.score * 1000) / 1000 })) : [];
|
||||
const out = (via, hit) => { mstats['sem' + via[0].toUpperCase() + via.slice(1)]++; return { via, hit, hits: ctx, confidence: top ? top.score : 0 }; };
|
||||
if (top && top.home && !named && top.score >= SEM.answer && (Number(m.margin) >= SEM.margin || (fast && String(fast.id) === String(top.entry.id)))) return out('answer', top.entry);
|
||||
if (fast) {
|
||||
const best = all.length ? all[0].score : 0;
|
||||
if (all.some(h => h.home && String(h.entry.id) === String(fast.id) && h.score >= SEM.floor && h.score >= best - SEM.agree)) return out('agree', fast);
|
||||
if (!top || top.score < SEM.unsure) return out('regex', fast);
|
||||
return out('veto', null);
|
||||
}
|
||||
return out('context', null);
|
||||
}
|
||||
|
||||
// support desk suggestions (2026-11-16): the help answers closest to what a signed-in member is typing into a new ticket.
|
||||
// Knowledge-base entries only (published answers, including the ones written from past tickets), never anyone's ticket text.
|
||||
// text + { own: this site's entries, fallback: async q => [{entry}] (BM25) when the hub is slow or down, max }
|
||||
const SUGGEST_MIN = Number(process.env.NETKB_SUGGEST_MIN) || 0.70;
|
||||
const NOT_SUGGESTED = /(^|[-:])support$|^c-refund$/; // the "contact support" entry is no help on the support form itself
|
||||
function suggestItem(e, home, score) {
|
||||
return { id: String(e.id), title: e.title, answer: String(e.answer || '').slice(0, 900), site: home ? '' : (e.siteName || e.site || ''),
|
||||
link: home ? (e.link || '') : (e.go || e.siteUrl || ''), fromTicket: !!(home && e.source === 'ticket'), score: score == null ? null : Math.round(score * 1000) / 1000 };
|
||||
}
|
||||
async function suggest(text, o) {
|
||||
o = o || {};
|
||||
const q = String(text || '').replace(/\s+/g, ' ').trim().slice(0, 600);
|
||||
if (q.replace(/[^A-Za-z0-9]/g, '').length < 10) return { items: [], via: 'short' };
|
||||
const me = siteName(); const own = new Map((o.own || []).map(e => [String(e.id), e]));
|
||||
const keep = (e, home) => e && !(home && e.handoff) && !NOT_SUGGESTED.test(String(e.id));
|
||||
let items = [], via = 'none';
|
||||
const m = await match(q, { k: 8, timeoutMs: o.timeoutMs || 2000 });
|
||||
if (m) {
|
||||
via = 'semantic'; const top = m.hits.length ? Number(m.hits[0].score) : 0; const rem = new Map(remote().map(e => [e.id, e]));
|
||||
for (const h of m.hits) {
|
||||
if (h.score < SUGGEST_MIN || h.score < top - 0.08) continue;
|
||||
const home = h.site === me; const e = home ? own.get(String(h.id)) : rem.get(h.site + ':' + h.id);
|
||||
if (keep(e, home)) items.push(suggestItem(e, home, h.score));
|
||||
}
|
||||
} else if (typeof o.fallback === 'function') {
|
||||
via = 'bm25';
|
||||
try { for (const x of (await o.fallback(q)) || []) { const e = x && x.entry; const home = !!e && !e.site; if (keep(e, home)) items.push(suggestItem(e, home, null)); } } catch (e) {}
|
||||
}
|
||||
return { items: items.slice(0, o.max || 3), via };
|
||||
}
|
||||
|
||||
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
|
||||
function init(opts) {
|
||||
O = opts || {}; readCache();
|
||||
@@ -99,8 +196,9 @@ function init(opts) {
|
||||
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); }
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt, semantic: matchOn(), sem: SEM }, stats, mstats); }
|
||||
function _set(m) { merged = m; } // tests
|
||||
|
||||
const version = () => merged.version || '';
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };
|
||||
function _matchReset() { matchDownUntil = 0; } // tests
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, match, route, suggest, SEM, _set, _matchReset };
|
||||
|
||||
@@ -25,7 +25,8 @@ window.IAPSupport = (function () {
|
||||
+ '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:var(--ground-soft)}.sup-msg.admin{border-color:var(--mint-line);background:var(--mint-faint)}.sup-msg.system{opacity:.8}'
|
||||
+ '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}'
|
||||
+ '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}'
|
||||
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}';
|
||||
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}'
|
||||
+ '.sup-suggest{border:1px solid var(--mint-line);border-radius:12px;padding:10px 14px;margin:10px 0 0;background:var(--mint-faint)}.sup-sg{margin:4px 0}.sup-sg summary{cursor:pointer;font-weight:700;font-size:14px}.sup-sg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:14px;line-height:1.5;margin:6px 0 8px}';
|
||||
document.head.appendChild(st);
|
||||
})();
|
||||
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
|
||||
@@ -91,9 +92,11 @@ window.IAPSupport = (function () {
|
||||
+ '<label for="hnCat">What is it about?</label><select id="hnCat">' + catOptions('') + '</select>'
|
||||
+ '<label for="hnSubject">Subject</label><input id="hnSubject" maxlength="140" placeholder="A few words, like: my payout did not arrive">'
|
||||
+ '<label for="hnBody">Message</label><textarea id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
|
||||
+ '<div id="hnSuggest" class="sup-suggest" hidden aria-live="polite"></div>'
|
||||
+ attachRow('hn')
|
||||
+ '<div class="sup-actions"><button class="btn small" type="button" id="hnSend">Send to support</button><button class="btn small sec" type="button" id="hnCancel">Cancel</button><span class="small muted" id="hnMsg"></span></div></div>';
|
||||
const atts = wireAttach('hn');
|
||||
wireSuggest();
|
||||
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
||||
const send = document.getElementById('hnSend');
|
||||
send.addEventListener('click', async () => {
|
||||
@@ -107,6 +110,27 @@ window.IAPSupport = (function () {
|
||||
});
|
||||
document.getElementById('hnSubject').focus();
|
||||
}
|
||||
// help answers while typing (2026-11-16): debounced, from the KB only (the hub's semantic match); a suggestion never blocks Send
|
||||
function wireSuggest() {
|
||||
const box = document.getElementById('hnSuggest'), subj = document.getElementById('hnSubject'), body = document.getElementById('hnBody');
|
||||
if (!box || !subj || !body) return;
|
||||
let timer = null, seq = 0, last = '';
|
||||
const run = async () => {
|
||||
const text = (subj.value + ' ' + body.value).replace(/\s+/g, ' ').trim();
|
||||
if (text.replace(/[^A-Za-z0-9]/g, '').length < 10) { box.hidden = true; box.innerHTML = ''; last = ''; return; }
|
||||
if (text === last) return; last = text; const mine = ++seq;
|
||||
let r; try { r = await call('/api/my/support/suggest', { subject: subj.value, body: body.value }); } catch (e) { return; }
|
||||
if (mine !== seq || !document.body.contains(box)) return;
|
||||
const items = (r && r.items) || [];
|
||||
if (!items.length) { box.hidden = true; box.innerHTML = ''; return; }
|
||||
box.innerHTML = '<p class="small" style="margin:0 0 6px"><b>These answers may help</b> <span class="muted">You can still send your ticket.</span></p>'
|
||||
+ items.map(i => '<details class="sup-sg"><summary>' + esc(i.title) + (i.site ? ' <span class="muted small">(' + esc(i.site) + ')</span>' : '') + (i.fromTicket ? ' <span class="muted small">from a past ticket</span>' : '') + '</summary>'
|
||||
+ '<div class="sm-body">' + linkify(i.answer) + (i.link && i.site ? '<br><a href="' + esc(i.link) + '" target="_blank" rel="noopener">Open ' + esc(i.site) + '</a>' : '') + '</div></details>').join('');
|
||||
box.hidden = false;
|
||||
};
|
||||
const kick = () => { clearTimeout(timer); timer = setTimeout(run, 700); };
|
||||
subj.addEventListener('input', kick); body.addEventListener('input', kick);
|
||||
}
|
||||
async function openMine(ref) {
|
||||
const host = document.getElementById('helpBody'); if (!host) return;
|
||||
helpState.open = ref;
|
||||
|
||||
+1
-1
@@ -1310,7 +1310,7 @@
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20261103gp"></script>
|
||||
<script src="/assets/support.js?v=20261115cb"></script>
|
||||
<script src="/assets/support.js?v=20261116sg"></script>
|
||||
<script src="/assets/netkits.js?v=20261115nk"></script>
|
||||
<script src="/assets/my.js?v=20261115hub"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script><script src="/assets/tankfeed.js?v=20261115tb"></script>
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261115nr"></script><script src="/assets/welcome.js?v=20261115la"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
<script src="/assets/support.js?v=20261115cb"></script>
|
||||
<script src="/assets/support.js?v=20261116sg"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Semantic matching, site side (netkb.js route/suggest/match, 2026-11-16) + parity of the shared files: node qa/netkb-semantic.test.mjs
|
||||
// A stand-in hub answers /v1/kb/match with scripted hits, so no model and no network. Checks: a sure match answers with this site's
|
||||
// entry, a pattern hit is kept when the match agrees or has no idea and overruled when the match points elsewhere, other sites'
|
||||
// entries rank behind this site's unless named or clearly closer, a named site that asks about "here" stays home, a slow or down hub
|
||||
// answers null inside the timeout and is skipped for a while (fail soft), and the support suggestions never offer the contact-support entry.
|
||||
// Parity: netkb.js is the same file in all eight network sites, chatcore.js + kb.js in the six that share them (checked against the
|
||||
// sibling checkouts beside this one; a missing sibling is skipped, a different one fails).
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline Banners, Stack POL).
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
let pass = 0, fail = 0, skip = 0;
|
||||
const ok = (c, m) => { if (c) pass++; else { fail++; console.log('FAIL', m); } };
|
||||
|
||||
// ---- parity with the sibling checkouts
|
||||
const sha = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex');
|
||||
const SIBLINGS = ['onchain-ad-membership/site', 'linkspin/site', 'vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol'];
|
||||
const KIT = new Set(['vbb/app', 'banner-line/app', 'viraladblitz/app', 'downlinehydra/app', '5xyourteam/app', 'stackpol']);
|
||||
let base = ROOT; for (let i = 0; i < 4 && !SIBLINGS.some(s => path.resolve(base, s) === ROOT); i++) base = path.dirname(base);
|
||||
const mine = SIBLINGS.find(s => path.resolve(base, s) === ROOT);
|
||||
for (const s of SIBLINGS) {
|
||||
if (s === mine) continue;
|
||||
const dir = path.resolve(base, s);
|
||||
const files = ['netkb.js'].concat(mine && KIT.has(mine) && KIT.has(s) ? ['chatcore.js', 'kb.js'] : []);
|
||||
for (const f of files) {
|
||||
if (!fs.existsSync(path.join(dir, f))) { skip++; continue; }
|
||||
ok(sha(path.join(dir, f)) === sha(path.join(ROOT, f)), 'parity: ' + f + ' differs from ' + s + '/' + f);
|
||||
}
|
||||
}
|
||||
ok(/The SAME file ships in every network site/.test(fs.readFileSync(path.join(ROOT, 'netkb.js'), 'utf8')), 'netkb.js carries the shared-file header');
|
||||
|
||||
// ---- a stand-in hub
|
||||
let script = () => ({ hits: [], margin: 0 }), delay = 0, status = 200, last = null;
|
||||
const hub = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
|
||||
last = { path: req.url, body: JSON.parse(b || '{}'), site: req.headers['x-hub-site'] };
|
||||
setTimeout(() => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(status === 200 ? Object.assign({ ok: true }, script(last.body)) : { error: 'embeddings_down' })); }, delay);
|
||||
}); });
|
||||
await new Promise(r => hub.listen(0, '127.0.0.1', r));
|
||||
process.env.HUB_URL = 'http://127.0.0.1:' + hub.address().port; process.env.HUB_SECRET = 'q'.repeat(40); process.env.HUB_SITE = 'home'; process.env.NETKB_MATCH_MS = '400';
|
||||
delete process.env.NETKB; delete process.env.NETKB_MATCH;
|
||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nksem-'));
|
||||
const netkb = require(path.join(ROOT, 'netkb.js'));
|
||||
netkb._set({ version: 'v', sites: { home: { name: 'Home', url: 'https://home.example' }, other: { name: 'Other', url: 'https://other.example' } },
|
||||
entries: [{ site: 'other', id: 'c-split', title: 'Other split', questions: [], answer: 'Other split answer.', tags: [] }] });
|
||||
const own = [{ id: 'c-split', title: 'Split', answer: 'Home split.' }, { id: 'c-packages', title: 'Packages', answer: 'Home prices.' }, { id: 'c-support', title: 'Support', answer: 'Ask support.', handoff: true }, { id: 'kb-t1', title: 'From a ticket', answer: 'Ticket answer.', source: 'ticket' }];
|
||||
const H = (site, id, score) => ({ site, id, title: id, answer: '', score, boosted: score + (site === 'home' ? 0.08 : 0), home: site === 'home' });
|
||||
const set = (hits, margin) => { script = () => ({ hits, margin: margin == null ? 0.1 : margin, confidence: hits.length ? hits[0].score : 0 }); };
|
||||
|
||||
// a sure match answers with this site's entry, even over a pattern hit that points elsewhere
|
||||
set([H('home', 'c-split', 0.93), H('home', 'c-packages', 0.7)]);
|
||||
let r = await netkb.route('how much do I earn', { fast: own[1], own });
|
||||
ok(r && r.via === 'answer' && r.hit.id === 'c-split', 'sure match answers (' + JSON.stringify(r && [r.via, r.hit && r.hit.id]) + ')');
|
||||
ok(last && last.path === '/v1/kb/match' && last.site === 'home' && last.body.k === 8, 'signed match call as this site');
|
||||
// the pattern hit kept when the match agrees
|
||||
set([H('home', 'c-split', 0.78), H('home', 'c-packages', 0.72)], 0.01);
|
||||
r = await netkb.route('what does it cost', { fast: own[1], own });
|
||||
ok(r && r.via === 'agree' && r.hit.id === 'c-packages', 'pattern kept when the match agrees (' + (r && r.via) + ')');
|
||||
// the pattern hit kept when the match has no idea
|
||||
set([H('home', 'c-split', 0.55)]);
|
||||
r = await netkb.route('zzq', { fast: own[1], own });
|
||||
ok(r && r.via === 'regex' && r.hit.id === 'c-packages', 'pattern kept when the match has no idea');
|
||||
// overruled when the match points elsewhere with some confidence
|
||||
set([H('home', 'c-split', 0.8), H('home', 'kb-t1', 0.75)], 0.05);
|
||||
r = await netkb.route('what is my cut when my friends buy', { fast: own[1], own });
|
||||
ok(r && r.via === 'veto' && r.hit === null && r.hits[0].entry.id === 'c-split', 'pattern overruled, the match feeds the prompt (' + (r && r.via) + ')');
|
||||
// home first: another site's entry stays behind unless clearly closer
|
||||
set([H('other', 'c-split', 0.82), H('home', 'c-split', 0.79)], 0.02);
|
||||
r = await netkb.route('my cut', { own });
|
||||
ok(r && r.via === 'context' && r.hits[0].entry.id === 'c-split' && !r.hits[0].entry.site, 'home entry first when no site is named');
|
||||
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.70)], 0.2);
|
||||
r = await netkb.route('other thing', { own });
|
||||
ok(r && !r.hits[0].entry.site && r.hits.some(h => h.entry.site === 'other'), 'another site rides behind this site entry when clearly closer');
|
||||
set([H('other', 'c-split', 0.95), H('home', 'c-packages', 0.55)], 0.2);
|
||||
r = await netkb.route('other thing', { own });
|
||||
ok(r && r.hits[0].entry.site === 'other', 'another site leads when this site has nothing close');
|
||||
// a named site asked about "here" stays home (no prefer sent)
|
||||
set([H('home', 'c-split', 0.9)]);
|
||||
await netkb.route('I am on Other, will my team carry over here?', { own, prefer: ['other'] });
|
||||
ok(!last.body.prefer, 'named site + "here": no prefer');
|
||||
await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||
ok(Array.isArray(last.body.prefer) && last.body.prefer[0] === 'other', 'named site: prefer sent');
|
||||
// remote never answers outright
|
||||
set([H('other', 'c-split', 0.99)], 0.3);
|
||||
r = await netkb.route('How much is the split on Other?', { own, prefer: ['other'] });
|
||||
ok(r && r.hit === null && r.hits[0].entry.site === 'other', 'another site\'s entry rides as context, never the instant answer');
|
||||
|
||||
// suggestions: KB entries only, no contact-support entry, ticket-derived entries labelled
|
||||
set([H('home', 'kb-t1', 0.82), H('home', 'c-support', 0.8), H('home', 'c-split', 0.79), H('home', 'c-packages', 0.5)]);
|
||||
let s = await netkb.suggest('my payout never arrived after a purchase', { own });
|
||||
ok(s.via === 'semantic' && s.items.map(i => i.id).join() === 'kb-t1,c-split', 'suggest: closest answers, no support entry, no weak ones (' + s.items.map(i => i.id) + ')');
|
||||
ok(s.items[0].fromTicket === true && s.items[1].fromTicket === false, 'suggest: past-ticket entries labelled');
|
||||
s = await netkb.suggest('hi', { own }); ok(s.items.length === 0 && s.via === 'short', 'suggest: too short asks nothing');
|
||||
|
||||
// fail soft: slow hub -> null inside the timeout, then skipped for a while; down hub -> null; suggest falls back to BM25
|
||||
netkb._matchReset(); delay = 2000;
|
||||
let t0 = Date.now(); r = await netkb.route('anything', { own }); const took = Date.now() - t0;
|
||||
ok(r === null && took < 1500, 'slow hub: null within the timeout (' + took + ' ms)');
|
||||
delay = 0; t0 = Date.now(); r = await netkb.route('anything', { own });
|
||||
ok(r === null && Date.now() - t0 < 50, 'after a failure the hub is skipped for a while (no wait)');
|
||||
s = await netkb.suggest('my payout never arrived after a purchase', { own, fallback: async () => [{ entry: own[0] }, { entry: own[2] }] });
|
||||
ok(s.via === 'bm25' && s.items.map(i => i.id).join() === 'c-split', 'suggest falls back to BM25 when the hub is skipped');
|
||||
netkb._matchReset(); status = 503;
|
||||
r = await netkb.route('anything', { own }); ok(r === null, 'hub 503: null');
|
||||
netkb._matchReset(); status = 200;
|
||||
process.env.NETKB_MATCH = '0'; r = await netkb.route('anything', { own }); ok(r === null, 'NETKB_MATCH=0: off'); delete process.env.NETKB_MATCH;
|
||||
const v = netkb.view(); ok(v.matchErrors >= 2 && v.semAnswer >= 1 && typeof v.sem.answer === 'number', 'view carries the semantic counters');
|
||||
|
||||
hub.close();
|
||||
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed' + (skip ? ', ' + skip + ' sibling files not here (skipped)' : ''));
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -69,7 +69,7 @@ elif [ "$MODE" = "sso" ]; then
|
||||
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||
node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub)
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; LOCAL=http://127.0.0.1:8796 node qa/support-suggest.mjs || status=1; }; stop_local 8796
|
||||
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
|
||||
@@ -104,6 +104,7 @@ elif [ "$MODE" = "kb" ]; then
|
||||
node qa/kb-retrieval.cjs || status=1
|
||||
node qa/kb-chat.mjs || status=1
|
||||
node qa/netkb-merge.test.cjs || status=1 # the shared network knowledge base: home first, a named site first, labels, fast-path skip (2026-11-15)
|
||||
node qa/netkb-semantic.test.mjs || status=1 # semantic matching via the hub (2026-11-16): route/suggest decisions, fail soft, shared-file parity
|
||||
elif [ "$MODE" = "door" ]; then
|
||||
node qa/door.mjs || status=1
|
||||
elif [ "$MODE" = "warpwares" ]; then
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Help desk suggestions (2026-11-16): POST /api/my/support/suggest on a LOCAL copy (bash qa/run.sh member starts it; no hub there,
|
||||
// so the answers come from the BM25 fallback, the path members get when the hub or the model is down). Checks: signed out is refused,
|
||||
// a typed problem gets the matching help answer, short text asks nothing, the contact-support entry is never offered, and a ticket
|
||||
// still sends right after (a suggestion never blocks Send). LinkSpin ships the same file (SUGGEST_SEND=0 there: its desk is IAP's).
|
||||
const B = process.env.LOCAL || 'http://127.0.0.1:8796';
|
||||
let pass = 0, fail = 0; const ok = (c, m, x) => { if (c) pass++; else { fail++; console.log('[bug] support-suggest ' + m + (x ? ' :: ' + x : '')); } };
|
||||
const email = 'sg' + Date.now() + '@example.com'; const ip = '198.51.100.' + (20 + Math.floor(Math.random() * 200));
|
||||
const H = { 'Content-Type': 'application/json', 'X-Forwarded-For': ip, 'User-Agent': 'Mozilla/5.0 SupportSuggestQA' };
|
||||
let cookie = '';
|
||||
async function post(p, b) {
|
||||
const r = await fetch(B + p, { method: 'POST', headers: Object.assign({}, H, cookie ? { Cookie: cookie } : {}), body: JSON.stringify(b) });
|
||||
const sc = typeof r.headers.getSetCookie === 'function' ? r.headers.getSetCookie() : [];
|
||||
if (sc.length) cookie = sc.map(c => c.split(';')[0]).join('; ');
|
||||
return { status: r.status, j: await r.json().catch(() => ({})) };
|
||||
}
|
||||
try {
|
||||
ok((await post('/api/my/support/suggest', { subject: 'my payout', body: 'never arrived' })).status === 401, 'signed out is refused');
|
||||
const st = await post('/api/auth/email/start', { email, fts: Date.now() - 8000, fage: 8000 });
|
||||
if (st.j.devCode) await post('/api/auth/email/verify', { email, code: st.j.devCode });
|
||||
ok(!!cookie, 'signed in for the test');
|
||||
let r = await post('/api/my/support/suggest', { subject: 'Coinbase', body: 'Can I hook up my Coinbase account to pay for a package?' });
|
||||
ok(r.status === 200 && Array.isArray(r.j.items) && r.j.items.length > 0, 'a typed problem gets suggestions', JSON.stringify(r.j).slice(0, 200));
|
||||
ok(r.j.items && r.j.items.some(i => /coinbase/i.test(i.title + ' ' + i.answer)), 'the matching help answer is offered', (r.j.items || []).map(i => i.id).join());
|
||||
ok(['semantic', 'bm25'].includes(r.j.via), 'answered by the hub or the BM25 fallback (' + r.j.via + ')');
|
||||
ok(r.j.items.every(i => !/(^|[-:])support$/.test(i.id) && i.title && i.answer), 'no contact-support entry, every item has a title and an answer');
|
||||
r = await post('/api/my/support/suggest', { subject: 'hi', body: '' });
|
||||
ok(r.status === 200 && r.j.items.length === 0, 'short text asks nothing');
|
||||
r = await post('/api/my/support/suggest', { subject: 'I want to talk to a real person', body: 'please contact me, I need support from a human' });
|
||||
ok(r.status === 200 && r.j.items.every(i => !/(^|[-:])support$/.test(i.id)), 'asking for a person never suggests the contact-support entry');
|
||||
if (process.env.SUGGEST_SEND !== '0') {
|
||||
const t = await post('/api/my/support', { category: 'Other', subject: 'Coinbase question (QA)', body: 'Can I hook up my Coinbase account to pay for a package? (support-suggest QA)' });
|
||||
ok(t.status === 200 && /^IAP-\d+$/.test(String(t.j.ref || '')), 'the ticket still sends after suggestions', JSON.stringify(t.j).slice(0, 160));
|
||||
}
|
||||
} catch (e) { fail++; console.log('[bug] support-suggest crashed :: ' + e.message); }
|
||||
console.log('support-suggest: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -31,6 +31,7 @@ const drip = require('./drip');
|
||||
const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set)
|
||||
let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ }
|
||||
const chatbot = require('./chatbot');
|
||||
const netkb = require('./netkb'); // the shared network KB on the hub; suggest() for the Help pane (2026-11-16)
|
||||
const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20)
|
||||
const fraud = require('./fraud');
|
||||
const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats
|
||||
@@ -5048,6 +5049,17 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments });
|
||||
return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref });
|
||||
}
|
||||
// help desk suggestions (2026-11-16): while a signed-in member types a new ticket, the closest help answers (the hub's semantic
|
||||
// match over the network KB, BM25 here when the hub is slow or down). KB entries only, never another member's ticket. Never blocks sending.
|
||||
if (p === '/api/my/support/suggest' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
const b = await readBody(req);
|
||||
if (supportFlood('sg:' + String(s.email).toLowerCase(), 240, 3600000)) return json(res, 200, { items: [], via: 'limited' });
|
||||
const text = (String(b.subject || '').slice(0, 200) + '. ' + String(b.body || '').slice(0, 800)).trim();
|
||||
try { return json(res, 200, await netkb.suggest(text, { own: await kb.own(), fallback: q => kb.context(q, 4) })); }
|
||||
catch (e) { console.error('support suggest', e.message); return json(res, 200, { items: [], via: 'error' }); }
|
||||
}
|
||||
m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p);
|
||||
if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) {
|
||||
const s = await auth.fromRequest(req);
|
||||
|
||||
Reference in New Issue
Block a user