Files
5xyourteam/qa/netkb-semantic.test.mjs
T
martbost e1915da9ba Smarter chatbot matching by meaning (Marty 2026-11-16): the hub's semantic match (free core2 embeddings)
chatcore.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).
netkb.js also has suggest() for the support desk (used by InstantAdPay and LinkSpin). Same chatcore.js in the six rebuilt
sites, same netkb.js in all eight. Test: node qa/netkb-semantic.test.mjs (decisions, fail soft, shared-file parity).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:48:54 -06:00

116 lines
9.3 KiB
JavaScript

// 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);