diff --git a/chatbot.js b/chatbot.js index 18741ea..fb47d58 100644 --- a/chatbot.js +++ b/chatbot.js @@ -7,18 +7,27 @@ // // HOUSE RULE: whenever a site feature changes, update BOTH the CANNED answers and FACTS below in the same commit. // Plain words, no em dashes, never a promise of income. +// +// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is the one +// source the assistant answers from. Each CANNED regex becomes its entry's instant-answer pattern (same order, +// first match wins), and for everything else the best-matching entries go into the system prompt. Admin > +// Knowledge base edits entries; an edited entry is no longer refreshed from the code. If the KB store fails, +// the in-code CANNED list still answers. const { SITE_HOST, SITE_URL } = require('./host'); const fs = require('fs'); const path = require('path'); const https = require('https'); +const http = require('http'); +const kb = require('./kb'); +const kbSeed = require('./kb-seed'); let DATA_DIR = null; let chain = null; const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro'; const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b'; -const KNOWLEDGE_DATE = '2026-10-18'; // the day the CANNED answers and FACTS below were last checked against the site +const KNOWLEDGE_DATE = '2026-10-20'; // the day the CANNED answers and FACTS below were last checked against the site -function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; } +function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); } function key() { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } @@ -29,70 +38,106 @@ function enabled() { return !!key(); } // handoff: true makes the widget offer "Send this to support" under the answer (help desk, 2026-10-16) const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at linkspin|someone|a (human|person|real person))|support (email|address|ticket|team|desk|page)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const CANNED = [ - { re: SUPPORT_RE, handoff: true, + { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a ticket?'], tags: ['support', 'help', 'ticket', 'contact'], + re: SUPPORT_RE, handoff: true, a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' }, - { re: /\b(fix|change|edit|update|correct|replace|wrong|broken|typo)\b.{0,40}\b(link|url|image|banner|picture|headline|text|name)\b.{0,30}\b(ad|ads|campaign|campaigns|banner)\b|\b(edit|fix|change|update) (my |an |the |this )?(ad|ads|campaign|banner|login ad|text ad)\b/i, + { id: 'edit-ad', title: 'Edit an ad: link, image or text', q: ['How do I change the link on my ad?', 'Can I fix a typo in my ad?', 'How do I replace my banner image?'], tags: ['ads', 'edit', 'banner', 'campaign'], + re: /\b(fix|change|edit|update|correct|replace|wrong|broken|typo)\b.{0,40}\b(link|url|image|banner|picture|headline|text|name)\b.{0,30}\b(ad|ads|campaign|campaigns|banner)\b|\b(edit|fix|change|update) (my |an |the |this )?(ad|ads|campaign|banner|login ad|text ad)\b/i, a: 'Open Ads in your Control Room (' + SITE_URL + '/ads) and press Edit on the ad. You can change where the click goes, the banner image (upload a new one or paste a link), the headline and line of a text ad, and the ad name. A login ad shows your page itself, so its link is the whole ad. The first edit of every ad is free, your one correction; each edit after that costs a small credit fee (100 credits at the moment, shown before you save), taken from earned credits first. The type, size, budget, countries, schedule and audience stay as they are; for those, start a new ad. A new link is checked the same way as a new ad, so it has to load and, for banner and text ads, allow framing.' }, - { re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i, + { id: 'login-ads', title: 'Login ad slots', q: ['How do login ads work?', 'How do I book a login ad?'], tags: ['login ad', 'slot', 'purchased credits'], + re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i, a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 3 member slots run at once because they share the same sign-ins, first come first served; when all 3 are taken the Ads screen says so and a place opens when a running slot ends its 30 days. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy one from Ads, New ad, Login ad.' }, - { re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i, + { id: 'vs-iap', title: 'LinkSpin and InstantAdPay: the difference', q: ['What is the difference between LinkSpin and InstantAdPay?', 'Is this the same as InstantAdPay?', 'Why another site?'], tags: ['instantadpay', 'iap', 'sister site', 'network'], + re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i, a: 'InstantAdPay is the ad marketplace: you buy ad packages there, earn credits by viewing ads, and get paid when your line buys. LinkSpin is the tool side of the same network: a link rotator, a page builder and ad zones for your own sites, free with an email address. Its packages buy ad delivery across the LinkSpin viewer, every member zone and the partner network, and they pay your sponsor line the same way, inside the purchase transaction. Same people above and below you, same wallet, and your InstantAdPay username and profile carry over when you sign in with the same email.' }, - { re: /(pyramid|ponzi|scam|scheme|mlm|legit)/i, + { id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is LinkSpin legit?', 'Is this an MLM?'], tags: ['pyramid', 'scam', 'legit', 'mlm'], + re: /(pyramid|ponzi|scam|scheme|mlm|legit)/i, a: 'Fair question. A pyramid pays for recruiting with no product. LinkSpin sells advertising: an ad package buys real ad delivery (banner, text and login ads across the ad viewer, every member zone and the partner network), and the free tools, spin links, pages and zones, work with no purchase at all. The referral split is a fixed rule in a verified contract on Polygon, 50 percent to the direct sponsor, 20 to level 2, 10 to level 3 and 10 plus 10 to two admin wallets, paid in the same transaction as the purchase. Nobody is paid for recruiting without a sale, nothing is held, and no income is promised. Read the code and every payout yourself at ' + SITE_URL + '/contract and ' + SITE_URL + '/ledger.' }, - { re: /(withdraw|cash ?out|payout request|minimum payout|pending (payment|payout|commission))/i, + { id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'Where is my pending payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'], + re: /(withdraw|cash ?out|payout request|minimum payout|pending (payment|payout|commission))/i, a: 'There are no withdrawals here, ever. When someone in your line buys a package, the contract pays your share straight to your own wallet in the same transaction as the purchase, so there is nothing to request and nothing pending. Credits are the other thing you can have, and they never cash out: they only buy ad delivery.' }, - { re: /(how (do|does) (the )?payouts? work|how (much|do i|does one|can i) (earn|get paid|make)|commission|percent(age)?|the split|split (the|a) (package|purchase)|who gets paid|where does the money go)/i, + { id: 'split', title: 'How payouts work: the split', q: ['How do payouts work?', 'How much do I earn?', 'Where does the money go?'], tags: ['payout', 'split', 'commission', 'levels'], + re: /(how (do|does) (the )?payouts? work|how (much|do i|does one|can i) (earn|get paid|make)|commission|percent(age)?|the split|split (the|a) (package|purchase)|who gets paid|where does the money go)/i, a: 'Every package splits the same way, in the same Polygon transaction it sells in: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, and 10 plus 10 percent to the two admin wallets. Level 1 pays you from your referral\'s very first qualifying purchase once your payouts are switched on. Level 2 opens after two of your people buy a qualifying package ($25 or larger; the $10 door does not count), level 3 after five. A level with no qualified member passes up the line to the next qualified person, then to the platform; nothing waits in a balance. Those numbers are constants in the verified contract at ' + SITE_URL + '/contract. No income is promised: nobody earns unless real ad buying happens in their line.' }, - { re: /(free member|free account|for free|without (a )?(wallet|buying|purchase)|do i (have|need) to (buy|pay|purchase)|what do (i|free members|members) get|what is free|is it free|costs? nothing)/i, + { id: 'free-account', title: 'What a free account gets', q: ['What do free members get?', 'Is it free?', 'Do I have to buy anything?'], tags: ['free account', 'tools', 'credits'], + re: /(free member|free account|for free|without (a )?(wallet|buying|purchase)|do i (have|need) to (buy|pay|purchase)|what do (i|free members|members) get|what is free|is it free|costs? nothing)/i, a: 'A free account gets the whole toolset: spin links (one short link that rotates every page you promote, with weights, a fallback and a report by source), the page builder (bridge, review and squeeze pages from a scan of any offer, leads to your own list), zones (an ad slot on your own site that pays ad credits per viewable impression), audiences (first-party retargeting), reports, promo tools and the blog. Free members earn ad credits by running zones, viewing the daily ad set, watching videos, making verified visits and signing in daily. Credits buy your own banner and text ads at one cent each and never cash out. POL, the real crypto, only ever reaches a wallet through the contract split when a package sells in your line, and you can switch payouts on without buying anything.' }, - { re: /(qualif|unlock level|open level|level ?2|level ?3|pass.?up|two buyers|five buyers)/i, + { id: 'qualification', title: 'Qualification: levels 2 and 3', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up'], + re: /(qualif|unlock level|open level|level ?2|level ?3|pass.?up|two buyers|five buyers)/i, a: 'Level 1, half of every package your direct referrals buy, pays from their first qualifying purchase once your payouts are on. Level 2 (20 percent) opens after two of your people buy a qualifying package, $25 or larger. Level 3 (10 percent) opens after five. The $10 door package is for trying the ads and does not count toward opening levels. Until a level opens, its share passes up the line to the next qualified member, then to the platform, and it never comes back, so leaders qualify before their teams\' teams buy. Qualification is counted by the contract, never expires and cannot be bought.' }, - { re: /(what('s| is) (a |an )?(ad )?zone|zones?\b|embed|script tag|publisher|site owner|my (own )?(web)?site|ad slot|viewable)/i, + { id: 'zones', title: 'Ad zones on your own site', q: ['What is an ad zone?', 'How do I put ads on my website?', 'What sizes are the zones?'], tags: ['zones', 'publisher', 'embed', 'website'], + re: /(what('s| is) (a |an )?(ad )?zone|zones?\b|embed|script tag|publisher|site owner|my (own )?(web)?site|ad slot|viewable)/i, a: 'A zone is an ad slot on your own site: one script tag, nine standard sizes (728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50). Each load shows a LinkSpin member campaign first, then a network ad, then our house banner if nothing paid fits. You earn ad credits per viewable impression (half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day): 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, or 1 per 8 on a Verified zone the admin has reviewed. A new zone earns after its first 100 on-site views with at least 40 percent viewable, and paid ads serve only on the site you declared, so copying the tag elsewhere earns nothing. Everything is explained at ' + SITE_URL + '/publishers and you add zones under Zones in your Control Room.' }, - { re: /(traffic ?sources?|postback|macros?|propeller ?ads|zeropark|adsterra|exoclick|hilltop ?ads|rich ?ads|traffic ?stars|pop ?ads|campaign url|buy(ing)? traffic|paid traffic|ad network|s2s|conversion (pixel|tracking))/i, + { id: 'sources', title: 'Traffic sources and postbacks', q: ['How do I track traffic I buy?', 'How do postbacks work?', 'Can I use PropellerAds or Zeropark?'], tags: ['sources', 'postback', 'paid traffic', 'ad network'], + re: /(traffic ?sources?|postback|macros?|propeller ?ads|zeropark|adsterra|exoclick|hilltop ?ads|rich ?ads|traffic ?stars|pop ?ads|campaign url|buy(ing)? traffic|paid traffic|ad network|s2s|conversion (pixel|tracking))/i, a: 'Sources, in your Control Room, is for traffic you buy on networks like PropellerAds, Zeropark, Adsterra or ExoClick. Pick the network from the catalog (or define your own), fill in your account details, and the source remembers that network\'s macros and conversion postback. Point a spin link at it and the Share kit gives you the exact campaign URL to paste into the network, macros included. When a click from that source joins, leaves a lead, links a wallet or buys, LinkSpin fires the network\'s own postback with its click id, so the network learns what converts, and Reports breaks clicks and conversions down by source and by the zone or placement the macro carried. The older account-level Postbacks on the Links screen still work for your tracker.' }, - { re: /(spin ?link|rotat|short link|one link|weights?|fallback|split test|sub ?id|click ?id|daypart|health check|dead link|redirect)/i, + { id: 'spin-links', title: 'Spin links (the rotator)', q: ['What is a spin link?', 'How do weights and the fallback work?', 'How do I rotate my links?'], tags: ['spin link', 'rotator', 'short link', 'weights'], + re: /(spin ?link|rotat|short link|one link|weights?|fallback|split test|sub ?id|click ?id|daypart|health check|dead link|redirect)/i, a: 'A spin link is one short link that rotates between every page you promote. Behind it you set destinations with weights, pause any of them, and name a fallback for when everything else is off. Every click is recorded in one hop with the day, country, source and device, bots are filtered on the server, and click ids and sub ids (clickid, subid, s1 to s4 and the usual tracker names) ride through to the destination, so you can split-test by tagging the same link with different sub ids. Reports show it per link and across all of them. Set the hours of the day and week a spin or a destination runs (the local time of your visitor by default), and automatic health checks pause a dead or parked destination for you. You can try a spin with no account on the home page.' }, - { re: /(page builder|bridge page|squeeze page|review page|sales page|advertorial|press release|landing page|build (a|me a) page|my pages?|lead capture|leads?\b)/i, + { id: 'pages', title: 'The page builder', q: ['How do I build a bridge page?', 'Can I make a squeeze page?', 'Where do my leads go?'], tags: ['pages', 'page builder', 'bridge page', 'leads'], + re: /(page builder|bridge page|squeeze page|review page|sales page|advertorial|press release|landing page|build (a|me a) page|my pages?|lead capture|leads?\b)/i, a: 'Pages is the built-in page builder. Paste the address of any offer you promote, LinkSpin scans its headline and points, you add your angle, and you get a bridge, review or squeeze page with your own leads list (CSV or webhook), published on LinkSpin\'s pages domain, lookfirst.page. Pick a design, palette and layout, or a niche preset that sets them for you with a matching hero image. Put the page behind a spin link to send traffic by weight. Sales, advertorial and press-release layouts are on the way. Open Pages in your Control Room; it is free.' }, - { re: /(audience|retarget|pixel|p\.js|my visitors|show only to|never show to)/i, + { id: 'audiences', title: 'Audiences and retargeting', q: ['How does retargeting work?', 'What is the pixel?', 'Can I show ads only to my visitors?'], tags: ['audiences', 'retargeting', 'pixel'], + re: /(audience|retarget|pixel|p\.js|my visitors|show only to|never show to)/i, a: 'Audiences is first-party retargeting. Everyone who views your LinkSpin pages or your zones lands in "My visitors" for 30 days with no setup, and for any other site you control you paste a small pixel tag (/p.js). Then, on any banner or text campaign, choose "show only to" or "never show to" an audience. The match uses a LinkSpin cookie with a 24-hour fallback where browsers block cross-site cookies, and nothing personal is stored. It lives on the Zones screen.' }, - { re: /(promo tools?|social posts?|email swipes?|banners? (kit|set)|text a friend|objection|hook videos?|angle (link|video|page)|share buttons?)/i, + { id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners'], + re: /(promo tools?|social posts?|email swipes?|banners? (kit|set)|text a friend|objection|hook videos?|angle (link|video|page)|share buttons?)/i, a: 'Promo tools (' + SITE_URL + '/tools#promo) holds everything personalised with your invite link: social posts, text-a-friend messages, email swipes, banners in the standard sizes, an objection-handling bank with honest replies, and the hook videos. There are five hook angles, each with its own join page and video: links (stop juggling links), pages (a bridge page in a minute), zones (your site pays you), audiences (reach your visitors again) and stack (the three tools, free). An angle link is your normal link with ?v= on the end, so every join and purchase still credits you.' }, - { re: /\bblog\b|articles?|read more/i, + { id: 'blog', title: 'The blog', q: ['Is there a blog?', 'Where are the articles?'], tags: ['blog', 'articles'], + re: /\bblog\b|articles?|read more/i, a: 'The blog at ' + SITE_URL + '/blog has Marty\'s articles on building a line, advertising that pays and daily habits. Each article has its own page you can share, and there is an RSS feed at /blog/feed.xml.' }, - { re: /(price|cost|packages?|how much is|ladder|\$10|\$25|\$50|\$100|\$250|\$500|door package)/i, + { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'What does the $10 door package do?', 'Which package should I buy?'], tags: ['packages', 'price', 'credits', 'qualification'], + re: /(price|cost|packages?|how much is|ladder|\$10|\$25|\$50|\$100|\$250|\$500|door package)/i, a: 'Six packages, priced in dollars and settled in POL at the live rate: the $10 door (1,000 credits, for trying the ads; it does not count toward qualification), $25 Starter (2,500), $50 Builder (5,000), $100 Growth (10,000), $250 Leader (25,000) and $500 Network (50,000). One credit is one cent of ad delivery. Any package of $25 or more makes you a qualifying buyer for your sponsor. Buy under Credits in your Control Room; the live ladder is on the home page.' }, - { re: /(credits?|impression|cpm|what do i get|what am i buying|one cent|1 cent)/i, + { id: 'credits', title: 'What credits are and how you get them', q: ['What is a credit?', 'How do I get credits?', 'What am I buying?'], tags: ['credits', 'ad delivery', 'impressions'], + re: /(credits?|impression|cpm|what do i get|what am i buying|one cent|1 cent)/i, a: 'One credit is one cent of ad delivery: banner, text and login ads shown across the LinkSpin ad viewer, every member zone and the partner network, managed from the Ads screen. Credits come two ways, bought in a package or earned free (zones, the daily ad set, videos, verified visits, daily sign-in). Earned credits spend on banner and text campaigns; a login-ad slot (1,000 purchased credits for 30 days) takes purchased credits only. Credits are advertising, not money: they never cash out and are never converted to crypto.' }, - { re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i, + { id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning'], + re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i, a: 'That red "this transaction will drain your wallet" screen is Trust Wallet\'s own safety rule, not a problem with the purchase: it blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet. SafePal, MetaMask and Phantom have no such block. Extra POL always stays yours. If the next try says WalletConnect disconnected, open the Wallet screen, disconnect, then connect again.' }, - { re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto|metamask|safepal|phantom|coinbase wallet)/i, + { id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'safepal', 'metamask', 'moonpay', 'buy pol'], + re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto|metamask|safepal|phantom|coinbase wallet)/i, a: 'SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first under Settings, Active Networks) and any WalletConnect wallet work too. Trust Wallet works but blocks a purchase that spends most of its POL, so keep about double the package cost there. Never held crypto? Link your wallet, open Credits and tap Buy POL with a card: MoonPay opens with POL on Polygon and your own address filled in, you pay by card, Apple Pay or Google Pay (the first time needs an ID check), the POL lands in your wallet in minutes, then you buy the package. Keep a little extra POL for network fees.' }, - { re: /(need (a )?wallet|crypto experience|how (do i|to) (join|sign ?up|register|sign in)|sign ?up|register|password|sign.?in code|six.?digit)/i, + { id: 'join', title: 'How to join and sign in', q: ['How do I join?', 'Do I need a wallet?', 'Is there a password?'], tags: ['join', 'sign up', 'sign in', 'code'], + re: /(need (a )?wallet|crypto experience|how (do i|to) (join|sign ?up|register|sign in)|sign ?up|register|password|sign.?in code|six.?digit)/i, a: 'Join free with just your email at ' + SITE_URL + '/join. A six-digit code signs you in, there is no password, and no wallet is needed to use the links, pages and zones. The wallet step comes later, inside your Control Room, when you want to be paid or to buy a package.' }, - { re: /(referral link|invite link|share link|join link|my link|refer(ring)? (people|friends|someone))/i, + { id: 'referral-link', title: 'My invite link', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools'], + re: /(referral link|invite link|share link|join link|my link|refer(ring)? (people|friends|someone))/i, a: 'Your invite link is live the moment you sign in, free members included: ' + SITE_HOST + '/join/yourname. Promo tools lists it with the five angle versions (links, pages, zones, audiences, stack), each with a video and Copy and Share buttons; they are the same link with ?v= on the end, so every join and purchase credits you. One tip: switch on payouts (Credits screen, one transaction, no purchase needed) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' }, - { re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit|carr)|carry.?over|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor|same (team|sponsor|upline)|registry)/i, + { id: 'sponsor', title: 'Who is my sponsor; wrong sponsor; carry-over', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Is my InstantAdPay sponsor carried over?'], tags: ['sponsor', 'carry-over', 'registry', 'invite link'], + re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit|carr)|carry.?over|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor|same (team|sponsor|upline)|registry)/i, a: 'The invite link you opened most recently sets your sponsor, and the join page shows who you are joining under. It locks when you create your account, and your first purchase binds you to that sponsor on the contract. Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their sponsor carried over automatically from the network registry when no invite link was used, so the same people are above you here. Already joined under the wrong sponsor by mistake? Message support before your first purchase and the admin can move you.' }, - { re: /(activat|switch(ed)? on payouts|payouts (on|off)|turn on payouts|get paid to my wallet|link (my |a )?wallet)/i, + { id: 'activation', title: 'Switching on payouts', q: ['How do I switch on payouts?', 'How do I link my wallet?', 'How do I activate?'], tags: ['activation', 'payouts', 'link wallet'], + re: /(activat|switch(ed)? on payouts|payouts (on|off)|turn on payouts|get paid to my wallet|link (my |a )?wallet)/i, a: 'Payouts switch on when your wallet is registered on the contract. That happens two ways: buy any package, or use the free activation on the Credits screen, one transaction that costs only network gas. First link the wallet that should receive your payouts (one signature, no transaction), then activate. From then on the contract pays your share of every qualifying purchase in your line straight to that wallet. Buying is never required to be paid at level 1; a $25 or larger package is what makes you a qualifying buyer for your own sponsor and funds your own ads.' }, - { re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|\bpol\b|polygon|matic/i, + { id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Is it MATIC?'], tags: ['pol', 'polygon', 'crypto', 'network'], + re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|\bpol\b|polygon|matic/i, a: 'One coin, one network: POL, the native coin of Polygon. Packages are priced in dollars and settled in POL at the live rate, and every payout arrives as POL in your own Polygon wallet in the same transaction. No other coins, tokens or chains are used. Send POL on the Polygon network, never MATIC on Ethereum.' }, - { re: /(control room|dashboard|where (do|can) i (find|see)|which screen|menu|navigation|more tools|\/tools)/i, + { id: 'control-room', title: 'The Control Room screens', q: ['Where do I find my links?', 'What is on the dashboard?', 'Which screen has my campaigns?'], tags: ['control room', 'dashboard', 'menu', 'tools'], + re: /(control room|dashboard|where (do|can) i (find|see)|which screen|menu|navigation|more tools|\/tools)/i, a: 'Your Control Room has these screens: Links (spin links), Pages (the page builder), Zones (ad slots on your site plus Audiences), Ads (your campaigns and the daily ad set), Credits (buy packages, link your wallet, switch on payouts), Reports (every link in one view), Team (your line, three levels) and Wallet (what was paid to you). More, at ' + SITE_URL + '/tools, holds Promo tools, Training, the Pipeline follow-up board, My line and your Profile.' }, - { re: /(holding tank|adopt|no sponsor|without a sponsor|orphan)/i, + { id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'no sponsor'], + re: /(holding tank|adopt|no sponsor|without a sponsor|orphan)/i, a: 'Members who join from the public site with no sponsor wait in the holding tank under More, My line. A member who has switched on payouts and bought their own qualifying package can adopt one, first come, with a 7-day window for the new member to link a wallet or buy; otherwise they return to the tank. Adopting sets the sponsor, and their first purchase then binds to the adopter on the contract.' }, - { re: /(my line|downline|my team|who (is|are) (in|on) my|three levels|level 1\b)/i, + { id: 'team', title: 'My line: the Team screen', q: ['How do I see my downline?', 'Who is in my team?'], tags: ['team', 'my line', 'downline', 'levels'], + re: /(my line|downline|my team|who (is|are) (in|on) my|three levels|level 1\b)/i, a: 'Team shows your line as a working table, three levels deep: who joined through your link, who has switched on payouts, who has bought, and how many qualifying buyers each person has. The chip count is what opens your levels: two qualifying buyers ($25 or larger) open level 2, five open level 3.' }, - { re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, + { id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?'], tags: ['balance', 'credits', 'campaigns'], + re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, a: 'One rule: your available balance is what is not committed to a live campaign. When you start a campaign its whole budget is set aside right then, so Available drops once and then sits still while the ad runs; the budget spends down inside that campaign on the Ads screen, where you can see delivered views and what is left. A paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live.' }, - { re: /(safe|trust (you|this|the site)|rug|run away|disappear|hold(s|ing)? (my|the) (money|funds))/i, + { id: 'safe', title: 'Is it safe? Who holds the money?', q: ['Is this safe?', 'Can you run away with the money?', 'Who holds the funds?'], tags: ['safe', 'contract', 'custody', 'trust'], + re: /(safe|trust (you|this|the site)|rug|run away|disappear|hold(s|ing)? (my|the) (money|funds))/i, a: 'The money never touches us. A verified, immutable contract on Polygon splits every purchase in the same transaction, holds no balance, and has no pause switch or upgrade path. Credits live on the platform and are advertising, not money. Read the plain-language review and the verified source at ' + SITE_URL + '/contract, and watch every payout land at ' + SITE_URL + '/ledger.' } ]; +// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence) +function seeds() { + return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source, + handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ); +} + // ---- facts for the AI fallback ---- -function systemPrompt() { +function systemPrompt(kbBlock) { return `You are the assistant on LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property. FACTS: @@ -113,29 +158,40 @@ RULES: - 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page. - NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen in their line. - No em dashes. If you do not know, say so and point to ${SITE_URL}/contract or the ledger. -- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.`; +- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at ${SITE_URL}/help, or ${SITE_URL}/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : ''); } -function askAI(message, historyText) { +// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai +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 askAI(message, historyText, kbBlock) { return new Promise((resolve, reject) => { const body = JSON.stringify({ model: MODEL, + reasoning: { enabled: false }, // deepseek-v4-flash thinks by default and can spend the whole max_tokens on it (IAP, 2026-10-16) max_tokens: 300, messages: [ - { role: 'system', content: systemPrompt() }, + { role: 'system', content: systemPrompt(kbBlock) }, ...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []), { role: 'user', content: String(message).slice(0, 600) } ] }); - const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST', + 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) }, timeout: 30000 }, res => { let d = ''; res.on('data', c => d += c); res.on('end', () => { - try { resolve(JSON.parse(d).choices[0].message.content.trim()); } - catch (e) { reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); } + // 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); @@ -148,14 +204,25 @@ const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unabl async function answer(message, historyText) { const msg = String(message || '').trim(); if (!msg) return { error: 'Say something first.' }; - for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + // fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down + let hit = null, kbOk = true; + try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); } + if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {}); + if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + // retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far) + let kbBlock = '', kbIds = []; + try { + const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; + const hits = await kb.context(query, 5); + kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id); + } catch (e) { console.error('kb search', e.message); } if (!enabled()) return { reply: 'Good question. The quick answers I have cover spin links, pages, zones, packages, the payout split, qualification and joining; for anything deeper, the plain-language contract review at ' + SITE_URL + '/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; // handoff: the answer admits it cannot help, so the widget offers "Send this to support" - try { const reply = await askAI(msg, historyText); return Object.assign({ reply }, UNSURE_RE.test(reply) ? { 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); return { reply: 'I hit a snag answering that one. The contract review at ' + SITE_URL + '/contract and the live ledger at ' + SITE_URL + '/ledger cover most deep questions, or tap "Send this to support" and Marty will answer.', handoff: true }; } } -module.exports = { init, answer, enabled, CANNED }; +module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt }; diff --git a/kb-seed.js b/kb-seed.js new file mode 100644 index 0000000..75c92a7 --- /dev/null +++ b/kb-seed.js @@ -0,0 +1,57 @@ +// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the home page's network notes, the +// wallets guide's Common questions, the earning guide, and support replies worth keeping. An entry here +// that nobody has edited in Admin > Knowledge base is refreshed when its text changes in this file; edit +// it in the admin pane and it becomes the admin's own. +// House rules: plain words, no em dashes, never a promise of income. +const { SITE_HOST, SITE_URL } = require('./host'); +const FAQ = [ + { id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket', + questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'], + tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'], + answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. LinkSpin runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open ' + SITE_HOST + ' in SafePal\'s browser (or the browser with the extension), sign in with your email, open Credits in your Control Room and tap Link a wallet (one free signature). You only need a wallet to buy a package or receive payouts.' }, + { id: 'f-team-here', title: 'Already on InstantAdPay? Your team is already here', source: 'faq', + questions: ['I am already on InstantAdPay, do I start over?', 'Will my InstantAdPay sponsor be my sponsor here?', 'Can I sign in with my InstantAdPay email?'], + tags: ['instantadpay', 'sponsor', 'carry-over', 'team', 'network'], + answer: 'Sign in with the email you use on InstantAdPay and your sponsor is placed for you before you buy anything: the same people above you, the same people below you, the same wallet. LinkSpin is a second property to build on, with tools you will use every day.' }, + { id: 'f-new-here', title: 'New here: where to start', source: 'faq', + questions: ['I am new, where do I start?', 'What should I do first?', 'How do I get started?'], + tags: ['getting started', 'new member', 'first steps'], + answer: 'Make a spin link on the home page at ' + SITE_URL + ', promote it anywhere, and watch the clicks in your Control Room. Create your free account at ' + SITE_URL + '/join with just your email. Buy a package when you want your own ads in front of the network. Email first, wallet only when you are ready to be paid.' }, + { id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq', + questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'], + tags: ['pol', 'fees', 'gas', 'buy packages'], + answer: 'The Credits screen shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' }, + { id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq', + questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'], + tags: ['moonpay', 'card', 'declined', 'buy pol'], + answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check (minimum order usually around $30).' }, + { id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq', + questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'], + tags: ['wallet', 'position', 'qualified start', 'metamask'], + answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them as positions under your main wallet. The Qualified Start videos in Training walk through it.' }, + { id: 'f-payouts-where', title: 'Where do my payouts go?', source: 'faq', + questions: ['Where do my payouts go?', 'Which wallet gets paid?', 'Does the site hold my earnings?'], + tags: ['payout', 'wallet', 'custody'], + answer: 'To the wallet address you switched payouts on with, in the same transaction as the purchase that earned them. Nothing is held on the site. The Wallet screen in your Control Room shows what was paid to that wallet.' }, + { id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq', + questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'], + tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'], + answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' }, + { id: 'f-claim-streak', title: 'The daily set and the claim streak', source: 'faq', + questions: ['How does the daily claim streak work?', 'How much does the daily claim pay?', 'When does the daily ad set reset?'], + tags: ['daily set', 'claim streak', 'earn credits', 'reset'], + answer: 'Earn credits > Watch ads gives five ads a day: each opens full screen, a 10-second countdown runs, you pass a quick click-the-icon check and earn 1 credit. Finish all five and Claim appears. The claim pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th day in a row; miss a day and it restarts. Days are counted in UTC, so the set resets at 7 PM Central (6 PM in winter time). Credits are ad delivery, never money.' }, + { id: 'f-visits-videos', title: 'Verified visits, videos and inbox ads', source: 'faq', + questions: ['How do verified visits pay?', 'How many videos can I watch a day?', 'How do inbox solo ads pay?'], + tags: ['verified visits', 'videos', 'inbox', 'earn credits'], + answer: 'After the daily set is claimed you can make up to 20 verified visits a day, 1 credit each: open a member\'s site in a new tab and stay for the dwell; each is a different site. Videos credit only when they play to the end, up to 6 a day, paying by length. Inbox solo ads: open the message, visit the advertiser\'s link, then claim 2 credits, once per message. Signing in also pays 5 credits a day, rising by one per day in a row up to 10.' }, + { id: 'f-spend-credits', title: 'What to do with earned credits', source: 'faq', + questions: ['What do I do with my credits?', 'How do I spend my credits?', 'My credits are just sitting there'], + tags: ['credits', 'campaign', 'spend'], + answer: 'Credits sitting in your balance do nothing. Open Ads in your Control Room, start a new banner or text campaign, give it a budget in credits and point it at your own invite link or wall. Banner and text ads also push out to the partner network. A campaign reserves its whole budget the moment it starts, and login ads are the one format that needs purchased credits.' }, + { id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq', + questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'], + tags: ['recovery phrase', 'private key', 'scam', 'security'], + answer: 'Never share your recovery phrase (the 12 or 24 words) or private key with anyone: whoever has them has your money. Nobody from LinkSpin will ever ask for them, and the site never sees them. If someone does ask, do not reply, and tell support through Help at ' + SITE_URL + '/help.' } +]; +module.exports = { FAQ }; diff --git a/kb.js b/kb.js new file mode 100644 index 0000000..08726d2 --- /dev/null +++ b/kb.js @@ -0,0 +1,245 @@ +// 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: one JSON file on the volume, DATA_DIR/kb.json (written to a temp file and renamed). Ported from +// InstantAdPay's kb.js, which also has a MySQL store; keep the scoring and seed rules of the two in step. +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { SITE_URL } = require('./host'); + +let DATA_DIR = null, SEEDS = [], ready = null; +let cache = null, cacheAt = 0, index = null; +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 }; +} +function rank(idx, query, k) { + if (!idx || !idx.n) return []; + const qt = [...new Set(terms(query))]; + if (!qt.length) return []; + 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) 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 J = { + file: () => path.join(DATA_DIR, 'kb.json'), + async ensure() {}, + async all() { 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); + 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'); +} + +function init(opts) { + DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null; + ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); }); + return ready; +} +async function load(force) { + if (ready) await ready; + if (!force && cache && Date.now() - cacheAt < TTL) return cache; + const all = await store().all(); + cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear(); + 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 || 5)); } +const HELP = 'Help (' + SITE_URL + '/help, or ' + SITE_URL + '/support when signed out)'; +function promptBlock(hits) { + const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.'; + if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.'; + return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. ' + + 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n' + + hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n'); +} + +// ---------------------------------------------------------------- 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).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); + 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); + 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); + 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, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) }; +} + +module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test, + _pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } }; diff --git a/public/admin.html b/public/admin.html index 7042b57..5da21a6 100644 --- a/public/admin.html +++ b/public/admin.html @@ -50,6 +50,7 @@ + @@ -349,6 +350,26 @@ +
+ + + +
+Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. Entries from the code follow chatbot.js and kb-seed.js until you edit them. LinkSpin tickets are answered on the InstantAdPay support desk: when a reply there is worth keeping for LinkSpin members, add it here with + New entry.
+