Files
martbost 1e040f21ff Chat knowledge base: the assistant answers from maintained entries, and support replies become entries
- kb.js: entries { id, title, questions, answer, tags, pattern, handoff, order, source, updated } in MySQL table kb_entries (created on boot) or DATA_DIR/kb.json without DATABASE_URL. BM25 over title, question variants and tags (answer at a low weight) with word bigrams; the top hits (within 30% of the best, score 3+) go into the system prompt as KNOWLEDGE BASE, and when nothing fits the prompt says to answer "I'm not sure, ask support".
- One source: chatbot.js CANNED seeds the KB (ids c-*, its regex becomes the entry's instant-answer pattern, same first-match order), kb-seed.js seeds the home FAQ, Platform Facts, wallets FAQ and the Coinbase support reply (f-*). The fast path now serves the KB entry, so an admin edit changes the instant answer; the in-code CANNED only answers if the KB store fails. Unedited seeds follow code changes, edited ones are left alone, deleted seeds stay deleted.
- Admin > Knowledge base: list, search, filter by source, add, edit, delete, and Try a question (instant answer or what the AI is given). Support tickets: "Save as KB entry" under each sent reply opens a draft with the member's question and the reply (greeting and sign-off trimmed). Em dashes in admin input become commas.
- chatbot.js: OPENROUTER_URL override for tests; solo-ads answer em dash removed; KNOWLEDGE_DATE 2026-10-20.
- qa/chatbot-sync.mjs: takes the later of KNOWLEDGE_DATE and /api/chat/kb-stamp (newest KB edit by a person, Central day; seed refreshes do not count).
- QA: qa/kb-retrieval.cjs (13 sample questions rank the right entry first, off-topic returns nothing), qa/kb-chat.mjs (local copy + mock OpenRouter: Coinbase answered from the KB, fast path without an AI call, admin CRUD, restart keeps edits), bash qa/run.sh kb; walk covers admin#kb and Save as KB entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 05:37:09 -05:00

50 lines
3.3 KiB
JavaScript

// Knowledge-base retrieval unit test (kb.js): the right entry must rank first for each sample question,
// scored over the real seeds (chatbot.js CANNED + kb-seed.js). No server, no network.
// node qa/kb-retrieval.cjs
const path = require('path');
const kb = require(path.join(__dirname, '..', 'kb.js'));
const chatbot = require(path.join(__dirname, '..', 'chatbot.js'));
const { buildIndex, rank, relevant, validate } = kb._pure;
const entries = chatbot.seeds();
const idx = buildIndex(entries);
const CASES = [
['Can I hook up my Coinbase account to pay for a package?', 'f-coinbase'],
['can i just use coinbase', 'f-coinbase'],
['Is my payment refundable if I change my mind?', 'f-refunds'],
['Can I give some of my credits to a friend?', 'f-credits-transfer'],
['Why does the amount of POL keep changing when I buy?', 'f-price-feed'],
['What is the smart contract address on polygonscan?', 'f-contract'],
['My video stopped playing when I switched tabs', 'f-active-viewing'],
['How many extra POL should I keep for gas fees?', 'f-how-much-pol'],
['My bank refused my card on MoonPay', 'f-moonpay-declined'],
['Trust wallet says this will drain my wallet', 'c-trust-drain'],
['How do I adopt somebody from the holding tank?', 'c-holding-tank'],
['I keep getting signed out every few hours', 'c-session-4h'],
['Where does the 20 percent platform share go?', 'f-platform-share']
];
let bad = 0;
for (const [q, want] of CASES) {
const hits = rank(idx, q, 5), top = hits[0];
const ok = top && top.entry.id === want && relevant(hits).length > 0;
if (!ok) bad++;
console.log((ok ? 'ok ' : 'FAIL ') + q + ' -> ' + hits.slice(0, 3).map(h => h.entry.id + ' ' + h.score).join(', ') + (ok ? '' : ' (wanted ' + want + ')'));
}
// off-topic questions should bring nothing back, so the prompt says "I'm not sure, ask support"
for (const q of ['What is the weather in Paris tomorrow?', 'Recommend a good pizza recipe']) {
const r = relevant(rank(idx, q, 5));
if (r.length) bad++;
console.log((r.length ? 'FAIL ' : 'ok ') + 'off-topic: ' + q + ' -> ' + (r.map(h => h.entry.id + ' ' + h.score).join(', ') || 'nothing'));
}
// admin input hygiene: em dashes are turned into commas, a bad pattern is refused
const v = validate({ title: 'T', answer: 'One — two', questions: 'a\nb', tags: 'X, y' });
if (v.answer !== 'One, two' || v.questions.length !== 2 || v.tags[0] !== 'x') { bad++; console.log('FAIL validate', v); } else console.log('ok validate cleans em dashes, splits questions and tags');
if (!validate({ title: 'T', answer: 'a', pattern: '(' }).error) { bad++; console.log('FAIL validate accepted a broken pattern'); } else console.log('ok validate refuses a broken pattern');
// every CANNED regex still answers through the KB fast path in the same order
const ordered = entries.filter(e => e.pattern).sort((a, b) => a.order - b.order);
const first = msg => ordered.find(e => new RegExp(e.pattern, 'i').test(msg));
const canned = chatbot.CANNED.find(c => c.re.test('how do I withdraw'));
if (!first('how do I withdraw') || first('how do I withdraw').answer !== canned.a) { bad++; console.log('FAIL fast-path order'); } else console.log('ok fast path keeps CANNED order');
console.log(bad ? bad + ' failure(s)' : 'all retrieval checks passed');
process.exit(bad ? 1 : 0);