Files
instantadpay/qa/kb-chat.mjs
T
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

131 lines
9.8 KiB
JavaScript

// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20).
// node qa/kb-chat.mjs (or: bash qa/run.sh kb)
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB) and a mock OpenRouter that
// records every request and answers from the "Knowledge base" block it was given. Nothing touches production:
// OPENROUTER_URL points at the mock and the key is a throwaway string.
// Covers: the Coinbase question answered from the KB through the AI path, the CANNED fast path served from the
// KB (no AI call), an off-topic question told to say "I'm not sure, ask support", admin create / edit / test /
// delete, an admin edit to a canned entry changing the instant answer, and /api/chat/kb-stamp. Exit 1 on failure.
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.KB_PORT || 8799), MOCK = PORT + 100;
const B = 'http://127.0.0.1:' + PORT;
const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kb-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
// -- the mock OpenRouter: answers with the first KB answer it was handed, or the not-sure line
const calls = [];
const mock = http.createServer((req, res) => {
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
let body = {}; try { body = JSON.parse(raw); } catch (e) {}
calls.push({ url: req.url, auth: req.headers.authorization, body });
const sys = ((body.messages || [])[0] || {}).content || '';
const m = /\nAnswer: ([^\n]+)/.exec(sys.slice(sys.indexOf('KNOWLEDGE BASE')));
const content = m ? m[1] : "I'm not sure, ask support: open Help at https://instantadpay.com/my#help.";
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end('\n\n' + JSON.stringify({ choices: [{ message: { content } }] })); // keepalive padding first, like the real thing
});
});
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
let srv = null, srvLog = '';
async function boot() {
srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN,
OPENROUTER_API_KEY: 'qa-throwaway', OPENROUTER_URL: 'http://127.0.0.1:' + MOCK + '/api/v1/chat/completions', DATABASE_URL: '' }) });
srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
}
async function halt() { if (!srv) return; const s = srv; srv = null; s.kill(); await new Promise(r => { s.once('exit', r); setTimeout(r, 3000); }); await sleep(300); }
const cleanup = async () => { try { await halt(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
try {
await boot();
const api = async (p, data, method, hdr) => { const r = await fetch(B + p, data !== undefined || method ? { method: method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: data === undefined ? undefined : JSON.stringify(data) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
const chat = message => api('/api/chat', { message }, 'POST'); // six questions in all, under the 10-a-minute chat limit
// 1. seeds landed in DATA_DIR/kb.json
await sleep(300);
const list0 = await api('/api/admin/kb', undefined, undefined, adminH);
const ids = (list0.j && list0.j.entries || []).map(e => e.id);
ok(ids.includes('f-coinbase') && ids.includes('c-withdraw') && ids.length >= 55, 'KB seeded from CANNED + FAQ + the Coinbase ticket', ids.length + ' entries');
ok(fs.existsSync(path.join(DATA, 'kb.json')), 'JSON store at DATA_DIR/kb.json');
// 2. the Coinbase question goes to the AI with the Coinbase entry in its knowledge base
let n = calls.length;
const cb = await chat('Can I use my regular Coinbase account?');
const sys = calls[n] && calls[n].body.messages[0].content || '';
ok(cb.status === 200 && calls.length === n + 1, 'Coinbase question goes to the AI path (one call)', 'status ' + cb.status);
ok(sys.includes('KNOWLEDGE BASE') && sys.includes('Coinbase is an exchange') && sys.indexOf('[1] Can I use my regular Coinbase account?') > 0, 'system prompt carries the Coinbase entry first');
ok(sys.includes('NEVER promise or estimate income') && sys.includes('No em dashes'), 'compliance rules still in the prompt');
ok(calls[n] && calls[n].body.reasoning && calls[n].body.reasoning.enabled === false, 'reasoning stays off');
ok(cb.j && /Coinbase is an exchange/.test(cb.j.reply) && (cb.j.kb || [])[0] === 'f-coinbase', 'reply drawn from the KB entry', JSON.stringify(cb.j).slice(0, 140));
// 3. the CANNED fast path, now served from the KB: no AI call
n = calls.length;
const wd = await chat('how do I withdraw my money');
ok(wd.j && wd.j.canned && wd.j.kb === 'c-withdraw' && /no withdrawals here/.test(wd.j.reply) && calls.length === n, 'canned answer served from the KB, no AI call', JSON.stringify(wd.j).slice(0, 100));
const sup = await chat('I want to talk to a real person');
ok(sup.j && sup.j.handoff && sup.j.kb === 'c-support', 'support hand-off flag kept on the instant answer');
// 4. nothing fits: the prompt says so and the reply hands off
n = calls.length;
const off = await chat('What is the capital of Mongolia?');
const sys2 = calls[n] && calls[n].body.messages[0].content || '';
ok(/no entry matches this question/.test(sys2) && /I'm not sure, ask support/.test(sys2), 'off-topic: prompt tells the AI to say it is not sure');
ok(off.j && off.j.handoff, 'off-topic reply offers "Send this to support"');
// 5. admin: create, find, test, edit, delete
const cr = await api('/api/admin/kb', { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?', 'Do you take PayPal'], answer: 'No. Packages are paid in POL on Polygon only — PayPal is not accepted.', tags: 'paypal, payment' }, 'POST', adminH);
ok(cr.j && cr.j.ok && cr.j.entry.answer.indexOf('—') < 0, 'admin creates an entry (em dash cleaned)', cr.j && cr.j.entry && cr.j.entry.answer);
const kid = cr.j && cr.j.entry && cr.j.entry.id;
const noAuth = await api('/api/admin/kb', { title: 'x', answer: 'y' }, 'POST');
ok(noAuth.status === 401, 'KB admin routes need the admin');
const t = await api('/api/admin/kb/test', { question: 'do you accept paypal' }, 'POST', adminH);
ok(t.j && t.j.ranked[0] && t.j.ranked[0].id === kid && t.j.ranked[0].used, 'Try a question ranks the new entry first');
n = calls.length;
await chat('can I pay using paypal?');
ok(calls[n] && calls[n].body.messages[0].content.includes('PayPal is not accepted'), 'new entry reaches the AI prompt right away');
const ed = await api('/api/admin/kb/' + kid, { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?'], answer: 'No, PayPal is not accepted. Packages are paid in POL on Polygon.', tags: ['paypal'] }, 'PUT', adminH);
ok(ed.j && ed.j.ok && ed.j.entry.answer.startsWith('No, PayPal'), 'admin edits the entry');
const srch = await api('/api/admin/kb?q=paypal', undefined, undefined, adminH);
ok(srch.j && srch.j.entries[0] && srch.j.entries[0].id === kid, 'admin search finds it');
const bad = await api('/api/admin/kb', { title: 'x', answer: 'y', pattern: '(' }, 'POST', adminH);
ok(bad.status === 400, 'a broken instant-answer pattern is refused');
const del = await api('/api/admin/kb/' + kid, undefined, 'DELETE', adminH);
const gone = await api('/api/admin/kb/' + kid, undefined, undefined, adminH);
ok(del.j && del.j.ok && gone.status === 404, 'admin deletes it');
// 6. editing a canned entry changes the instant answer (one source)
const cw = (await api('/api/admin/kb/c-withdraw', undefined, undefined, adminH)).j.entry;
await api('/api/admin/kb/c-withdraw', Object.assign({}, cw, { answer: cw.answer + ' (edited in QA)' }), 'PUT', adminH);
const wd2 = await chat('how do I withdraw');
ok(wd2.j && /\(edited in QA\)$/.test(wd2.j.reply), 'admin edit to a canned entry is what the fast path serves');
// 7. the sync guard's stamp: today (Central), because a person just edited entries
const st = await api('/api/chat/kb-stamp');
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
ok(st.j && st.j.updated === today && st.j.count >= 55, '/api/chat/kb-stamp reports the newest human edit', JSON.stringify(st.j));
// 8. a restart (the seed sync runs again) keeps admin work and does not bring a deleted seed back
await api('/api/admin/kb/f-refunds', undefined, 'DELETE', adminH);
await halt(); await boot();
const after = await api('/api/admin/kb', undefined, undefined, adminH);
const aIds = (after.j && after.j.entries || []).map(e => e.id);
const cw2 = (after.j && after.j.entries || []).find(e => e.id === 'c-withdraw');
ok(!aIds.includes('f-refunds') && aIds.includes('f-coinbase'), 'restart: a deleted seed stays deleted');
ok(cw2 && /\(edited in QA\)$/.test(cw2.answer) && cw2.edited, 'restart: an admin edit to a seed is not overwritten by the code');
} catch (e) { ok(false, 'run', e.message); }
await cleanup();
console.log(fails ? fails + ' failure(s)' : 'all KB chat checks passed');
process.exit(fails ? 1 : 0);