// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20). // The chatbot answers from maintained entries, and good support replies become entries. // // An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef, // updated, created, edited, deleted, seedHash } // pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path: // the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list // in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast // path serves the new text. // source canned | faq | ticket | admin // // Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with // word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls. // The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js). // // Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin // pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays // deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it. // // Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else // DATA_DIR/kb.json (local dev and the QA harness). const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const db = require('./db'); let DATA_DIR = null, SEEDS = [], ready = null; let cache = null, cacheAt = 0, index = null; const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then // ---------------------------------------------------------------- text + scoring (pure, unit-tested) const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its ' + 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why ' + 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here ' + 'should shall may might must anyone someone something thing things want wanted like know tell').split(' ')); const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw', signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log', wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price', ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' }; function stem(w) { if (SYN[w]) return SYN[w]; if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4); if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3); if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y'; if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2); if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1); return w; } function words(text) { return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ') .filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem); } // unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words function terms(text) { const w = words(text), out = w.slice(); for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]); return out; } const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 }; const K1 = 1.2, B = 0.75; function fieldText(e, f) { if (f === 'questions') return (e.questions || []).join(' . '); if (f === 'tags') return (e.tags || []).join(' . '); return e[f] || ''; } function buildIndex(entries) { const docs = entries.map(e => { const d = { e, f: {} }; for (const f of Object.keys(FIELDS)) { const t = terms(fieldText(e, f)), tf = new Map(); for (const x of t) tf.set(x, (tf.get(x) || 0) + 1); d.f[f] = { tf, len: t.length }; } return d; }); const df = new Map(), avg = {}; for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1; for (const d of docs) { const seen = new Set(); for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t); for (const t of seen) df.set(t, (df.get(t) || 0) + 1); } return { docs, df, avg, n: docs.length }; } function rank(idx, query, k) { if (!idx || !idx.n) return []; const qt = [...new Set(terms(query))]; if (!qt.length) return []; const out = []; for (const d of idx.docs) { let s = 0; for (const t of qt) { const n = idx.df.get(t); if (!n) continue; const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1); for (const f of Object.keys(FIELDS)) { const tf = d.f[f].tf.get(t); if (!tf) continue; s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f])); } } if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 }); } out.sort((a, b) => b.score - a.score); return out.slice(0, k || 5); } // keep hits that are close to the best one, and only when the best is a real match const MIN_SCORE = 3; function relevant(hits) { if (!hits.length || hits[0].score < MIN_SCORE) return []; const floor = Math.max(MIN_SCORE, hits[0].score * 0.3); return hits.filter(h => h.score >= floor); } // ---------------------------------------------------------------- store const row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '', handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '', edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) }); function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } } const D = { async ensure() { await db.q(`CREATE TABLE IF NOT EXISTS kb_entries ( id VARCHAR(64) PRIMARY KEY, title VARCHAR(200) NOT NULL, questions TEXT NULL, answer TEXT NOT NULL, tags VARCHAR(800) NULL, pattern TEXT NULL, handoff TINYINT NOT NULL DEFAULT 0, ord INT NULL, source VARCHAR(16) NOT NULL DEFAULT 'admin', ticket_ref VARCHAR(20) NULL, seed_hash CHAR(40) NULL, edited TINYINT NOT NULL DEFAULT 0, deleted TINYINT NOT NULL DEFAULT 0, created BIGINT NOT NULL, updated BIGINT NOT NULL, INDEX (deleted, updated) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); }, async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); }, async put(e) { await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags), pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash), edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`, [e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order, e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]); } }; const J = { file: () => path.join(DATA_DIR, 'kb.json'), async ensure() {}, async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } }, async put(e) { const all = await J.all(), i = all.findIndex(x => x.id === e.id); if (i >= 0) all[i] = e; else all.push(e); const tmp = J.file() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify({ entries: all })); fs.renameSync(tmp, J.file()); } }; const store = () => db.enabled() ? D : J; // ---------------------------------------------------------------- seeds const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source']; const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex'); function seedEntry(s) { return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff, order: s.order == null ? null : s.order, source: s.source || 'faq' }; } async function syncSeeds() { const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now(); const seedIds = new Set(SEEDS.map(s => s.id)); let added = 0, refreshed = 0, retired = 0; for (const s of SEEDS) { const h = seedHash(seedEntry(s)), cur = byId.get(s.id); if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; } else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; } } // a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing) if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; } if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired'); } function init(opts) { DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null; ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); }); return ready; } async function load(force) { if (ready) await ready; if (!force && cache && Date.now() - cacheAt < TTL) return cache; const all = await store().all(); cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear(); return cache; } const rx = new Map(); function compiled(src) { if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); } return rx.get(src); } const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated; // ---------------------------------------------------------------- the chatbot side async function fastPath(msg) { const list = (await load()).filter(e => e.pattern).sort(byOrder); for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; } return null; } async function search(query, k) { await load(); return rank(index, query, k || 5); } async function context(query, k) { return relevant(await search(query, k || 5)); } const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)'; function promptBlock(hits) { const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.'; if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.'; return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. ' + 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n' + hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n'); } // ---------------------------------------------------------------- the admin side const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text function validate(o, cur) { o = o || {}; const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15); const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15); const answer = clean(o.answer).slice(0, 4000); const title = (clean(o.title) || questions[0] || '').slice(0, 200); const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000); if (!title) return { error: 'Give the entry a title or at least one question.' }; if (!answer) return { error: 'The answer is empty.' }; if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } } const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order); return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null }; } async function list(q) { const all = (await load(true)).slice(); if (!q) return all.sort((a, b) => b.updated - a.updated); const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry)); const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id)); const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc))); return ranked.concat(plain); } async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; } async function create(o) { const v = validate(o); if (v.error) return v; const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex'); const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin'; const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now }); await store().put(e); await load(true); return { ok: true, entry: e }; } async function update(id, o) { const cur = await get(id); if (!cur) return { error: 'Entry not found.' }; const v = validate(o, cur); if (v.error) return v; const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() }); await store().put(e); await load(true); return { ok: true, entry: e }; } async function remove(id) { const cur = await get(id); if (!cur) return { error: 'Entry not found.' }; await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); return { ok: true }; } // newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync // guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose // KNOWLEDGE_DATE already speaks for the code. const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); async function stamp() { const all = await load(); const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0); return { updated: max ? ctDay(max) : '', count: all.length }; } async function test(question) { const fast = await fastPath(String(question || '')); const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id)); return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) }; } module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test, _pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };