Files
martbost 7e113f055d 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>
2026-11-16 05:46:31 -06:00

205 lines
14 KiB
JavaScript

// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
// 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';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const REFRESH_MS = 10 * 60 * 1000;
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const secret = () => String(process.env.HUB_SECRET || '').trim();
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, 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(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 };
}
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
async function publish() {
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
const body = { name: O.name, url: O.url, entries };
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
if (h === publishedHash) return { same: true };
try {
const r = await call('PUT', '/v1/kb', body);
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
return r.body;
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
}
// an admin edit: publish a few seconds later (several quick edits go as one)
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
function readCache() {
const f = cacheFile(); if (!f) return;
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
}
function writeCache() {
const f = cacheFile(); if (!f) return;
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
}
async function refresh() {
if (!enabled()) return { skipped: true };
try {
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
stats.lastReadAt = Date.now();
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
writeCache();
return { version: merged.version, count: merged.entries.length };
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
}
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
function remote() {
const me = siteName(); const out = [];
for (const e of merged.entries || []) {
if (!e || e.site === me) continue;
const s = (merged.sites || {})[e.site] || {};
const url = s.url || e.link || '';
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
}
return out;
}
// the network's sites as the hub knows them (name, link), this one left out
function sites() {
const me = siteName();
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();
if (!enabled()) return;
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
if (first.unref) first.unref();
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, semantic: matchOn(), sem: SEM }, stats, mstats); }
function _set(m) { merged = m; } // tests
const version = () => merged.version || '';
function _matchReset() { matchDownUntil = 0; } // tests
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, match, route, suggest, SEM, _set, _matchReset };