diff --git a/chatbot.js b/chatbot.js new file mode 100644 index 0000000..315a05e --- /dev/null +++ b/chatbot.js @@ -0,0 +1,92 @@ +// Downline Banners' 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: ../contracts BannerLine (PRICE_CENTS 500, SPONSOR_BPS 3000, +// LEVEL_BPS 550 x LEVELS 10, FEE_A 500 + FEE_B 500 = company 10%, FUND_BPS 500, GIFT_COOLDOWN 7 days, no setters, no owner withdraw, +// a failed send goes to the fund), config.js (300 views, 30 days, 12 board slots, gate 9 s / 10 s, keeper 4 h stall, 12 a day), +// server.js (468x60 image up to 150 KB), dlbnas.js (Network Ad Space finishes a spot after 30 days), refuelspots.js (a $50+ Monthly +// Refuel on InstantAdPay or LinkSpin earns a spot), public/how.html, join.html, index.html. +// 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_PROMISED = 'Nothing is promised: you are paid only when spots sell after yours, and a spot can earn back less than it cost.'; + +const CANNED = [ + { id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My spot 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, Downline Banners included: open ' + SUPPORT + ', say it is about Downline Banners, and include your wallet address and the transaction link if it is about a spot. 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 on my spot?', 'Can I cancel my spot?'], tags: ['refund', 'cancel'], + re: /\brefund|cancel (my |the |a )?spot|money back|reverse (my |a |the )?(payment|transaction)/i, handoff: true, + a: 'Spots are paid on Polygon straight to the contract and are final once confirmed, so they cannot be reversed or refunded. A spot is one payment, never a subscription. If something went wrong with a payment, open network support at ' + SUPPORT + ' with the transaction link.' }, + { id: 'about', title: 'What is Downline Banners?', q: ['What is Downline Banners?', 'How does Downline Banners work?', 'What is DLB?'], tags: ['downline banners', 'dlb', 'line', 'board', 'overview'], + re: /(what('s| is) (downline ?banners?|dlb|the line|this (site|place))|how does (downline ?banners?|dlb|the line|this site|it) work)/i, + a: 'Downline Banners is one global line of 468x60 banner spots. A $5 spot buys ' + C.viewsOwed + ' guaranteed views on the board for your image and link (within ' + C.spotDays + ' days, newest spots on top) and a place in the line. When a later spot sells, the contract pays the 10 spots before it and the buyer\'s sponsor in that same transaction. ' + NOT_PROMISED + ' See ' + URL_ + '/how' }, + { 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. Every share goes straight to the owner\'s wallet in the buyer\'s transaction; the contract holds nothing except the momentum fund. Every sale and payout shows in the live ledger at ' + URL_ + '/ledger' }, + { id: 'split', title: 'Where the $5 goes', q: ['Where does the $5 go?', 'How do payouts work?', 'What do I get when someone I refer buys?', 'How much do I earn per spot?'], tags: ['split', 'payout', 'sponsor', 'line', 'commission'], + re: /(split|payouts?|commission|who gets paid|where does (my|the) (money|\$ ?5) go|percent|earn|get paid|refer(red|ral)? (buys|someone)|0\.275|1\.50)/i, + a: 'In the same transaction: 30% ($1.50) to the buyer\'s sponsor (no sponsor: the momentum fund), 55% split as $0.275 to each of the owners of the 10 spots bought just before this one, 10% to the company and 5% to the momentum fund, which can only buy spots. So each time one of the next 10 spots after yours sells, you receive $0.275 in POL, and $1.50 when someone you referred buys. The splits cannot be changed and there is no owner withdraw. ' + NOT_PROMISED }, + { id: 'fund', title: 'The momentum fund and gifted spots', q: ['What is the momentum fund?', 'How do I get a gifted spot?', 'Who gets free spots?'], tags: ['momentum fund', 'gift', 'free spot', 'keeper'], + re: /(momentum fund|\bfund\b|gift(ed)? spots?|free spots?|keeper)/i, + a: 'The momentum fund gets 5% of every spot (and any payout that fails to send) and can only buy spots. When no spot has sold for ' + C.keeperStallHours + ' hours, it buys one (at most ' + C.keeperMaxPerDay + ' a day) and gifts it to an active member who owns a paid spot and has not had a gift in 7 days, members who referred someone recently first. If nobody qualifies, the fund keeps the spot and its line money goes back into the fund.' }, + { id: 'tour', title: 'The Look around first tour', q: ['Why can I not join yet?', 'What is the Look around first tour?', 'Why is Join locked?'], tags: ['tour', 'gate', 'look around', 'join locked'], + re: /(look around|tour|join (is )?locked|(can.?t|cannot|can i not) join|not join yet|unlock|timer|count ?down)/i, + a: 'Before Join unlocks, the home page walks you through a few short steps (your sponsor\'s spot, the board, the 3 newest spots), each with a timer of a few seconds. Keep the tab open while it counts down, then Join unlocks.' }, + { id: 'buy-for', title: 'Buying a spot for someone else', q: ['Can I buy a spot for someone else?', 'Can I gift a spot?'], tags: ['buy for', 'gift', 'someone else'], + re: /(for someone else|for (a |my )?(friend|member|downline|team)|buy (a spot )?for|gift a spot)/i, + a: 'Yes: on ' + URL_ + '/join use "Buy a spot for someone else" with their wallet address. They own the spot and its place in the line.' }, + { id: 'refuel', title: 'Refuel spots', q: ['Do I get a spot when I refuel?', 'What is a refuel spot?'], tags: ['refuel', 'instantadpay', 'linkspin', 'free spot'], + re: /(refuel)/i, + a: 'A counted Monthly Refuel of $50 or more on InstantAdPay or LinkSpin earns the refueling member one Downline Banners spot, bought for their wallet under their network sponsor and paid by the company. InstantAdPay decides which refuels count.' }, + { id: 'spot', title: 'What a spot buys and costs', q: ['How much is a spot?', 'What does a spot buy?', 'Is it a subscription?', 'Can I buy more than one spot?'], tags: ['spot', 'price', '$5', '300 views', 'board'], + re: /(\bspots?\b|\$ ?5\b|five dollars|how much(?! pol)|price|cost|300 views|guaranteed views|subscription)/i, + a: 'A spot is $5 in POL at the Chainlink POL/USD price, one payment, never a subscription. It buys ' + C.viewsOwed + ' guaranteed views on the board for your 468x60 image and link, delivered within ' + C.spotDays + ' days, and a place in the line. Each spot takes the next place, so you can buy more than one. If a spot has not reached ' + C.viewsOwed + ' views after ' + C.spotDays + ' days, Network Ad Space finishes it. Get one at ' + URL_ + '/join' }, + { id: 'banner', title: 'Your banner image and link', q: ['How do I add my banner?', 'What size is the banner?', 'How do I change my image?'], tags: ['banner', '468x60', 'image', 'link', 'my spots'], + re: /(468 ?x ?60|banner (size|image)|what size|upload|add (my |an )?(image|banner|link)|change (my )?(image|banner|link)|my spots)/i, + a: 'After buying, open My Spots (' + URL_ + '/my), sign in with one free signature (it cannot move funds), and add your 468x60 image (150 KB or less) and link to each spot. Your spot then shows on the board, newest on top, until it has its ' + C.viewsOwed + ' views.' }, + { 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: 'Pay from your own wallet straight to the contract with SafePal or any other crypto wallet on Polygon; the site never holds your money. Keep a little extra POL for the network fee. Sign in to My Spots with one free signature, or through your InstantAdPay or LinkSpin account.' }, + { id: 'safe', title: 'Is it safe? Is it a scheme?', q: ['Is this a pyramid scheme?', 'Is Downline Banners legit?', 'Who holds the money?'], tags: ['safe', 'legit', 'pyramid', 'contract'], + re: /(pyramid|ponzi|scam|scheme|legit|safe|trust|rug|who holds)/i, + a: 'A spot buys guaranteed banner views and a place in the line. The BannerLine contract on Polygon splits each $5 in the same transaction with fixed shares, no setters and no owner withdraw; it holds nothing except the momentum fund. From the line alone, a member who refers nobody gets back less than the $5 a spot costs. Check every sale at ' + URL_ + '/ledger and the contract at ' + URL_ + '/contract. This is advertising with a share of later sales, not an investment.' }, + { id: 'promote', title: 'Promote Downline Banners', q: ['Is there a promo kit?', 'Where are the banners to promote DLB?'], tags: ['promote', 'kit', 'banners'], + re: /(promo|promote|creatives?|kit|swipes?|my link|referral link)/i, + a: 'The promo kit at ' + URL_ + '/promote has your referral links, creatives in the common sizes and copy. When someone you referred buys a spot, you receive $1.50 in POL in that transaction.' } +]; + +const FAQ = [ + { id: 'f-network', title: 'Downline Banners and the other network sites', source: 'faq', tags: ['network', 'one account', 'sponsor'], + questions: ['Is Downline Banners part of InstantAdPay?', 'Who is my sponsor here?', 'Which network sites are there?'], + answer: 'Downline Banners 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. Your sponsor here is your network sponsor. Open board slots show network sites such as InstantAdPay and LinkSpin. Ad credits buy advertising, not income.' }, + { id: 'f-nas', title: 'Network Ad Space finishes a spot', source: 'faq', tags: ['network ad space', 'nas', '30 days', 'delivery'], + questions: ['What if my spot does not get 300 views?', 'What is Network Ad Space?'], + answer: 'A spot that is past ' + C.spotDays + ' days with fewer than ' + C.viewsOwed + ' views gets its banner placed in Network Ad Space, a network ad site, for exactly the views still owed. What Network Ad Space serves counts toward the spot\'s ' + C.viewsOwed + '.' } +]; + +const FACTS = () => [ + '- WHAT IT IS: Downline Banners (' + URL_ + ') is one global line of 468x60 banner spots on the BannerLine contract (Polygon). A spot = $5 in POL at the Chainlink price, one payment = ' + C.viewsOwed + ' guaranteed board views for the image and link within ' + C.spotDays + ' days (newest on top, ' + C.boardSlots + ' board slots) + the next place in the line. Not done after ' + C.spotDays + ' days: Network Ad Space finishes the views owed.', + '- SPLIT (contract constants, no setters, no owner withdraw): 30% ($1.50) to the buyer\'s sponsor (none: the momentum fund); 55% = $0.275 to each owner of the 10 spots bought just before; 10% company; 5% momentum fund. Same transaction. A failed send goes to the fund. The contract holds nothing except the fund. From the line alone, a member who refers nobody gets back less than $5 per spot. Never estimate totals.', + '- MOMENTUM FUND: only buys spots. No sale for ' + C.keeperStallHours + ' hours: it buys one (max ' + C.keeperMaxPerDay + ' a day), gifted to an active member who owns a paid spot and had no gift in 7 days, recent referrers first; nobody qualifies: the fund keeps the spot and its line money returns to the fund.', + '- JOIN FLOW: "Look around first" on the home page (sponsor\'s spot, the board, the 3 newest spots, each a short timer), then Join unlocks. /join: connect a wallet and buy, or "Buy a spot for someone else" (they own it). My Spots (/my): one free signature, add a 468x60 image (150 KB max) and link per spot.', + '- REFUEL SPOTS: a counted Monthly Refuel of $50+ on InstantAdPay or LinkSpin earns one spot, bought for the member under their network sponsor, paid by the company.', + '- BOARD: open slots show members\' LinkSpin Banner Spins, then network house ads (InstantAdPay, LinkSpin, network games). Pages: /, /board, /how, /join, /my, /promote, /ledger, /contract, /terms, /disclaimer, /privacy.', + '- 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). This is advertising with a share of later sales, not an investment. Nothing is promised.' +].join('\n'); + +const SITE = { + id: 'bannerline', hubSite: 'bannerline', netId: 'dlb', name: 'Downline Banners', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE, + dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, + intro: 'You are the assistant on Downline Banners (' + URL_ + '), one global line of $5 banner spots: each spot buys 300 guaranteed board views and a place in the line, and the BannerLine contract pays the 10 spots before each sale and the buyer\'s sponsor in the same transaction.', + quickTopics: ['How does it work?', 'Where does the $5 go?', 'What is the momentum fund?', 'What is Viral Banner Blitz?'] +}; + +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/assets/chat.css b/public/assets/chat.css new file mode 100644 index 0000000..c4166b3 --- /dev/null +++ b/public/assets/chat.css @@ -0,0 +1,38 @@ +/* Site assistant widget, Downline Banners look (site.css): ultraviolet night with lime. Near-black glass panel, violet hairlines, + lime accents and send button, Bricolage Grotesque headings, JetBrains Mono labels. Fallbacks match site.css. */ +#scChat{--sc-bg:var(--panel-solid,#14111f);--sc-bg2:var(--ground2,#0e0c18);--sc-ink:var(--ink,#f3f1fa);--sc-sub:var(--muted,#a29cbc);--sc-line:var(--line-strong,rgba(150,135,230,.32)); + --sc-lime:var(--mint,#c6f432);--sc-lime-hi:var(--mint-hi,#dcff6e);--sc-lime-ink:var(--mint-ink,#141a02);--sc-violet:var(--violet,#9b7bff);--sc-cyan:var(--cyan,#6fd8ff); + --sc-disp:var(--disp,"Bricolage Grotesque","Inter","Segoe UI",system-ui,sans-serif);--sc-mono:var(--mono,"JetBrains Mono","Consolas",monospace); + position:fixed;right:18px;bottom:18px;z-index:80;font-family:Inter,"Segoe UI",system-ui,sans-serif} +#scBtn{width:58px;height:58px;border-radius:50%;border:1px solid var(--sc-lime);cursor:pointer;background:var(--sc-lime);color:var(--sc-lime-ink);display:flex;align-items:center;justify-content:center; + box-shadow:0 0 0 6px rgba(198,244,50,.12),0 10px 28px rgba(0,0,0,.55)} +#scBtn:hover{background:var(--sc-lime-hi)} +#scBtn:focus-visible{outline:2px solid var(--sc-cyan);outline-offset:4px} +#scChat.open #scBtn{background:var(--sc-bg);color:var(--sc-lime)} +#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:1px solid var(--sc-line);border-radius:18px;box-shadow:0 24px 60px rgba(0,0,0,.6),0 0 0 1px rgba(155,123,255,.08);overflow:hidden} +.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:linear-gradient(135deg,rgba(155,123,255,.22),rgba(14,12,24,0) 70%),var(--sc-bg2);border-bottom:1px solid var(--sc-line)} +.sc-head>div{flex:1;min-width:0} +.sc-title{display:block;font-family:var(--sc-disp);font-weight:800;font-size:19px;letter-spacing:-.015em} +.sc-sub{display:block;font:500 11.5px var(--sc-mono);color:var(--sc-sub);margin-top:2px} +#scClose{background:transparent;border:0;color:var(--sc-sub);font-size:26px;line-height:1;cursor:pointer;padding:0 2px} +#scClose:hover{color:var(--sc-ink)} +.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:9px} +.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;border-radius:14px;overflow-wrap:anywhere} +.sc-m.bot{align-self:flex-start;background:rgba(150,135,230,.12);border:1px solid var(--sc-line);color:var(--sc-ink);border-bottom-left-radius:4px} +.sc-m.me{align-self:flex-end;background:var(--sc-lime);color:var(--sc-lime-ink);font-weight:600;border-bottom-right-radius:4px} +.sc-m a{color:var(--sc-cyan);text-decoration:underline} +.sc-m.me a{color:inherit} +.sc-m.wait{opacity:.6} +.sc-cta{display:inline-block;background:var(--sc-lime);color:var(--sc-lime-ink)!important;text-decoration:none!important;font-weight:700;padding:8px 14px;border-radius:999px;font-family:var(--sc-disp)} +.sc-handoff{background:transparent!important;border:0!important;padding:0!important} +.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px} +.sc-topics button{background:transparent;color:var(--sc-lime);border:1px solid rgba(198,244,50,.4);border-radius:999px;font:500 12px var(--sc-mono);padding:5px 10px;cursor:pointer} +.sc-topics button:hover{background:rgba(198,244,50,.1)} +.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line)} +.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);border-radius:999px;padding:10px 14px;font:15px Inter,"Segoe UI",system-ui,sans-serif;color:var(--sc-ink);background:var(--sc-bg2)} +.sc-input input::placeholder{color:var(--sc-sub)} +.sc-input input:focus{outline:2px solid var(--sc-violet);outline-offset:-1px} +.sc-input button{background:var(--sc-lime);color:var(--sc-lime-ink);border:0;border-radius:999px;font:700 14px var(--sc-disp);padding:0 18px;cursor:pointer} +.sc-human{display:block;text-align:center;font:500 11.5px var(--sc-mono);color:var(--sc-sub);padding:0 0 10px} +@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..26b7b0e --- /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=20261115d'; 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/board.html b/public/board.html index bc7a3be..1553f22 100644 --- a/public/board.html +++ b/public/board.html @@ -33,5 +33,6 @@ + diff --git a/public/contract.html b/public/contract.html index 5644eb9..f7453ce 100644 --- a/public/contract.html +++ b/public/contract.html @@ -37,5 +37,6 @@ + diff --git a/public/disclaimer.html b/public/disclaimer.html index 3595156..e0662ae 100644 --- a/public/disclaimer.html +++ b/public/disclaimer.html @@ -35,5 +35,6 @@ + diff --git a/public/how.html b/public/how.html index e534b16..e5a60cd 100644 --- a/public/how.html +++ b/public/how.html @@ -42,5 +42,6 @@ + diff --git a/public/index.html b/public/index.html index 90eb3cc..0c0b630 100644 --- a/public/index.html +++ b/public/index.html @@ -54,5 +54,6 @@ + diff --git a/public/join.html b/public/join.html index 3ea605d..a72cf73 100644 --- a/public/join.html +++ b/public/join.html @@ -51,5 +51,6 @@ + diff --git a/public/ledger.html b/public/ledger.html index 7f0ced3..9feee90 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -32,5 +32,6 @@ + diff --git a/public/my.html b/public/my.html index 04b9b92..a279cb9 100644 --- a/public/my.html +++ b/public/my.html @@ -44,5 +44,6 @@ + diff --git a/public/privacy.html b/public/privacy.html index 320b1bc..ecfcc1d 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -36,5 +36,6 @@ + diff --git a/public/promote.html b/public/promote.html index e14c2d6..9036922 100644 --- a/public/promote.html +++ b/public/promote.html @@ -36,5 +36,6 @@ + diff --git a/public/terms.html b/public/terms.html index e8c638e..0e3d8a0 100644 --- a/public/terms.html +++ b/public/terms.html @@ -41,5 +41,6 @@ + diff --git a/qa/chat-qa.json b/qa/chat-qa.json new file mode 100644 index 0000000..a297812 --- /dev/null +++ b/qa/chat-qa.json @@ -0,0 +1,22 @@ +{ + "site": "bannerline", + "home": [ + { "q": "What is Downline Banners?", "kb": "about", "must": ["468x60", "300 guaranteed views", "Nothing is promised"] }, + { "q": "How much is a spot and what does it buy?", "kb": "spot", "must": ["\\$5", "300", "30 days"] }, + { "q": "Where does the $5 go?", "kb": "split", "must": ["30%", "55%", "\\$0.275", "10%", "5%"] }, + { "q": "What do I get when someone I referred buys?", "kb": "split", "must": ["\\$1.50"] }, + { "q": "What size is the banner?", "kb": "banner", "must": ["468x60", "150 KB"] }, + { "q": "What is the momentum fund?", "kb": "fund", "must": ["4 hours", "7 days"] }, + { "q": "Why is Join locked?", "kb": "tour", "must": ["timer"] }, + { "q": "Can I buy a spot for someone else?", "kb": "buy-for", "must": ["wallet address"] }, + { "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", "less than the \\$5"] } + ], + "cross": [ + { "q": "How does Viral Banner Blitz work?", "site": "vbb" }, + { "q": "What is a ViralAdBlitz Boost?", "site": "viraladblitz" }, + { "q": "What does DownlineHydra Pro cost?", "site": "downlinehydra" }, + { "q": "What is a LinkSpin spin link?", "site": "linkspin" }, + { "q": "How does the 5xYourTeam draft work?", "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 de0bbfc..dd6a783 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -115,7 +115,7 @@ async function main() { fs.writeFileSync(path.join(DATA, 'house.json'), JSON.stringify([{ key: 'one', title: 'Test house 1', img: '/art/house-iap.svg', link: 'https://example.com/' }, { key: 'two', title: 'Test house 2', img: '/art/house-linkspin.svg', link: 'https://example.net/' }])); const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA, DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development', - HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member', + HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', NETKB: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member', TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT }); startStandIns(); const hid = n => 'h_' + String(n).padStart(16, '0'); @@ -132,6 +132,13 @@ async function main() { ok(st.totals && st.totals.members === 6, 'index parsed 6 MemberJoined (payer of a buyFor is not a member)', st.totals); ok(BigInt(st.totals.paidInWei) === 7n * q, 'paid in = 7 x quote (refunds excluded)', st.totals.paidInWei); const cfg = await u.json('/api/config'); ok(cfg.ready && cfg.sel.buy === '0xf088d547', '/api/config has contract + selectors'); + // 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 u.req('/')).text(); + ok(/