Site assistant (Marty 2026-11-15): chat widget in the Stack POL look on every page, CANNED + FACTS from this repo (the on-page FAQ, programs.js, the 5-minute indexer, opt-in member pages, holds nothing, no income promise), retrieval over the shared network knowledge base on the hub (netkb.js as hub site stackpol; another site named = its answer, with its tracked LinkSpin link), reasoning off, account problems hand off to network support. Static server now serves .js/.css; Dockerfile copies the chat modules. chatbot.test 125 pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 13:11:04 -06:00
parent 3a6ac0a81e
commit 7446df2f4f
12 changed files with 916 additions and 3 deletions
+289
View File
@@ -0,0 +1,289 @@
// 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.
//
// Store: DATA_DIR/kb.json (written to a temp file and renamed), which docstore.js keeps in MySQL when DOCSTORE_URL is set
// (Marty's database rule). Ported from LinkSpin's kb.js (2026-11-15); keep the scoring and seed rules in step.
//
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's
// own entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries instead
// (NAMED_BOOST). Other sites' entries never take the instant-answer fast path: they only ride along as context, labelled
// with the site and the link to send people to. This site's own entries are published to the hub (netkb.publish).
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
let DATA_DIR = null, SEEDS = [], ready = null, SITE_URL = '', HELP_TEXT = '', MEMORY = false;
let cache = null, cacheAt = 0, index = null, netVer = '';
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: 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 };
}
const HOME_BOOST = 2, NAMED_BOOST = 3;
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
function namedSites(query, idx) {
const q = norm(query); const out = new Set();
for (const s of (idx && idx.sites) || []) {
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
}
return out;
}
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside and the
// answer comes from retrieval over the whole network (a "how much" about another site must not get this site's price).
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
function namesOther(query, self) {
const q = norm(query); const out = [];
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
for (const id of ids) {
if (id === self) continue;
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
}
return out;
}
function rank(idx, query, k) {
if (!idx || !idx.n) return [];
const qt = [...new Set(terms(query))];
if (!qt.length) return [];
const named = namedSites(query, idx);
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 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
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 mem = { entries: [] }; // a site with no data volume (Stack POL): seeds in memory only
const J = {
file: () => path.join(DATA_DIR, 'kb.json'),
async ensure() {},
async all() { if (MEMORY) return mem.entries.slice(); 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);
if (MEMORY) { mem.entries = all; return; }
const tmp = J.file() + '.tmp';
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
fs.renameSync(tmp, J.file());
}
};
const store = () => 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');
}
// opts: { dataDir (null = memory only), seeds, siteUrl, helpText (where a member gets a person) }
function init(opts) {
DATA_DIR = opts.dataDir || null; MEMORY = !DATA_DIR; SEEDS = opts.seeds || []; cache = null; index = null; mem.entries = [];
SITE_URL = String(opts.siteUrl || '').replace(/\/+$/, ''); HELP_TEXT = opts.helpText || 'network support at https://instantadpay.com/support';
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
return ready;
}
// this site's own entries, for netkb.publish
async function own() { await load(); return cache.slice(); }
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL && (!netkb || netkb.version() === netVer)) return cache; // a new network set rebuilds at once
const all = await store().all();
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear(); netVer = netkb ? netkb.version() : '';
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
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 || 6)); }
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP_TEXT + '.';
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 + label(h.entry) + '\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).filter(h => !h.entry.site).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); if (netkb) netkb.publishSoon();
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); if (netkb) netkb.publishSoon();
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); if (netkb) netkb.publishSoon();
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, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
}
module.exports = { init, load, own, namesOther, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };