Shared network knowledge (Marty 2026-11-15): the chatbot publishes its KB to the network hub and reads the other network sites' entries (netkb.js, the same file in every network site), home entries boosted, a named site's entries first and labelled with its LinkSpin tracked link, a question naming another site skips the instant answers (a hand-off still wins). Wallet answers follow Marty's rule (SafePal or any other crypto wallet, never recommend MetaMask), since they are now shared network-wide. KNOWLEDGE_DATE 2026-11-15. qa kb: netkb-merge 67 pass, kb-chat pass, kb-retrieval 2 misses that also fail on a clean tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 13:31:35 -06:00
parent f4789156b8
commit fbf7d87030
6 changed files with 221 additions and 20 deletions
+52 -11
View File
@@ -9,6 +9,12 @@
// path serves the new text.
// source canned | faq | ticket | admin
//
// 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 (NAMED_BOOST) and
// skips this site's instant answers (namesOther, chatbot.js). Other sites' entries never take the fast path; they 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. The same
// merge code is in InstantAdPay, LinkSpin and the rebuilt sites' kb.js.
//
// 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).
@@ -22,10 +28,11 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
const { SITE_URL } = require('./host');
let DATA_DIR = null, SEEDS = [], ready = null;
let cache = null, cacheAt = 0, index = null;
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)
@@ -82,10 +89,38 @@ function buildIndex(entries) {
}
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.
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;
@@ -97,6 +132,8 @@ function rank(idx, query, k) {
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);
@@ -153,9 +190,10 @@ function init(opts) {
}
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
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(); index = buildIndex(cache); rx.clear();
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();
@@ -173,13 +211,16 @@ async function fastPath(msg) {
}
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)); }
// this site's own entries, for netkb.publish
async function own() { await load(); return cache.slice(); }
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
const HELP = 'Help (' + SITE_URL + '/help, or ' + SITE_URL + '/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');
+ 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
@@ -200,7 +241,7 @@ function validate(o, cur) {
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 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);
@@ -211,19 +252,19 @@ async function create(o) {
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);
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);
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);
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
@@ -238,8 +279,8 @@ async function stamp() {
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) })) };
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, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
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 } };