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:
+26
-7
@@ -20,15 +20,28 @@ const https = require('https');
|
||||
const http = require('http');
|
||||
const kb = require('./kb');
|
||||
const kbSeed = require('./kb-seed');
|
||||
const netkb = require('./netkb'); // the shared network knowledge base on the hub (2026-11-15): publishes this site's entries, reads the other sites'
|
||||
|
||||
let DATA_DIR = null;
|
||||
let chain = null;
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
|
||||
const KNOWLEDGE_DATE = '2026-11-13'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
const KNOWLEDGE_DATE = '2026-11-15'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
|
||||
function init(opts) {
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; const ready = kb.init({ dataDir: DATA_DIR, seeds: seeds() });
|
||||
netkb.init({ dataDir: DATA_DIR, site: process.env.HUB_SITE || 'linkspin', name: 'LinkSpin', url: SITE_URL, entries: () => kb.own(), linkFor: netLink });
|
||||
return ready; }
|
||||
// the link to another network site: its LinkSpin tracked link with ?src=linkspin (netsites.js), else its plain address
|
||||
function netLink(url) {
|
||||
try { const ns = require('./netsites'); const h = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
const m = ns.list().concat(ns.FALLBACK || []).find(x => h(x.url) === h(url)); return (m && m.id !== 'linkspin' && ns.tracked(m.id, 'linkspin')) || url; } catch (e) { return url; }
|
||||
}
|
||||
// the other network sites for the system prompt (from the hub's merged set)
|
||||
function networkBlock() {
|
||||
const l = netkb.sites(); if (!l.length) return '';
|
||||
return '\n- OTHER NETWORK SITES (one network account works across them): ' + l.map(x => x.name + ' ' + x.go).join('; ') + '. A question about one of them: answer from its KNOWLEDGE BASE entries below, say which site it is about, give its link exactly as shown, and never mix two sites\' prices, splits or rules. Wallets: say "SafePal or any other crypto wallet". Ad credits buy advertising, not income. Never mention RM Circle.';
|
||||
}
|
||||
function key() {
|
||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||
@@ -124,10 +137,10 @@ const CANNED = [
|
||||
a: 'One credit is one cent of ad delivery: banner, text and login ads shown across the LinkSpin ad viewer, every member zone and the partner network, managed from the Ads screen. Credits come two ways, bought in a package or earned free (zones, the daily ad set, videos, verified visits, daily sign-in). Earned credits spend on banner and text campaigns; a login-ad slot (1,000 purchased credits for 30 days) takes purchased credits only. Credits are advertising, not money: they never cash out and are never converted to crypto.' },
|
||||
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning'],
|
||||
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||
a: 'That red "this transaction will drain your wallet" screen is Trust Wallet\'s own safety rule, not a problem with the purchase: it blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet. SafePal, MetaMask and Phantom have no such block. Extra POL always stays yours. If the next try says WalletConnect disconnected, open the Wallet screen, disconnect, then connect again.' },
|
||||
a: 'That red "this transaction will drain your wallet" screen is Trust Wallet\'s own safety rule, not a problem with the purchase: it blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet. SafePal and most other wallets have no such block. Extra POL always stays yours. If the next try says WalletConnect disconnected, open the Wallet screen, disconnect, then connect again.' },
|
||||
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'safepal', 'metamask', 'buy pol', 'card'],
|
||||
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|card to crypto|no crypto|never (had|held|owned) crypto|metamask|safepal|phantom|coinbase wallet)/i,
|
||||
a: 'SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first under Settings, Active Networks) and any WalletConnect wallet work too. Trust Wallet works but blocks a purchase that spends most of its POL, so keep about double the package cost there. Never held crypto? Buy POL with a card on any major exchange or on-ramp (or the Buy button inside your wallet app), choose POL on the Polygon network, send it to your own wallet address, then buy the package on the Credits screen. The provider handles its own ID checks, fees and limits. Keep a little extra POL for network fees. The step-by-step guide is at ' + SITE_URL + '/wallets.' },
|
||||
a: 'Use SafePal or any other crypto wallet on Polygon (in Phantom, turn Polygon on first under Settings, Active Networks). Trust Wallet works but blocks a purchase that spends most of its POL, so keep about double the package cost there. Never held crypto? Buy POL with a card on any major exchange or on-ramp (or the Buy button inside your wallet app), choose POL on the Polygon network, send it to your own wallet address, then buy the package on the Credits screen. The provider handles its own ID checks, fees and limits. Keep a little extra POL for network fees. The step-by-step guide is at ' + SITE_URL + '/wallets.' },
|
||||
{ id: 'join', title: 'How to join and sign in', q: ['How do I join?', 'Do I need a wallet?', 'Is there a password?'], tags: ['join', 'sign up', 'sign in', 'code'],
|
||||
re: /(need (a )?wallet|crypto experience|how (do i|to) (join|sign ?up|register|sign in)|sign ?up|register|password|sign.?in code|six.?digit)/i,
|
||||
a: 'Join free with just your email at ' + SITE_URL + '/join. A six-digit code signs you in, there is no password, and no wallet is needed to use the links, pages and zones. The wallet step comes later, inside your Control Room, when you want to be paid or to buy a package.' },
|
||||
@@ -211,7 +224,7 @@ ${refuelFact()}${synFact()}- PRODUCT, all free with an email account: SPIN LINKS
|
||||
- THE SPLIT, same transaction on Polygon, fixed in the contract: 50 percent direct sponsor, 20 percent level 2, 10 percent level 3, 10 percent + 10 percent to the two admin wallets. Level 1 pays from a referral's first qualifying purchase once the sponsor's payouts are on. Level 2 opens after two of the member's people buy a qualifying ($25 or larger) package, level 3 after five. An unfilled tier passes up the line to the next qualified member, then to the platform. Nothing is held, there are no withdrawals, no pending balances. Contract ${CONTRACT} on Polygon, verified on Polygonscan; plain-language review at ${SITE_URL}/contract; live ledger at ${SITE_URL}/ledger with a verify link on every row.
|
||||
- CREDITS VS POL: every member, free ones included, earns CREDITS (zones, the daily ad set with a claim streak, watch-to-earn videos, verified visits, a daily sign-in bonus). Credits buy the member's own banner and text ads (a login-ad slot takes purchased credits only) and NEVER cash out or convert to crypto. POL only reaches a wallet through the contract split when a package sells in the member's line. Never promise or estimate income.
|
||||
- AD FORMATS members buy with credits: banner ads (standard sizes), text ads, full-screen login ads (a flat slot: 1,000 PURCHASED credits for 30 days of unlimited sign-in impressions, never charged per day; at most 6 member slots live at once (raised from 3 on 2026-10-23); PAID QUEUE (2026-10-23): when all 6 are taken a member can reserve the next slot by paying the full 1,000 purchased credits now, first paid first served, the 30 days start only when a slot frees (a slot ends or is paused) and the member gets an on-site notice and an email, the Ads screen shows the place in line and an ESTIMATED start date in Central time, edits are free while waiting, cancelling before the start refunds the full amount as purchased credits (a running slot is not refundable), and a paused slot can resume only when live plus waiting slots are under 6; house login ads only show when no member slot is running; earned credits never fund login ads); EDITING AN AD (2026-10-18): the Edit button on each ad on the Ads screen changes the click link, the banner image (upload or https link), a text ad's headline and line, and the ad name; type, size, budget, countries, schedule and audience cannot change (start a new ad); the first edit of every ad is free, each later edit costs the campaignEditFee, 100 credits by default, earned credits first, then purchased; a new link and a new banner image get the same checks as a new ad, plus solo ads to member inboxes, watch-to-earn video, verified visits. Banner and text ads also run on member zones and the partner network.
|
||||
- ACCOUNT: join at ${SITE_URL}/join with email only, a six-digit code, no password. Wallet linking happens inside the Control Room (Credits screen): one signature to link, then payouts switch on by activating (one transaction, gas only) or by buying any package. SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first) and any WalletConnect wallet work; Trust Wallet blocks a buy that spends most of its POL. No card button on the site: members buy POL with a card on any major exchange or on-ramp, then send it to their own wallet on the Polygon network (guide at ${SITE_URL}/wallets); never name a specific exchange or on-ramp brand.
|
||||
- ACCOUNT: join at ${SITE_URL}/join with email only, a six-digit code, no password. Wallet linking happens inside the Control Room (Credits screen): one signature to link, then payouts switch on by activating (one transaction, gas only) or by buying any package. wallets: say "SafePal or any other crypto wallet", never recommend MetaMask by name (Marty 2026-11-13); in Phantom turn Polygon on first; Trust Wallet blocks a buy that spends most of its POL. No card button on the site: members buy POL with a card on any major exchange or on-ramp, then send it to their own wallet on the Polygon network (guide at ${SITE_URL}/wallets); never name a specific exchange or on-ramp brand.
|
||||
- SPONSOR: the invite link opened most recently sets the sponsor (30-day cookie), shown on the join page, locked when the account is created; the contract binds the buyer to that sponsor at the first purchase. CARRY-OVER: Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their InstantAdPay sponsor from the network registry automatically when no invite link was used. Wrong sponsor before the first purchase: the admin can move the account. Members should switch on payouts before their people buy.
|
||||
- CONTROL ROOM screens: Links, Pages, Zones (with Audiences), Ads, Credits, Reports, Team (three levels, who has payouts on, who bought, qualifying-buyer counts), Wallet (what was paid to this wallet, payout history). More at ${SITE_URL}/tools: Promo tools, Training, Pipeline (a follow-up board for prospects and directs), My line (including the holding tank: members who joined with no sponsor wait there and can be adopted by a member with payouts on and their own qualifying package), Profile.
|
||||
- BTC4HITS (2026-11-11): the closed BTC4Hits rotator site moved here. Its members with a deliverable email were imported as waiting accounts (InstantAdPay first, carried here by the registry sync), with their BTC4Hits sponsor when that sponsor was also imported or already a member, otherwise into the holding tank. Sign-in page: /from/btc4hits (same email, code sign-in, no welcome-back credits). Rotators with visits in the last month became spin links named 'BTC4Hits rotator #<old id>' on the owner's account with every working destination (dead, parked or erroring URLs left out), on a 'BTC4Hits' traffic source; btc4hits.com/ro.php?id=<id> forwards to the spin link, other btc4hits.com pages go to /from/btc4hits. Pro status and old BTC4Hits commissions do not carry over. HOLDING TANK CAP: an adopter may hold up to 10 people from the tank at one time (open adoptions whose person has not switched on payouts yet; was 2). The cap is the site setting tankAdoptCap (default 10). HOLDING TANK MENU ITEM: members who can adopt (payouts on, own $25 package) see Holding tank in the Control Room menu (rail), with a badge of how many can be adopted right now; it opens More > My line, where the Holding tank card lists them and says how many you can adopt at a time. Members who cannot adopt do not see the item.
|
||||
@@ -230,7 +243,7 @@ RULES:
|
||||
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
|
||||
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen in their line.
|
||||
- No em dashes. If you do not know, say so and point to ${SITE_URL}/contract or the ledger.
|
||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
|
||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.${networkBlock()}` + (kbBlock ? '\n\n' + kbBlock : '');
|
||||
}
|
||||
|
||||
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
|
||||
@@ -280,7 +293,13 @@ async function answerRaw(message, historyText) {
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||
let hit = null, kbOk = true;
|
||||
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
try {
|
||||
await kb.load();
|
||||
// another network site named (and this one not): this site's instant answers stand aside, except a hand-off (2026-11-15)
|
||||
const other = /link ?spin/i.test(msg) ? [] : kb.namesOther(msg, process.env.HUB_SITE || 'linkspin');
|
||||
hit = await kb.fastPath(msg);
|
||||
if (hit && other.length && !hit.handoff) hit = null;
|
||||
} catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && (SYN_N() !== 4 || SYN_T() !== 10)) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ const FAQ = [
|
||||
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
||||
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
||||
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
||||
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' },
|
||||
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside your wallet app, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' },
|
||||
{ id: 'f-payouts-where', title: 'Where do my payouts go?', source: 'faq',
|
||||
questions: ['Where do my payouts go?', 'Which wallet gets paid?', 'Does the site hold my earnings?'],
|
||||
tags: ['payout', 'wallet', 'custody'],
|
||||
|
||||
@@ -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 } };
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
|
||||
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
|
||||
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
|
||||
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
|
||||
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
|
||||
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||
// Banners, Stack POL). Keep them identical.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const REFRESH_MS = 10 * 60 * 1000;
|
||||
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
|
||||
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
|
||||
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
|
||||
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||
|
||||
async function call(method, route, body, headers) {
|
||||
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
|
||||
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
|
||||
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
|
||||
async function publish() {
|
||||
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
|
||||
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
|
||||
const body = { name: O.name, url: O.url, entries };
|
||||
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
|
||||
if (h === publishedHash) return { same: true };
|
||||
try {
|
||||
const r = await call('PUT', '/v1/kb', body);
|
||||
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
|
||||
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
|
||||
return r.body;
|
||||
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
// an admin edit: publish a few seconds later (several quick edits go as one)
|
||||
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
|
||||
|
||||
function readCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
|
||||
}
|
||||
function writeCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
|
||||
}
|
||||
async function refresh() {
|
||||
if (!enabled()) return { skipped: true };
|
||||
try {
|
||||
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
|
||||
stats.lastReadAt = Date.now();
|
||||
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
|
||||
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
|
||||
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
|
||||
writeCache();
|
||||
return { version: merged.version, count: merged.entries.length };
|
||||
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
|
||||
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
|
||||
function remote() {
|
||||
const me = siteName(); const out = [];
|
||||
for (const e of merged.entries || []) {
|
||||
if (!e || e.site === me) continue;
|
||||
const s = (merged.sites || {})[e.site] || {};
|
||||
const url = s.url || e.link || '';
|
||||
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
|
||||
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the network's sites as the hub knows them (name, link), this one left out
|
||||
function sites() {
|
||||
const me = siteName();
|
||||
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
|
||||
}
|
||||
|
||||
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
|
||||
function init(opts) {
|
||||
O = opts || {}; readCache();
|
||||
if (!enabled()) return;
|
||||
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
|
||||
if (first.unref) first.unref();
|
||||
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); }
|
||||
function _set(m) { merged = m; } // tests
|
||||
|
||||
const version = () => merged.version || '';
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };
|
||||
@@ -0,0 +1,34 @@
|
||||
// The shared network knowledge base in this site's chatbot (2026-11-15): node qa/netkb-merge.test.cjs
|
||||
// No network: netkb's merged set is set by hand. Checks: this site's entries rank first for a general question, a named site's
|
||||
// entries rank first when it is named, other sites never take the fast path, the prompt labels them with the site and link,
|
||||
// a question naming another site skips this site's instant answers (a hand-off still wins), and own() is this site only.
|
||||
// The SAME file ships in InstantAdPay and LinkSpin.
|
||||
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'netkb-'));
|
||||
delete process.env.DATABASE_URL; delete process.env.OPENROUTER_API_KEY; process.env.NETKB = '0';
|
||||
const kb = require('../kb'); const netkb = require('../netkb'); const bot = require('../chatbot');
|
||||
let pass = 0, fail = 0;
|
||||
const ok = (c, m) => { if (c) { pass++; console.log('PASS', m); } else { fail++; console.log('FAIL', m); } };
|
||||
(async () => {
|
||||
await bot.init({ dataDir: DIR, chain: null });
|
||||
const self = fs.existsSync(path.join(__dirname, '..', 'tickets.js')) ? 'iap' : 'linkspin';
|
||||
netkb._set({ version: 'v1', sites: { downlinehydra: { name: 'DownlineHydra', url: 'https://downlinehydra.com' }, [self]: { name: 'Me', url: 'https://me.example' } },
|
||||
entries: [
|
||||
{ site: 'downlinehydra', id: 'c-pro', title: 'Pro: what it costs', questions: ['How much is Pro?', 'What do I get with Pro?'], answer: 'Pro is $30 one time.', tags: ['pro', 'price'] },
|
||||
{ site: 'downlinehydra', id: 'c-withdraw', title: 'Withdrawals', questions: ['How do I withdraw?'], answer: 'Nothing to withdraw on DownlineHydra.', tags: ['withdraw'] },
|
||||
{ site: self, id: 'c-own', title: 'Own entry from the hub', questions: ['x'], answer: 'never in remote', tags: [] }] });
|
||||
await kb.load(true);
|
||||
const top = async q => { const h = await kb.search(q, 8); return h[0] && h[0].entry; };
|
||||
{ const t = await top('How do I withdraw?'); ok(t && !t.site, 'a general question ranks this site first (' + (t && t.id) + ')'); }
|
||||
{ const t = await top('How do I withdraw on DownlineHydra?'); ok(t && t.site === 'downlinehydra', 'a named site ranks its own entry first (' + (t && t.id) + ')'); }
|
||||
ok(!(await kb.search('Own entry from the hub', 8)).some(h => h.entry.site === self), 'this site\'s own copy on the hub is not read back as another site');
|
||||
{ const b = kb.promptBlock(await kb.context('How much is Pro on DownlineHydra', 6)); ok(/about DownlineHydra, another network site; send people to /.test(b), 'remote entries labelled with site and link'); }
|
||||
{ const r = await bot.answer('How much is Pro on DownlineHydra?'); ok(!r.canned, 'naming another site skips this site\'s instant answers (' + r.kb + ')'); }
|
||||
{ const r = await bot.answer('How do I withdraw?'); ok(r.canned, 'this site\'s own question keeps its instant answer'); }
|
||||
{ const r = await bot.answer('I need a real person, my DownlineHydra pro is missing'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
|
||||
{ const own = await kb.own(); ok(own.length > 10 && own.every(e => !e.site), 'own(): this site\'s entries only (' + own.length + ')'); }
|
||||
ok(kb.namesOther('what is 5xYourTeam', self).includes('fivex') && !kb.namesOther('what is this site', self).length, 'namesOther finds a network site by name');
|
||||
for (const e of await kb.own()) ok(!/\bmetamask\b/i.test(e.answer.replace(/never recommend MetaMask/gi, '')), e.id + ': no MetaMask recommendation in a shared answer');
|
||||
console.log((fail ? 'FAILED ' : 'all network KB checks passed: ') + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -5,7 +5,7 @@
|
||||
# bash qa/run.sh sso # network sign-in InstantAdPay <-> LinkSpin: unit + both servers end to end (NSSO_PEER_DIR = the other repo's site dir if not side by side; also runs in member)
|
||||
# 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
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter + the network merge (netkb)
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
|
||||
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
|
||||
# bash qa/run.sh netconv # conversion linkage: InstantAdPay's joins, wallets, purchases counted once, own account left out, window, aged hits, two copies racing, one Reports list, the landing tag on network links
|
||||
@@ -108,6 +108,7 @@ elif [ "$MODE" = "lsid" ]; then
|
||||
elif [ "$MODE" = "kb" ]; then
|
||||
node qa/kb-retrieval.cjs || status=1
|
||||
node qa/kb-chat.mjs || status=1
|
||||
node qa/netkb-merge.test.cjs || status=1 # the shared network knowledge base: home first, a named site first, labels, fast-path skip (2026-11-15)
|
||||
elif [ "$MODE" = "earn" ]; then
|
||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
||||
else
|
||||
|
||||
Reference in New Issue
Block a user