diff --git a/chatbot.js b/chatbot.js new file mode 100644 index 0000000..751cfa4 --- /dev/null +++ b/chatbot.js @@ -0,0 +1,99 @@ +// Viral Banner Blitz's site assistant (Marty 2026-11-15): what it knows. The engine is chatcore.js (the same on every rebuilt +// site); retrieval also covers the other network sites through the hub (netkb.js), this site's entries first. +// +// Every fact below was checked against this repo on KNOWLEDGE_DATE: config.js (loop 50, 10 verified visitors per shift, 150 network +// ad views per cycle recorded but not credited yet, 6 s visit, 3 browsers per connection a day, 1 free post credit a day for network +// members, 3 banners waiting per member, packs 10 for $3 and 40 for $10, banner look $2), ../contracts VBBShop (SPONSOR_BPS 3000, +// PRIZE_BPS 1000, company the rest, sponsor bound once by voucher, no owner withdraw, failed sends claimable), server.js (100 KB +// image, 125x125, Banner Spin posting 125x125 or 250x250), lsspins.js (SPIN tiles in empty places never shift, cycle or earn), +// public/how.html, packages.html, leaders.html. The prize pot's floor and cap are internal and never shown (Marty's rule). +// HOUSE RULE: when a feature changes, update CANNED and FACTS in the same commit and bump KNOWLEDGE_DATE. +// Plain words, no em dashes, never a promise of income, "SafePal or any other crypto wallet", never RM Circle. +'use strict'; +const core = require('./chatcore'); +const C = require('./config').get(); + +const KNOWLEDGE_DATE = '2026-11-15'; +const URL_ = 'https://' + C.site; +const SUPPORT = 'https://instantadpay.com/support'; +const NOT_INCOME = 'You buy advertising for your own banners, not an income opportunity.'; +const packs = C.packs.map(p => p.credits + ' post credits for $' + p.usd).join(' or '); +const places = C.prizePot.places.join('/'); + +const CANNED = [ + { id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My credits did not show up', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'], + re: core.SUPPORT_RE, handoff: true, + a: 'Network support handles every network site, Viral Banner Blitz included: open ' + SUPPORT + ', say it is about Viral Banner Blitz, and include your wallet address (and the transaction link if it is about a purchase). Marty answers there and by email. Tap "Open network support" below and your question goes with you.' }, + { id: 'refund', title: 'Refunds', q: ['Can I get a refund?', 'Can I cancel my package?'], tags: ['refund', 'cancel'], + re: /\brefund|cancel (my |the |a )?(package|pack|purchase)|money back|reverse (my |a |the )?(payment|transaction)/i, handoff: true, + a: 'Purchases are paid on Polygon and are final once confirmed, so they cannot be reversed or refunded. Every package is a one-time purchase that never renews, so there is nothing to cancel. If something went wrong with a payment, open network support at ' + SUPPORT + ' with the transaction link.' }, + { id: 'about', title: 'What is Viral Banner Blitz?', q: ['What is Viral Banner Blitz?', 'How does Viral Banner Blitz work?', 'What is VBB?'], tags: ['viral banner blitz', 'vbb', 'loop', 'overview'], + re: /(what('s| is) (viral ?banner ?blitz|vbb|the loop|this (site|place))|how does (viral ?banner ?blitz|vbb|the loop|this site|it) work)/i, + a: 'Viral Banner Blitz is one public banner loop the whole community moves. Post a 125x125 banner; it waits in line, then enters the loop. Every ' + C.perShift + ' verified visitors shift every banner one place forward, and the banner at the end rides out: it has cycled, and its owner earns ' + C.viewsPerCycle + ' network ad views. Network members get one free post credit each day they sign in. See ' + URL_ + '/how' }, + { id: 'cycle', title: 'What a cycle earns', q: ['What do I get when my banner cycles?', 'Are the 150 views added yet?', 'What does riding out mean?'], tags: ['cycle', 'ride out', '150 views', 'network ad views'], + re: /(cycle[sd]?|ride[sd]? out|riding out|150 (network )?(ad )?views|what do i (get|earn)|views (added|credited))/i, + a: 'When your banner reaches the end of the loop it rides out: it has cycled, and you earn ' + C.viewsPerCycle + ' network ad views, advertising for your own offers across the network. Right now each cycle is recorded on your My Banners page; adding those views to your network advertising is the next step and is not switched on yet. It is advertising, not cash, and nothing here promises income.' }, + { id: 'free-credit', title: 'Free post credits', q: ['How do I get a free post credit?', 'Is posting free?', 'Why did I not get my free credit?'], tags: ['free credit', 'post credit', 'daily', 'network member'], + re: /(free (post )?credits?|post credits?|is (it|posting) free|daily credit|credit (a|per|each) day)/i, + a: 'Network members (anyone with an InstantAdPay or LinkSpin account) get one free post credit each day they sign in, Central time. Each credit posts one banner into the loop. Want to post more? Credit packs are one-time purchases: ' + packs + '. You can have up to ' + C.maxQueuedPerMember + ' banners waiting at once.' }, + { id: 'post', title: 'Posting a banner', q: ['How do I post a banner?', 'What size is the banner?', 'Can I use a Banner Spin?'], tags: ['post', 'banner', '125x125', 'image', 'link', 'banner spin'], + re: /(post (a |my )?banner|banner size|what size|125 ?x ?125|upload|image|banner spin|my banners)/i, + a: 'On My Banners (' + URL_ + '/my) upload a 125x125 image (100 KB or less) with your link, or post one of your LinkSpin Banner Spins (125x125 or 250x250). It uses one post credit, waits in line, and enters the loop at the front at the next shift. Your link must be a real page that loads.' }, + { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'What is the banner look?', 'Is it a subscription?'], tags: ['packages', 'price', 'credit pack', 'banner look', 'buy'], + re: /(packages?|packs?\b|price|how much(?! pol)|cost|\$ ?(2|3|10)\b|banner look|border|teaser|subscription|tokens?)/i, + a: 'Post credit packs: ' + packs + '. The banner look is $' + C.lookUsd + ' per banner: a bright border in the loop plus a teaser line that shows when someone points at it (add it on My Banners to a banner that is waiting or in the loop). All one-time purchases in POL at the live price, never a subscription; anything above the price comes back in the same transaction. Tokens (network visits) are coming soon. ' + NOT_INCOME }, + { id: 'split', title: 'Where your payment goes', q: ['Where does my payment go?', 'How do payouts work?', 'Do I earn when someone I invite buys?'], tags: ['split', 'payout', 'sponsor', '30%', 'commission'], + re: /(split|payouts?|commission|who gets paid|where does (my|the) (money|payment) go|percent|earn|get paid|invite|introduc)/i, + a: 'Each purchase is split on Polygon in the same transaction: 30% to the network member who introduced the buyer (to Viral Banner Blitz if nobody did), 10% to the weekly leaderboard prize pot, 60% to Viral Banner Blitz. The introducer is set once, on the buyer\'s first purchase, and never changes. Nothing is held and there is nothing to withdraw. ' + NOT_INCOME }, + { id: 'visitors', title: 'What counts as a verified visitor', q: ['What is a verified visitor?', 'Why did my visit not count?', 'How does the loop move?'], tags: ['verified visitor', 'shift', 'visit', 'bots'], + re: /(verified visitors?|visit (did ?n.?t|not) count|counts? as a visit|loop (move|shift)|shift|how (does|do) (the loop|banners) move)/i, + a: 'A verified visitor is a real browser that keeps the loop page open and visible for about ' + C.visitSeconds + ' seconds. Each visitor counts once every 24 hours; bots, crawlers, repeat visits and more than a few visitors per internet connection a day do not count. Every ' + C.perShift + ' verified visitors shift every banner one place forward.' }, + { id: 'leaders', title: 'Weekly leaderboards and prizes', q: ['How do the leaderboards work?', 'How do I win the weekly prize?', 'When are prizes paid?'], tags: ['leaderboard', 'prize', 'weekly', 'ref link', 'traffic sources'], + re: /(leader ?boards?|leaders|prizes?|\bpot\b|winners?|top three|weekly|my link|ref link|traffic sources)/i, + a: 'Share your link (it ends in ?ref= and your network username). Two weekly leaderboards, Monday to Sunday Central time: most verified visitors sent, and most different websites they came from. The top three on each share the prize pot (10% of the week\'s sales, ' + places + ' percent), paid in POL to the wallet of their Viral Banner Blitz account the following Monday. Ties go to whoever got there first. Past winners and their transactions: ' + URL_ + '/leaders' }, + { id: 'spin-tiles', title: 'SPIN tiles in the loop', q: ['What are the SPIN tiles?', 'Why is there a SPIN banner in the loop?'], tags: ['spin', 'banner spin', 'empty space'], + re: /(spin tiles?|tiles? marked spin|\bspin\b banner|banners? marked spin)/i, + a: 'Tiles marked SPIN are members\' LinkSpin Banner Spins showing in empty places of the loop. They are not in the loop: they never shift it, never cycle and never earn. Post a banner and yours takes a real place.' }, + { id: 'withdraw', title: 'Withdrawals', q: ['How do I withdraw?', 'Where is my balance?'], tags: ['withdraw', 'balance', 'cash out'], + re: /(withdraw|cash ?out|my balance|pending (pay|commission))/i, + a: 'There is nothing to withdraw. The introducer\'s 30% goes straight to their wallet inside the buyer\'s transaction (a payment that fails to send waits in the contract for that wallet to claim). Leaderboard prizes are paid in POL to the winners\' wallets. Every payment is in the ledger at ' + URL_ + '/ledger' }, + { id: 'wallet', title: 'Signing in and paying', q: ['How do I sign in?', 'Which wallet should I use?', 'How do I pay?'], tags: ['sign in', 'wallet', 'pol', 'safepal'], + re: /(sign ?(in|up)|log ?in|account|which wallet|what wallet|wallet|metamask|safepal|\bpol\b|polygon|crypto|gas|fee|how (do|can) i (pay|buy))/i, + a: 'Sign in on My Banners (' + URL_ + '/my) through InstantAdPay, LinkSpin or a wallet signature (free, it cannot move funds). Packages are paid in POL on Polygon with SafePal or any other crypto wallet; keep a little extra POL for the network fee.' }, + { id: 'safe', title: 'Is it safe? Is it a scheme?', q: ['Is this a pyramid scheme?', 'Is Viral Banner Blitz legit?', 'Who holds the money?'], tags: ['safe', 'legit', 'pyramid', 'contract'], + re: /(pyramid|ponzi|scam|scheme|legit|safe|trust|rug|who holds)/i, + a: 'Posting is free for network members every day, and packages buy more banner posts and a better-looking banner. The VBBShop contract on Polygon splits each purchase in the same transaction with fixed shares and no owner withdraw. Check every payment at ' + URL_ + '/ledger and the contract at ' + URL_ + '/contract. ' + NOT_INCOME }, + { id: 'promote', title: 'Promote Viral Banner Blitz', q: ['Is there a promo kit?', 'Where are the banners to promote VBB?'], tags: ['promote', 'kit', 'banners'], + re: /(promo|promote|creatives?|kit|swipes?)/i, + a: 'The promo kit at ' + URL_ + '/promote has creatives in the common sizes and copy, all with your link. Every verified visitor you send moves the loop for everyone and counts on the weekly leaderboards.' } +]; + +const FAQ = [ + { id: 'f-network', title: 'Viral Banner Blitz and the other network sites', source: 'faq', tags: ['network', 'one account', 'instantadpay', 'linkspin'], + questions: ['Is Viral Banner Blitz part of InstantAdPay?', 'Do I need a new account?', 'Which network sites are there?'], + answer: 'Viral Banner Blitz is part of the network: one account, username and sponsor across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner. Sign in here through InstantAdPay or LinkSpin.' }, + { id: 'f-old-vbb', title: 'The old Viral Banner Blitz', source: 'faq', tags: ['old account', 'old site', 'balance'], + questions: ['Where is my old Viral Banner Blitz account?', 'Did my old credits carry over?'], + answer: 'Viral Banner Blitz was rebuilt as one shared banner loop. Old members were matched to the network by email; old balances and credits were not carried over. Sign in with InstantAdPay or LinkSpin and you get a free post credit each day you sign in.' } +]; + +const FACTS = () => [ + '- WHAT IT IS: Viral Banner Blitz (' + URL_ + ') is one public loop of ' + C.loopSize + ' member banners (125x125 tiles). A posted banner waits in line, then enters at the front. Every ' + C.perShift + ' verified visitors shift every banner one place; the banner at the end rides out (has cycled) and its owner earns ' + C.viewsPerCycle + ' network ad views. Cycles are recorded on My Banners now; crediting those views to network advertising is NOT switched on yet.', + '- VERIFIED VISITOR: a real browser keeps the loop page open and visible about ' + C.visitSeconds + ' seconds; once per visitor per 24 hours; bots, crawlers, repeats and more than ' + C.perIpDay + ' browsers per connection per day do not count.', + '- POSTING: one post credit per banner. Network members (InstantAdPay or LinkSpin, checked with the network hub) get 1 free post credit each day they sign in (Central day). Up to ' + C.maxQueuedPerMember + ' banners waiting per member. Image 125x125, 100 KB max, or post a LinkSpin Banner Spin (125x125 or 250x250). The link must answer. SPIN tiles in empty places are LinkSpin Banner Spins: they never shift, cycle or earn.', + '- PACKAGES (one-time, POL at the live price, never a subscription, overpayment returned): ' + packs + '; banner look $' + C.lookUsd + ' per banner (border + hover teaser, on a waiting or in-loop banner, one per banner); tokens (network visits at the InstantAdPay visit rate) coming soon.', + '- SPLIT (VBBShop constants, no owner withdraw): 30% to the member who introduced the buyer (bound once, by a keeper-signed voucher, on the first purchase; none = company), 10% to the weekly prize pot, 60% company, same transaction. Failed sends wait in the contract for their owner to claim.', + '- LEADERBOARDS (Monday to Sunday Central): most verified visitors sent (the member\'s ?ref= link) and most different traffic sources (referring sites). Prize pot = 10% of the week\'s sales, half per board, top three ' + places + ' percent, paid in POL to the winners\' VBB wallets the following Monday at the POL price at payout; ties to whoever got there first. Never state a maximum or a cap.', + '- PAGES: / (the loop), /how, /packages, /my (My Banners), /leaders, /promote, /ledger, /contract, /terms, /disclaimer, /privacy. Sign in through InstantAdPay, LinkSpin or a wallet signature.', + '- NO REFUNDS: blockchain payments are final. SUPPORT for account or payment problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site). ' + NOT_INCOME +].join('\n'); + +const SITE = { + id: 'vbb', hubSite: 'vbb', netId: 'vbb', name: 'Viral Banner Blitz', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE, + dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, + intro: 'You are the assistant on Viral Banner Blitz (' + URL_ + '), one public banner loop the community moves with verified visitors: post a 125x125 banner, ride it out, earn network ad views. Network members post free once a day; credit packs and a banner look are one-time purchases.', + quickTopics: ['How does the loop work?', 'Is posting free?', 'How do the leaderboards work?', 'What is ViralAdBlitz?'] +}; + +function init() { return core.init(SITE); } +module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE }; diff --git a/chatcore.js b/chatcore.js new file mode 100644 index 0000000..b1f1493 --- /dev/null +++ b/chatcore.js @@ -0,0 +1,219 @@ +// The site assistant's engine (Marty 2026-11-15: a chatbot on every rebuilt network site), ported from LinkSpin's chatbot.js. +// The site's own chatbot.js holds what it knows (CANNED instant answers + FACTS, written from that site's code); this file +// holds how it answers, the same on every site: +// 1. the knowledge base's instant answers (kb.js, seeded from CANNED; first matching pattern wins, no AI call) +// 2. retrieval over the merged NETWORK knowledge base (this site's entries boosted, netkb.js), into the system prompt +// 3. OpenRouter (deepseek/deepseek-v4-flash:nitro, reasoning OFF, retried once), house rules in the prompt and on the way out +// Account problems go to the network support desk on InstantAdPay (handoff: true makes the widget offer it). +// Routes: POST /api/chat, GET /api/chat/kb-stamp, admin GET/POST /api/admin/kb, GET/PUT/DELETE /api/admin/kb/, +// POST /api/admin/kb/test, GET /api/admin/kb/network (x-admin-token, the site's own isAdmin). +// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const https = require('https'); +const http = require('http'); +const kb = require('./kb'); +const netkb = require('./netkb'); + +const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; +let S = null; // the site: { id, hubSite, name, url, dataDir, canned, faq, facts(), about, supportUrl, linkFor, quickTopics } + +function key() { + if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); + if (!S || !S.dataDir) return ''; + try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } +} +const enabled = () => !!key(); + +// CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence) +function seeds() { + return S.canned.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re ? c.re.source : '', + handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(S.faq || []); +} + +const supportUrl = () => S.supportUrl || 'https://instantadpay.com/support'; +// asking for a person, or one person's own account problem: every site's first CANNED entry uses this (handoff: true) +const SUPPORT_RE = /((contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|someone|a (human|person|real person))|real person|\bhuman\b|customer (service|support)|open a ticket|support (ticket|desk|team|email)|help ?desk|(my|the) (boost|purchase|payment|payout|order|account|sign.?in|log.?in|pro|upgrade|ad|banner|pick)s? (is |was |has |did |does )?(not|never|n.?t|missing|stuck|wrong|failed|broken|lost|gone)|(did ?n.?t|did not|never|has ?n.?t|have ?n.?t) (show|arriv|appear|receiv|get paid|go through|work|confirm)|i (was|got) (charged|scammed)|charged twice)/i; +const HOUSE_RULES = () => `RULES: +- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page. +- Your main job is ${S.name}. Questions about another network site: answer from that site's knowledge-base entry, say which site it is about, and give that site's link exactly as the entry gives it. Never mix two sites' prices, splits or rules. +- NEVER promise or estimate income, and never state a maximum or total anyone can earn. This is advertising with a referral program, never an investment. Nobody earns unless real purchases happen in their line. Crypto payments are final. +- Whenever ad credits come up, say: Ad credits buy advertising, not income. +- Wallets: say "SafePal or any other crypto wallet". Never recommend MetaMask. +- Never mention RM Circle. It is not part of this network. +- No em dashes. If you do not know, say so plainly; never guess a price, a percentage or a rule. +- Anything about one person's own account (a missing payout, a sign-in that will not work, a purchase that did not show, a bug) you cannot look up: say so and send them to network support at ${supportUrl()}.`; + +function networkLine() { + const list = netkb.sites(); + if (!list.length) return ''; + return '\nNETWORK SITES (one network account works across them; link to use for each):\n' + list.map(s => '- ' + s.name + ': ' + s.go).join('\n') + '\n'; +} +function systemPrompt(kbBlock) { + return S.intro + '\n\nFACTS (checked against this site\'s code on ' + S.knowledgeDate + '):\n' + S.facts() + '\n' + networkLine() + '\n' + HOUSE_RULES() + (kbBlock ? '\n\n' + kbBlock : ''); +} + +function endpoint() { + try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); } +} +function askOnce(message, historyText, kbBlock) { + return new Promise((resolve, reject) => { + const body = JSON.stringify({ + model: MODEL, + reasoning: { enabled: false }, // deepseek-v4-flash reasons by default and can spend the whole max_tokens on it (2026-10-16) + max_tokens: 320, + messages: [ + { role: 'system', content: systemPrompt(kbBlock) }, + ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + String(historyText).slice(0, 800) }] : []), + { role: 'user', content: String(message).slice(0, 600) } + ] + }); + const ep = endpoint(); + const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST', + headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body), + 'HTTP-Referer': S.url, 'X-Title': S.name + ' assistant' }, timeout: 30000 }, + res => { + let d = ''; + res.on('data', c => { d += c; }); + res.on('end', () => { + // OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object + const i = d.indexOf('{'); let txt = ''; + try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); } + catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); } + if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content')); + resolve(txt); + }); + }); + req.on('error', reject); + req.on('timeout', () => req.destroy(new Error('openrouter timeout'))); + req.end(body); + }); +} +async function askAI(message, historyText, kbBlock) { + try { return await askOnce(message, historyText, kbBlock); } + catch (e) { await new Promise(r => setTimeout(r, 700)); return askOnce(message, historyText, kbBlock); } // one provider dropping it is the usual cause +} + +// house rules on the way out, whatever the model wrote +const RMC_RE = /\brm ?circle\b|rmcircle/i; +function scrub(t) { + let s = String(t || '').replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', '); + s = s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/^#+\s*/gm, ''); + s = s.replace(/\bMeta ?Mask\b(\s*(,|or|and)\s*)?/gi, '').replace(/\s{2,}/g, ' ').trim(); + return s; +} +const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) ?not (see|check|look)|contact support|network support|support desk|\/support\b)/i; + +async function answer(message, historyText) { + const r = await answerRaw(message, historyText); + if (r && typeof r.reply === 'string') { + r.reply = scrub(r.reply); + if (RMC_RE.test(r.reply)) r.reply = 'I can only help with ' + S.name + ' and the network sites. For anything else, network support at ' + supportUrl() + ' can point you the right way.'; + } + return r; +} +async function answerRaw(message, historyText) { + const msg = String(message || '').trim().slice(0, 600); + if (!msg) return { error: 'Say something first.' }; + let hit = null, kbOk = true, other = []; + try { + await kb.load(); + // a question about another network site (named, and this site not named) skips this site's instant answers, except a hand-off + other = kb.namesOther(msg, S.hubSite); + if (other.length && new RegExp('\\b' + S.name.replace(/[^A-Za-z0-9]+/g, '\\s*') + '\\b', 'i').test(msg)) other = []; + 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) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {}); + if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + let kbBlock = '', kbIds = [], hits = []; + try { + const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; + hits = await kb.context(query, 6); + kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id); + } catch (e) { console.error('kb search', e.message); } + if (!enabled()) { + // no AI: the best matching entry, if it is a clear match, else the honest fallback + if (hits.length) { const e = hits[0].entry; return { reply: e.answer + (e.site ? ' More at ' + e.go : ''), kb: [e.id] }; } + return { reply: S.fallback || ('Good question. The quick answers I have cover how ' + S.name + ' works, what it costs and how payouts work. For anything else, network support at ' + supportUrl() + ' will help.'), handoff: true }; + } + try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); } + catch (e) { + console.error('chat AI failed', e.message); + if (hits.length) { const x = hits[0].entry; return { reply: x.answer + (x.site ? ' More at ' + x.go : ''), kb: [x.id] }; } + return { reply: 'I hit a snag answering that one, on our side. The live ledger at ' + S.url + '/ledger and the contract page at ' + S.url + '/contract cover most deep questions, or network support at ' + supportUrl() + ' will answer.', handoff: true }; + } +} + +// ---- rate limit: per visitor, in memory ---- +const hits = new Map(); +function limited(ip) { + const now = Date.now(); const h = hits.get(ip) || { m: 0, mAt: now, d: 0, dAt: now }; + if (now - h.mAt > 60000) { h.m = 0; h.mAt = now; } + if (now - h.dAt > 86400000) { h.d = 0; h.dAt = now; } + h.m++; h.d++; hits.set(ip, h); + if (hits.size > 20000) hits.clear(); + return h.m > 12 || h.d > 300; +} +const ipOf = req => String(req.headers['cf-connecting-ip'] || String(req.headers['x-forwarded-for'] || '').split(',')[0] || (req.socket && req.socket.remoteAddress) || 'x').trim(); + +// h: { json(res, code, obj, extra), readBody(req), isAdmin(req) }; returns true when it answered +async function handle(req, res, p, u, h) { + if (p === '/api/chat' && req.method === 'POST') { + if (limited(ipOf(req))) { h.json(res, 429, { error: 'Give it a minute, then ask again.' }); return true; } + const b = await h.readBody(req); + const hist = Array.isArray(b.history) ? b.history.map(x => String(x || '')).join(' ').slice(-800) : String(b.history || '').slice(-800); + const r = await answer(b.message, hist); + if (r.handoff) r.support = supportLink(b.message); + h.json(res, r.error ? 400 : 200, r); return true; + } + if (p === '/api/chat/config' && req.method === 'GET') { h.json(res, 200, { name: S.name, support: supportUrl(), topics: S.quickTopics || [] }, { 'Cache-Control': 'public, max-age=300' }); return true; } + if (p === '/api/chat/kb-stamp' && req.method === 'GET') { h.json(res, 200, Object.assign(await kb.stamp(), { knowledgeDate: S.knowledgeDate }), { 'Cache-Control': 'no-store' }); return true; } + if (!p.startsWith('/api/admin/kb')) return false; + if (!h.isAdmin(req)) { h.json(res, 401, { error: 'no' }); return true; } + if (p === '/api/admin/kb') { + if (req.method === 'GET') { h.json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }); return true; } + if (req.method === 'POST') { const r = await kb.create(await h.readBody(req)); h.json(res, r.error ? 400 : 200, r); return true; } + } + if (p === '/api/admin/kb/test' && req.method === 'POST') { const b = await h.readBody(req); h.json(res, 200, Object.assign(await kb.test(b.question), b.answer ? { answer: await answer(b.question) } : {})); return true; } + if (p === '/api/admin/kb/network' && req.method === 'GET') { + if (u.searchParams.get('refresh') === '1') await netkb.refresh(); + if (u.searchParams.get('publish') === '1') await netkb.publish(); + h.json(res, 200, Object.assign(netkb.view(), { ai: enabled(), model: MODEL })); return true; + } + const m = /^\/api\/admin\/kb\/([A-Za-z0-9._:-]{1,80})$/.exec(p); + if (m) { + if (req.method === 'GET') { const e = await kb.get(m[1]); h.json(res, e ? 200 : 404, e ? { entry: e } : { error: 'Entry not found.' }); return true; } + if (req.method === 'PUT') { const r = await kb.update(m[1], await h.readBody(req)); h.json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); return true; } + if (req.method === 'DELETE') { const r = await kb.remove(m[1]); h.json(res, r.error ? 404 : 200, r); return true; } + } + h.json(res, 404, { error: 'Not found' }); return true; +} +// the support desk link the widget offers: InstantAdPay's public form, told which site and question it came from +function supportLink(q) { + const qs = new URLSearchParams({ from: S.id, subject: (S.name + ': ' + String(q || '').replace(/\s+/g, ' ').trim()).slice(0, 120) }); + return supportUrl() + '?' + qs.toString(); +} + +// the link to another network site: its LinkSpin tracked link with ?src= (netsites.js), else its plain address +const hostOf = x => { try { return new URL(x).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } }; +function linkVia(netId) { + return url => { + try { + const ns = require('./netsites'); const h = hostOf(url); + const m = ns.list().concat(ns.FALLBACK || []).find(s => hostOf(s.url) === h); + return (m && netId && m.id !== netId && ns.tracked(m.id, netId)) || url; + } catch (e) { return url; } + }; +} + +// site: see S above. Call after docstore.init (kb.json is a MySQL document there). +function init(site) { + S = site; if (!S.linkFor) S.linkFor = linkVia(S.netId); + const ready = kb.init({ dataDir: site.dataDir, seeds: seeds(), siteUrl: site.url, helpText: 'network support at ' + supportUrl() }); + netkb.init({ dataDir: site.dataDir, site: site.hubSite, name: site.name, url: site.url, entries: () => kb.own(), linkFor: site.linkFor }); + return ready; +} + +module.exports = { init, handle, answer, enabled, seeds, systemPrompt, scrub, supportLink, linkVia, SUPPORT_RE, _limited: limited }; diff --git a/kb.js b/kb.js new file mode 100644 index 0000000..9a5053f --- /dev/null +++ b/kb.js @@ -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 } }; diff --git a/netkb.js b/netkb.js new file mode 100644 index 0000000..0a79f6c --- /dev/null +++ b/netkb.js @@ -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 ":", 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 }; diff --git a/public/admin.html b/public/admin.html index 98d0586..d4cba99 100644 --- a/public/admin.html +++ b/public/admin.html @@ -38,5 +38,6 @@ + diff --git a/public/assets/chat.css b/public/assets/chat.css new file mode 100644 index 0000000..d169c6b --- /dev/null +++ b/public/assets/chat.css @@ -0,0 +1,34 @@ +/* Site assistant widget, Viral Banner Blitz look (vbb.css): pop-art. Cream panel, thick ink borders with hard offset shadows, + hot pink and amber, Bricolage Grotesque headings, DM Sans body. Fallbacks match vbb.css. */ +#scChat{--sc-bg:var(--bg2,#fffaf0);--sc-ink:var(--ink,#14121f);--sc-sub:var(--muted,#4d4862);--sc-head:var(--amber,#ffd400);--sc-hot:var(--hot,#ff2d87); + --sc-bot:var(--panel,#fff);--sc-me:var(--sky,#2b59ff);--sc-edge:2.5px solid var(--line2,#14121f);--sc-shadow:5px 5px 0 var(--line2,#14121f);--sc-shadow-sm:3px 3px 0 var(--line2,#14121f); + --sc-font:var(--body,"DM Sans","Segoe UI",system-ui,sans-serif);--sc-disp:var(--disp,"Bricolage Grotesque","Arial Black",system-ui,sans-serif); + position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)} +#scBtn{width:58px;height:58px;border-radius:16px;border:var(--sc-edge);cursor:pointer;background:var(--sc-hot);color:#fff;display:flex;align-items:center;justify-content:center;box-shadow:var(--sc-shadow-sm);transition:transform .12s} +#scBtn:hover{transform:translate(-2px,-2px);box-shadow:var(--sc-shadow)} +#scBtn:focus-visible{outline:3px solid var(--sc-me);outline-offset:3px} +#scChat.open #scBtn{background:var(--sc-head);color:var(--sc-ink)} +#scPanel{position:absolute;right:0;bottom:74px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column; + background:var(--sc-bg);color:var(--sc-ink);border:var(--sc-edge);border-radius:16px;box-shadow:var(--sc-shadow);overflow:hidden} +.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--sc-head);color:var(--sc-ink);border-bottom:var(--sc-edge)} +.sc-head>div{flex:1;min-width:0} +.sc-title{display:block;font-family:var(--sc-disp);font-weight:800;font-size:20px;letter-spacing:-.02em} +.sc-sub{display:block;font-size:12.5px;color:var(--sc-ink);opacity:.8} +#scClose{background:#fff;border:2px solid var(--sc-ink);border-radius:8px;color:var(--sc-ink);font-size:20px;line-height:1;width:30px;height:30px;cursor:pointer;padding:0} +.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px} +.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;border-radius:12px;border:2px solid var(--sc-ink);overflow-wrap:anywhere} +.sc-m.bot{align-self:flex-start;background:var(--sc-bot);color:var(--sc-ink);box-shadow:var(--sc-shadow-sm)} +.sc-m.me{align-self:flex-end;background:var(--sc-me);color:#fff;box-shadow:var(--sc-shadow-sm)} +.sc-m a{color:inherit;text-decoration:underline;text-decoration-thickness:2px} +.sc-m.wait{opacity:.6} +.sc-cta{display:inline-block;background:var(--sc-hot);color:#fff!important;text-decoration:none!important;font-weight:800;padding:8px 14px;border:2px solid var(--sc-ink);border-radius:10px;box-shadow:var(--sc-shadow-sm);font-family:var(--sc-disp)} +.sc-handoff{background:transparent!important;border:0!important;box-shadow:none!important;padding:0!important} +.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px} +.sc-topics button{background:var(--amber-soft,#fff3a8);color:var(--sc-ink);border:2px solid var(--sc-ink);border-radius:999px;font:700 12.5px var(--sc-font);padding:4px 10px;cursor:pointer} +.sc-topics button:hover{background:var(--sc-head)} +.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:var(--sc-edge);background:#fff} +.sc-input input{flex:1;min-width:0;border:2px solid var(--sc-ink);border-radius:10px;padding:9px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:var(--sc-bg)} +.sc-input input:focus{outline:3px solid var(--sc-hot);outline-offset:0} +.sc-input button{background:var(--sc-hot);color:#fff;border:2px solid var(--sc-ink);border-radius:10px;font:800 14px var(--sc-disp);padding:0 16px;cursor:pointer;box-shadow:var(--sc-shadow-sm)} +.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:0 0 10px;background:#fff} +@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:66px;height:calc(100vh - 100px)}} diff --git a/public/assets/chat.js b/public/assets/chat.js new file mode 100644 index 0000000..88415c9 --- /dev/null +++ b/public/assets/chat.js @@ -0,0 +1,72 @@ +// Site assistant widget (2026-11-15): a round button bottom right, a panel that asks /api/chat. The look is this site's own, +// in /assets/chat.css (colors and fonts from the site's stylesheet). When an answer cannot help, or the visitor asks for a +// person, it offers "Open network support": InstantAdPay's support desk, which already knows the question and the site. +// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL. +(function () { + if (window.__siteChat || /^\/admin/.test(location.pathname)) return; + window.__siteChat = 1; + var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/assets/chat.css?v=20261115c'; document.head.appendChild(css); + var NAME = 'this site', TOPICS = []; + var root = document.createElement('div'); root.id = 'scChat'; + root.innerHTML = '' + + ''; + document.body.appendChild(root); + var $ = function (id) { return document.getElementById(id); }; + var msgs = $('scMsgs'), input = $('scIn'), panel = $('scPanel'), btn = $('scBtn'); + var history = [], greeted = false, support = 'https://instantadpay.com/support'; + fetch('/api/chat/config').then(function (r) { return r.json(); }).then(function (c) { + if (c.name) { NAME = c.name; $('scTitle').textContent = 'Ask ' + c.name; } + if (c.support) { support = c.support; $('scHuman').href = c.support; } + TOPICS = c.topics || []; + }).catch(function () {}); + + function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); } + function add(text, who) { + var d = document.createElement('div'); d.className = 'sc-m ' + who; + d.innerHTML = esc(text).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)])/g, '$1'); + msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; return d; + } + function offer(link) { + var old = msgs.querySelector('.sc-handoff'); if (old) old.remove(); + var d = document.createElement('div'); d.className = 'sc-m bot sc-handoff'; + var a = document.createElement('a'); a.className = 'sc-cta'; a.href = link || support; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open network support'; + d.appendChild(a); msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; + } + function open() { + panel.hidden = false; btn.setAttribute('aria-expanded', 'true'); root.className = 'open'; + if (!greeted) { + greeted = true; + add('Hi. Ask me how ' + NAME + ' works, what it costs, how payouts work, or about any other site in the network. Straight answers, no income hype.', 'bot'); + var t = $('scTopics'); TOPICS.slice(0, 4).forEach(function (q) { + var b = document.createElement('button'); b.type = 'button'; b.textContent = q; b.addEventListener('click', function () { input.value = q; send(); }); t.appendChild(b); + }); + } + setTimeout(function () { input.focus(); }, 50); + } + function close() { panel.hidden = true; btn.setAttribute('aria-expanded', 'false'); root.className = ''; } + btn.addEventListener('click', function () { panel.hidden ? open() : close(); }); + $('scClose').addEventListener('click', close); + document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !panel.hidden) close(); }); + async function send() { + var q = input.value.trim(); if (!q) return; + input.value = ''; $('scTopics').innerHTML = ''; + add(q, 'me'); var wait = add('...', 'bot wait'); + try { + var r = await (await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: q, history: history.slice(-6) }) })).json(); + wait.remove(); + add(r.reply || r.error || 'Something went wrong. Try again in a moment.', 'bot'); + history.push(q, r.reply || ''); + if (r.handoff) offer(r.support); + } catch (e) { wait.remove(); add('I could not reach the assistant just now. Try again in a moment, or open network support.', 'bot'); offer(); } + } + $('scForm').addEventListener('submit', function (e) { e.preventDefault(); send(); }); +})(); diff --git a/public/contract.html b/public/contract.html index 157a426..32d941d 100644 --- a/public/contract.html +++ b/public/contract.html @@ -52,5 +52,6 @@ + diff --git a/public/disclaimer.html b/public/disclaimer.html index c76b204..ad61e0b 100644 --- a/public/disclaimer.html +++ b/public/disclaimer.html @@ -36,5 +36,6 @@ + diff --git a/public/how.html b/public/how.html index de6b58e..1c9e81c 100644 --- a/public/how.html +++ b/public/how.html @@ -58,5 +58,6 @@ + diff --git a/public/index.html b/public/index.html index 4648dcc..a0fa72e 100644 --- a/public/index.html +++ b/public/index.html @@ -58,5 +58,6 @@ + diff --git a/public/leaders.html b/public/leaders.html index a408710..b68c427 100644 --- a/public/leaders.html +++ b/public/leaders.html @@ -35,5 +35,6 @@ + diff --git a/public/ledger.html b/public/ledger.html index e732b64..b881d3f 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -37,5 +37,6 @@ + diff --git a/public/my.html b/public/my.html index 9b0d1be..e6343e0 100644 --- a/public/my.html +++ b/public/my.html @@ -82,5 +82,6 @@ + diff --git a/public/packages.html b/public/packages.html index 8f5f2e0..015b654 100644 --- a/public/packages.html +++ b/public/packages.html @@ -47,5 +47,6 @@ + diff --git a/public/privacy.html b/public/privacy.html index fbee33b..2e5bbe7 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -37,5 +37,6 @@ + diff --git a/public/promote.html b/public/promote.html index 0f9df04..119407c 100644 --- a/public/promote.html +++ b/public/promote.html @@ -37,5 +37,6 @@ + diff --git a/public/terms.html b/public/terms.html index 19d5461..70a2c6b 100644 --- a/public/terms.html +++ b/public/terms.html @@ -42,5 +42,6 @@ + diff --git a/qa/chat-qa.json b/qa/chat-qa.json new file mode 100644 index 0000000..526770e --- /dev/null +++ b/qa/chat-qa.json @@ -0,0 +1,22 @@ +{ + "site": "vbb", + "home": [ + { "q": "What is Viral Banner Blitz?", "kb": "about", "must": ["loop", "10 verified visitors", "150 network ad views"] }, + { "q": "Is posting free?", "kb": "free-credit", "must": ["one free post credit", "InstantAdPay or LinkSpin"] }, + { "q": "What size is the banner?", "kb": "post", "must": ["125x125", "100 KB"] }, + { "q": "How much are the packages?", "kb": "packages", "must": ["10 post credits for \\$3", "40 post credits for \\$10", "\\$2"] }, + { "q": "Where does my payment go?", "kb": "split", "must": ["30%", "10%", "60%"] }, + { "q": "Are the 150 views added to my advertising yet?", "kb": "cycle", "must": ["not switched on yet"] }, + { "q": "How do I win the weekly prize?", "kb": "leaders", "must": ["top three", "following Monday"] }, + { "q": "What are the SPIN tiles?", "kb": "spin-tiles", "must": ["never shift"] }, + { "q": "Which wallet should I use?", "kb": "wallet", "must": ["SafePal or any other crypto wallet"] }, + { "q": "Is this a pyramid scheme?", "kb": "safe", "must": ["contract", "not an income opportunity"] } + ], + "cross": [ + { "q": "What is Downline Banners?", "site": "bannerline" }, + { "q": "How does a ViralAdBlitz Boost work?", "site": "viraladblitz" }, + { "q": "What is DownlineHydra Pro?", "site": "downlinehydra" }, + { "q": "What is LinkSpin Banner Spin?", "site": "linkspin" }, + { "q": "What is the 5xYourTeam draft?", "site": "fivex" } + ] +} diff --git a/qa/chatbot.test.mjs b/qa/chatbot.test.mjs new file mode 100644 index 0000000..e8c4b4d --- /dev/null +++ b/qa/chatbot.test.mjs @@ -0,0 +1,87 @@ +// Site assistant checks (2026-11-15): node qa/chatbot.test.mjs +// No network: a stand-in OpenRouter and a stand-in hub. Checks the instant answers route every example question to its own entry, +// the house rules (no em dashes, no MetaMask, never RM Circle, ad-credits line where credits come up, no income promises), +// the network merge (home boosted, a named site boosted), the support hand-off, and the site's scripted Q&A (qa/chat-qa.json: +// home questions must land on the named entry and contain the expected facts). +// The SAME file ships in every rebuilt network site. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); + +const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'chat-')); +process.env.DATA_DIR = DIR; delete process.env.DOCSTORE_URL; process.env.NETKB = '0'; delete process.env.OPENROUTER_API_KEY; +let pass = 0, fail = 0; const bad = []; +const ok = (c, m) => { if (c) pass++; else { fail++; bad.push(m); console.log('FAIL', m); } }; + +// stand-in OpenRouter: answers with what the system prompt says about the first KB entry, so we can see the prompt +let lastPrompt = '', reply = 'Fine.'; +const or = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => { + const j = JSON.parse(b); lastPrompt = j.messages[0].content; ok(j.reasoning && j.reasoning.enabled === false, 'reasoning is switched off'); + res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('\n\n' + JSON.stringify({ choices: [{ message: { content: reply } }] })); }); }); +await new Promise(r => or.listen(0, r)); +process.env.OPENROUTER_URL = 'http://127.0.0.1:' + or.address().port + '/v1/chat/completions'; + +const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset(); +const bot = require(path.join(ROOT, 'chatbot.js')); +const core = require(path.join(ROOT, 'chatcore.js')); +const kb = require(path.join(ROOT, 'kb.js')); +const netkb = require(path.join(ROOT, 'netkb.js')); +const dataDir = bot.SITE.dataDir; +await bot.init(); + +// 1. seeds and the fast path: every example question of a canned entry lands on that entry (first match wins) +const seeds = core.seeds(); +ok(seeds.length >= 12, 'at least 12 seeded entries (' + seeds.length + ')'); +for (const c of bot.CANNED) { + ok(c.re instanceof RegExp, c.id + ' has a pattern'); + for (const q of c.q || []) { const hit = await kb.fastPath(q); ok(hit && hit.id === 'c-' + c.id, 'example "' + q + '" -> ' + c.id + ' (got ' + (hit && hit.id) + ')'); } +} +// 2. house rules in every seeded answer +for (const s of seeds) { + ok(!/[—―]/.test(s.answer + s.title), s.id + ': no em dashes'); + ok(!/metamask/i.test(s.answer), s.id + ': never recommends MetaMask'); + ok(!/rm ?circle/i.test(s.answer), s.id + ': never RM Circle'); + ok(!/(guarantee[ds]? (income|earnings|profit)|you will (earn|make)|passive income|get rich|up to \$?\d[\d,.]* (a|per) (day|week|month))/i.test(s.answer), s.id + ': no income promise'); + if (/\bad credits?\b/i.test(s.answer)) ok(/Ad credits buy advertising, not income\./.test(s.answer), s.id + ': ad credits line'); + if (/wallet/i.test(s.answer) && /(which|use|recommend)/i.test(s.answer) && /safepal/i.test(s.answer)) ok(/SafePal or any other crypto wallet/i.test(s.answer), s.id + ': wallet wording'); +} +// 3. the engine: scrub, support hand-off, the AI path +ok(core.scrub('A — B, use MetaMask or SafePal') === 'A, B, use SafePal', 'scrub: em dash and MetaMask (' + core.scrub('A — B, use MetaMask or SafePal') + ')'); +{ const r = await bot.answer('I need to talk to a real person about my account'); ok(r.handoff === true, 'asking for a person hands off'); } +{ const r = await bot.answer(''); ok(!!r.error, 'empty question refused'); } +fs.writeFileSync(path.join(dataDir || DIR, 'openrouter.key'), 'test-key'); +reply = 'Sure — try RM Circle'; { const r = await bot.answer('zzqx unrelated words nobody wrote down'); ok(!/rm ?circle/i.test(r.reply) && !/—/.test(r.reply), 'an RM Circle or em dash reply never leaves (' + r.reply + ')'); } +ok(/NEVER promise or estimate income/.test(lastPrompt) && /SafePal or any other crypto wallet/.test(lastPrompt) && /Ad credits buy advertising, not income\./.test(lastPrompt), 'house rules in the system prompt'); +reply = 'Fine.'; + +// 4. the network merge: home boosted, a named site boosted, labelled with the site and its link +const GENERAL = bot.CANNED.find(c => !['support', 'refund', 'about'].includes(c.id) && (c.q || []).length).q[0].replace(/\?$/, ''); +netkb._set({ version: 'v1', sites: { othersite: { name: 'Other Site', url: 'https://other.example', count: 1 }, [process.env.HUB_SITE || bot.SITE.hubSite]: { name: bot.SITE.name, url: bot.SITE.url } }, + entries: [{ site: 'othersite', id: 'about', title: 'What is Other Site?', questions: ['What is Other Site?', GENERAL + ' on Other Site'], answer: 'Other Site is a test site with its own rules.', tags: ['test'] }] }); +await kb.load(true); +{ const hits = await kb.search(GENERAL, 8); const top = hits[0] && hits[0].entry; ok(top && !top.site, 'home entries first for a general question (top ' + (top && top.id) + ')'); } +{ const hits = await kb.search(GENERAL + ' on Other Site', 8); const top = hits[0] && hits[0].entry; ok(top && top.site === 'othersite', 'a named site boosts its own entry (top ' + (top && top.id) + ')'); } +{ const block = kb.promptBlock(await kb.context('What is Other Site', 6)); ok(/about Other Site, another network site; send people to https:\/\/other\.example/.test(block), 'remote entry labelled with site and link'); } +{ const fp = await kb.fastPath('What is Other Site?'); ok(!fp || !String(fp.id).startsWith('othersite:'), 'other sites never take the fast path'); } +{ const r = await bot.answer(GENERAL + ' on Other Site'); ok(!r.canned, 'a question naming another site skips this site\'s instant answers (' + r.kb + ')'); } +{ const r = await bot.answer('I need a real person, my order on Other Site failed'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); } +{ const r = await bot.answer(bot.CANNED.find(c => c.id === 'about').q[0]); ok(r.canned && r.kb === 'c-about', 'this site\'s own name keeps the instant answer'); } +{ const own = await kb.own(); ok(own.length === seeds.length && own.every(e => !e.site), 'publish set = this site\'s own entries only'); } + +// 5. the scripted Q&A (home questions) +const qaFile = path.join(ROOT, 'qa', 'chat-qa.json'); +if (fs.existsSync(qaFile)) { + const qa = JSON.parse(fs.readFileSync(qaFile, 'utf8')); + for (const t of qa.home || []) { + const r = await bot.answer(t.q); + if (t.kb) ok(r.kb === 'c-' + t.kb || (Array.isArray(r.kb) && r.kb.includes('c-' + t.kb)), 'Q&A "' + t.q + '" -> ' + t.kb + ' (got ' + JSON.stringify(r.kb) + ')'); + for (const m of t.must || []) ok(new RegExp(m, 'i').test(r.reply) || new RegExp(m, 'i').test(lastPrompt), 'Q&A "' + t.q + '" mentions /' + m + '/'); + } +} +or.close(); +console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed'); +process.exit(fail ? 1 : 0); diff --git a/qa/smoke.mjs b/qa/smoke.mjs index f9cecc8..1194c66 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -87,7 +87,7 @@ const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, LOOP_SIZE: '5', VISITORS_PER_SHIFT: '3', VIEWS_PER_CYCLE: '150', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + (PORT + 1) + '/api/network/member', NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', LS_PARTNER_URL: 'http://127.0.0.1:' + LS_PORT, LS_SPINS_FIRST_MS: '300', LS_SPINS_EVERY_MS: '700', CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', - HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300', HUB_DOWN_MS: '400' }); + HUB_ENABLED: '1', NETKB: '0', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300', HUB_DOWN_MS: '400' }); const sleep = ms => new Promise(r => setTimeout(r, ms)); let pass = 0, fail = 0; let srv = null; const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 400) : '')); } }; @@ -211,6 +211,14 @@ async function main() { r = await anon.req('/sitemap.xml'); ok((await r.text()).includes('/promote'), 'sitemap lists /promote'); } r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in'); + // the site assistant (2026-11-15): widget on every page, canned answers without AI, account problems hand off, admin KB behind the token + { const home = await (await anon.req('/')).text(); + ok(/