Merge LinkSpin knowledge-base chatbot (Banner Spin answer moved into a KB entry)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-20 05:52:02 -05:00
11 changed files with 753 additions and 46 deletions
+131
View File
@@ -0,0 +1,131 @@
// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20).
// node qa/kb-chat.mjs (or: bash qa/run.sh kb) LinkSpin copy of InstantAdPay's qa/kb-chat.mjs
// 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(), 'ls-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 in your Control Room.";
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 >= 40, '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(/open \S+ in SafePal's browser/.test(sys) && !/instantadpay\.com in SafePal/.test(sys), 'Coinbase entry is the LinkSpin wording');
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 >= 40, '/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);
+48
View File
@@ -0,0 +1,48 @@
// 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'],
['I already have an InstantAdPay account, will my upline carry over here?', 'f-team-here'],
['How many extra POL should I keep for gas fees?', 'f-how-much-pol'],
['MoonPay declined my bank card', 'f-moonpay-declined'],
['When does the daily set reset each day?', 'f-claim-streak'],
['How many videos can I watch per day?', 'f-visits-videos'],
['How do I rotate several offers behind one short link?', 'c-spin-links'],
['How do I put an ad slot on my own website?', 'c-zones'],
['Can I track conversions from PropellerAds with a postback?', 'c-sources'],
['Someone on Telegram asked for my recovery phrase', 'f-recovery-phrase'],
['Which network do I choose when withdrawing POL from Binance?', 'f-exchange-withdraw']
];
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);
+4
View File
@@ -4,6 +4,7 @@
# bash qa/run.sh member # local copy: member + admin walk
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
# bash qa/run.sh all # public + member + earn
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u
@@ -29,6 +30,9 @@ if [ "$MODE" = "public" ]; then
node qa/walk.mjs public || status=1
elif [ "$MODE" = "member" ]; then
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
elif [ "$MODE" = "kb" ]; then
node qa/kb-retrieval.cjs || status=1
node qa/kb-chat.mjs || status=1
elif [ "$MODE" = "earn" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
else
+1 -1
View File
@@ -121,7 +121,7 @@ if (MODE === 'member' || MODE === 'all') {
// admin
await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' });
await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200);
for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'settings']) {
for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'kb', 'releases', 'pnl', 'settings']) {
const label = L + 'admin#' + pn;
await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200);
const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn);