From 1e040f21ff8c94d824575f4a5291f6701e31f323 Mon Sep 17 00:00:00 2001 From: martbost Date: Tue, 20 Oct 2026 05:37:09 -0500 Subject: [PATCH 1/2] Chat knowledge base: the assistant answers from maintained entries, and support replies become entries - kb.js: entries { id, title, questions, answer, tags, pattern, handoff, order, source, updated } in MySQL table kb_entries (created on boot) or DATA_DIR/kb.json without DATABASE_URL. BM25 over title, question variants and tags (answer at a low weight) with word bigrams; the top hits (within 30% of the best, score 3+) go into the system prompt as KNOWLEDGE BASE, and when nothing fits the prompt says to answer "I'm not sure, ask support". - One source: chatbot.js CANNED seeds the KB (ids c-*, its regex becomes the entry's instant-answer pattern, same first-match order), kb-seed.js seeds the home FAQ, Platform Facts, wallets FAQ and the Coinbase support reply (f-*). The fast path now serves the KB entry, so an admin edit changes the instant answer; the in-code CANNED only answers if the KB store fails. Unedited seeds follow code changes, edited ones are left alone, deleted seeds stay deleted. - Admin > Knowledge base: list, search, filter by source, add, edit, delete, and Try a question (instant answer or what the AI is given). Support tickets: "Save as KB entry" under each sent reply opens a draft with the member's question and the reply (greeting and sign-off trimmed). Em dashes in admin input become commas. - chatbot.js: OPENROUTER_URL override for tests; solo-ads answer em dash removed; KNOWLEDGE_DATE 2026-10-20. - qa/chatbot-sync.mjs: takes the later of KNOWLEDGE_DATE and /api/chat/kb-stamp (newest KB edit by a person, Central day; seed refreshes do not count). - QA: qa/kb-retrieval.cjs (13 sample questions rank the right entry first, off-topic returns nothing), qa/kb-chat.mjs (local copy + mock OpenRouter: Coinbase answered from the KB, fast path without an AI call, admin CRUD, restart keeps edits), bash qa/run.sh kb; walk covers admin#kb and Save as KB entry. Co-Authored-By: Claude Opus 5.5 --- chatbot.js | 188 +++++++++++++++++-------- kb-seed.js | 72 ++++++++++ kb.js | 280 ++++++++++++++++++++++++++++++++++++++ public/admin.html | 25 +++- public/assets/admin-kb.js | 108 +++++++++++++++ public/assets/admin.js | 11 +- qa/chatbot-sync.mjs | 14 +- qa/kb-chat.mjs | 130 ++++++++++++++++++ qa/kb-retrieval.cjs | 49 +++++++ qa/run.sh | 4 + qa/walk.mjs | 16 ++- server.js | 24 ++++ 12 files changed, 858 insertions(+), 63 deletions(-) create mode 100644 kb-seed.js create mode 100644 kb.js create mode 100644 public/assets/admin-kb.js create mode 100644 qa/kb-chat.mjs create mode 100644 qa/kb-retrieval.cjs diff --git a/chatbot.js b/chatbot.js index 59e494b..6f281ca 100644 --- a/chatbot.js +++ b/chatbot.js @@ -4,15 +4,24 @@ // // HOUSE RULE: whenever a site feature changes, update BOTH the CANNED // answers and FACTS below in the same commit. +// +// 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 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'; -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 ''; } @@ -20,58 +29,81 @@ function key() { function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- -const KNOWLEDGE_DATE = '2026-10-18'; // bump whenever the canned answers / prompt are brought up to date +const KNOWLEDGE_DATE = '2026-10-20'; // bump whenever the canned answers / prompt are brought up to date 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 instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|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 support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'], + re: SUPPORT_RE, handoff: true, a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' }, - { re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, + { id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'], + re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the Pass badge. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' }, - { re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, + { id: 'road-agent', title: 'Road Agent (night-highway shooter)', q: ['What is Road Agent?', 'How do fuel stops work in Road Agent?'], tags: ['games', 'road agent', 'fuel stop'], + re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' }, - { re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i, + { id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'], + re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i, a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' }, - { re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i, + { id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'], + re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i, a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' }, - { re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i, + { id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'], + re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i, a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' }, - { re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i, + { id: 'polybreak', title: 'PolyBreak brick breaker', q: ['What is PolyBreak?', 'How do I get another paddle?'], tags: ['games', 'polybreak', 'brick breaker', 'gem'], + re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i, a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' }, - { re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i, + { id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'], + re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i, a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' }, - { re: /(clutter ?hunt|hidden.object|haunted manor)/i, + { id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'], + re: /(clutter ?hunt|hidden.object|haunted manor)/i, a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Haunted Manor (six rooms) through Oct 31, then new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' }, - { re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i, + { id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'], + re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i, a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' }, - { re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i, + { id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do refuels work?'], tags: ['games', 'drip runner', 'refuel', 'games tab'], + re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i, a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' }, - { re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i, + { id: 'gem-kingdom', title: 'Gem Kingdom match-3 and Crowns', q: ['What is Gem Kingdom?', 'How do I buy Crowns?', 'What do the bosses pay?'], tags: ['games', 'gem kingdom', 'crowns', 'match-3'], + re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i, a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' }, - { re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i, + { id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'], + re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i, a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' }, - { re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i, + { id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'], + re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i, a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' }, - { re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i, + { id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'], + re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i, a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' }, // 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being // signed out, and the honest answer reads far better than letting it look like a fault. - { re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i, + { id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'], + re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i, a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' }, - { re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i, + { id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'], + re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i, a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' }, - { re: /(pyramid|ponzi|scam|scheme)/i, + { id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'], + re: /(pyramid|ponzi|scam|scheme)/i, a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' }, - { re: /(withdraw|cash ?out|payout request|minimum payout)/i, + { id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'], + re: /(withdraw|cash ?out|payout request|minimum payout)/i, a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' }, // "how much do I earn" used to fall through to the PRICE answer below, because that one // matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17). - { re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i, + { id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'], + re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i, a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' }, - { re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|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?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'], + re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i, a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; 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. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' }, - { re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i, + { id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'], + re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i, a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' }, - { re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i, + { id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'], + re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i, a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' }, // PIF + the holding tank. Asked together often ("should I pif someone from the tank"), // and the honest answer is that the order matters: you cannot PIF someone still in the @@ -80,54 +112,82 @@ const CANNED = [ // ("should I fund their first package", "can I buy it for them"). It needs BOTH a // paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions // like "which package should I buy" are not stolen (Marty, 2026-09-17). - { re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, + { id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'], + re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' }, - { re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/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', 'unsponsored'], + re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i, a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances.' }, - { re: /(qualif|unlock level|level 2|level 3|pass.?up)/i, + { id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'], + re: /(qualif|unlock level|level 2|level 3|pass.?up)/i, a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' }, - { re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i, + { id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'], + re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i, a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' }, - { re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i, + { id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'], + re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i, a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' }, - { re: /(referral link|invite link|share link|refer)/i, + { id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'], + re: /(referral link|invite link|share link|refer)/i, a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' }, - { re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i, + { id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'], + re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i, a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' }, - { re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i, + { id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'], + re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i, a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' }, - { 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 transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'], + 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 the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet 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 (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' }, - { re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i, + { id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'], + re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i, a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' }, - { re: /(solo ad|inbox ad|inbox)/i, - a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members — give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' }, - { re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i, + { id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'], + re: /(solo ad|inbox ad|inbox)/i, + a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' }, + { id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'], + re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i, a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' }, - { re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i, + { id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'], + re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i, a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' }, - { re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i, + { id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'], + re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i, a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' }, - { re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i, + { id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'], + re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i, a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' }, - { re: /(verified visit|visit pack|buy visits|visits campaign)/i, + { id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'], + re: /(verified visit|visit pack|buy visits|visits campaign)/i, a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' }, - { re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i, + { id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'], + re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i, a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' }, - { re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i, + { id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'], + re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i, a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' }, - { re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i, + { id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'], + re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i, a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' }, - { re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i, + { id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'], + re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i, a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' }, - { 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)/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', 'metamask', 'safepal', 'phantom', '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)/i, a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' }, - { re: /(safe|trust|rug|run away|company disappear)/i, + { id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'], + re: /(safe|trust|rug|run away|company disappear)/i, a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' } ]; +// 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 InstantAdPay (https://instantadpay.com), a membership advertising platform. FACTS: @@ -218,22 +278,27 @@ RULES: - Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes. - 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. - No em dashes. If you do not know, say so and point to /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 https://instantadpay.com/my#help, or https://instantadpay.com/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 https://instantadpay.com/my#help, or https://instantadpay.com/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 }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers) 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 => { @@ -263,13 +328,24 @@ 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 packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; // One retry: the usual failure is a single provider dropping the request, and asking // again almost always lands. Only after both fail do we admit defeat. for (let attempt = 0; attempt < 2; attempt++) { // handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16) - 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 (attempt ' + (attempt + 1) + ')', e.message); if (attempt === 0) await new Promise(r => setTimeout(r, 700)); @@ -279,4 +355,4 @@ async function answer(message, historyText) { return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true }; } -module.exports = { init, answer, enabled, KNOWLEDGE_DATE }; +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..bbe22c3 --- /dev/null +++ b/kb-seed.js @@ -0,0 +1,72 @@ +// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the public FAQ on the home page, +// the Platform Facts page (/facts), the wallets guide's Common questions, 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 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. InstantAdPay 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 instantadpay.com in SafePal\'s browser (or the browser with the extension), sign in with your email and tap Link wallet (one free signature). You only need a wallet to buy a package or receive payouts.' }, + { id: 'f-how-fast', title: 'How fast do I really get paid?', source: 'faq', + questions: ['How fast do I get paid?', 'When does my commission arrive?', 'Is there an approval step for payouts?'], + tags: ['payout', 'speed', 'same transaction', 'ledger'], + answer: 'Payouts happen inside the very transaction that pays for the package. There is no approval step and nobody holding funds. Your share lands in your own wallet the moment your referral\'s purchase confirms, and the public ledger at https://instantadpay.com/ledger lets you watch each one go through.' }, + { id: 'f-what-buying', title: 'What am I actually buying?', source: 'faq', + questions: ['What am I actually buying?', 'What is the product?', 'Do bigger packages give bonus credits?'], + tags: ['product', 'ad delivery', 'credits', 'packages'], + answer: 'You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. The $5 package mints 500 credits, and the bigger packages mint bonus credits on top, up to 70,000 on the $500 package. Earnings only come from referring people who also buy real ad delivery, and the contract splits every purchase automatically. Nothing is a promise of income.' }, + { id: 'f-refunds', title: 'Refunds', source: 'faq', + questions: ['Can I get a refund?', 'Is my purchase refundable?', 'Can a POL payment be reversed or charged back?', 'What happens if my campaign fails to deliver?'], + tags: ['refund', 'chargeback', 'reverse payment', 'final'], + answer: 'Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in your balance until you spend them. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to your balance, labeled as returned purchased credits.' }, + { id: 'f-credits-transfer', title: 'Can credits be transferred or turned into POL?', source: 'faq', + questions: ['Can I transfer credits to another member?', 'Can I give my credits to a friend?', 'Can I sell my credits or exchange them for POL?', 'Are credits a token?'], + tags: ['credits', 'transfer', 'cash value', 'token'], + answer: 'No. Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash. Purchased credits are recorded on-chain and burned as your campaigns spend them; earned credits (welcome, viewing, visits, promo codes) are kept by the site and labeled separately.' }, + { id: 'f-price-feed', title: 'How the POL price of a package is set', source: 'faq', + questions: ['How is the POL price calculated?', 'Why did the POL amount change?', 'What price feed do you use?'], + tags: ['price', 'chainlink', 'pol price', 'rate'], + answer: 'Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon, so the POL amount moves with the market. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers. Any package price change waits 24 hours before it takes effect.' }, + { id: 'f-contract', title: 'The contract address and network', source: 'faq', + questions: ['What is the contract address?', 'Which network is the contract on?', 'Is the contract verified?', 'Can the split be changed?'], + tags: ['contract', 'address', 'polygonscan', 'verified', 'polygon'], + answer: 'InstantAdPay runs on Polygon mainnet (chain id 137). The contract is 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 and its source is verified and public. The percentages and qualification rules are constants in the code, there is no function that changes them, and the contract holds no member funds. The plain-language review is at https://instantadpay.com/contract and the reference facts at https://instantadpay.com/facts.' }, + { id: 'f-platform-share', title: 'Where the platform share goes', source: 'faq', + questions: ['Where does the 20 percent platform share go?', 'What are the platform wallets?', 'What happens to a share nobody qualifies for?'], + tags: ['platform', 'platform wallets', 'fees', 'pass-up'], + answer: 'The 20 percent platform share is two fixed 10 percent fees to platform wallet A (0x7627fc78876948ac9d95c1c9eb061e7d6d647b70) and B (0x8b7d33849a2c4d92c985be31e46dc564ba901ad2). Platform income pays for operations, development, marketing and the game rewards. If nobody within 25 steps qualifies for a level, that share goes to wallet A, and every pass-up is recorded on-chain with the reason. Overpayment is returned to the buyer in the same transaction.' }, + { id: 'f-active-viewing', title: 'Why the video or timer paused', source: 'faq', + questions: ['Why did my video ad pause?', 'Why did the countdown stop?', 'Why was my view not counted?'], + tags: ['video', 'timer', 'countdown', 'paused', 'anti-fraud'], + answer: 'Viewing is active only: video ads pause when you switch tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early. Keep the tab in front until the countdown finishes and pass the quick check.' }, + { id: 'f-game-rewards', title: 'Where game POL rewards come from', source: 'faq', + questions: ['Where do the game rewards come from?', 'Are game rewards guaranteed?', 'Why did a game reward not pay?'], + tags: ['games', 'rewards', 'pool', 'pol'], + answer: 'The network games pay small POL rewards for gameplay milestones from game wallets and reward pools the company tops up from platform income (some games also fund a pool from in-game sales). Rewards are per action, paid while the pool covers them, and never guaranteed. You sign in to every game with your InstantAdPay account, so your sponsor carries across them.' }, + { id: 'f-not-investment', title: 'What InstantAdPay is not', source: 'faq', + questions: ['Is this an investment?', 'Is there guaranteed income?', 'Does InstantAdPay hold my money?'], + tags: ['investment', 'income', 'guarantee', 'custody', 'disclaimer'], + answer: 'InstantAdPay is an advertising platform with a referral program, not an investment, token sale or security. Credits are not a token and have no cash value. It does not hold member money: payments are split by the contract in the same transaction. And it is not a guarantee of income: referral payouts happen only when real advertising is bought in your line.' }, + { 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 Buy packages tab 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.' }, + { 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 on the Buy packages tab. The three Qualified Start videos in Training walk through it.' }, + { 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-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 or private key with anyone. Nobody from InstantAdPay will ever ask for them, and nobody from InstantAdPay will message you first asking for money or wallet access. If someone does, do not reply, and tell support through Help at https://instantadpay.com/my#help.' } +]; +module.exports = { FAQ }; diff --git a/kb.js b/kb.js new file mode 100644 index 0000000..6bccee7 --- /dev/null +++ b/kb.js @@ -0,0 +1,280 @@ +// 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. +// +// Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else +// DATA_DIR/kb.json (local dev and the QA harness). +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const db = require('./db'); + +let DATA_DIR = null, SEEDS = [], ready = null; +let cache = null, cacheAt = 0, index = null; +const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: 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 row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '', + handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '', + edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) }); +function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } } +const D = { + async ensure() { + await db.q(`CREATE TABLE IF NOT EXISTS kb_entries ( + id VARCHAR(64) PRIMARY KEY, + title VARCHAR(200) NOT NULL, + questions TEXT NULL, + answer TEXT NOT NULL, + tags VARCHAR(800) NULL, + pattern TEXT NULL, + handoff TINYINT NOT NULL DEFAULT 0, + ord INT NULL, + source VARCHAR(16) NOT NULL DEFAULT 'admin', + ticket_ref VARCHAR(20) NULL, + seed_hash CHAR(40) NULL, + edited TINYINT NOT NULL DEFAULT 0, + deleted TINYINT NOT NULL DEFAULT 0, + created BIGINT NOT NULL, + updated BIGINT NOT NULL, + INDEX (deleted, updated) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); + }, + async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); }, + async put(e) { + await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags), + pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash), + edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`, + [e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order, + e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]); + } +}; +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 = () => db.enabled() ? D : 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 (https://instantadpay.com/my#help, or https://instantadpay.com/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 6abb6e6..25b86a8 100644 --- a/public/admin.html +++ b/public/admin.html @@ -97,6 +97,7 @@ + @@ -295,6 +296,27 @@ + + ' @@ -925,6 +926,12 @@ + '

' + '' + '

'; + $('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20) + const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return; + const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal); + const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body); + await setPane('kb'); window.IAPKB.compose(draft); + })); $('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } }; $('spSt').addEventListener('change', () => patch({ status: $('spSt').value })); diff --git a/qa/chatbot-sync.mjs b/qa/chatbot-sync.mjs index ac970cf..77d5d87 100644 --- a/qa/chatbot-sync.mjs +++ b/qa/chatbot-sync.mjs @@ -1,6 +1,10 @@ // Chatbot knowledge guard (Marty, 2026-09-16: "ensure the chatbot is completely current, and keep it that way"). // Compares chatbot.js KNOWLEDGE_DATE with the newest public release note. If a note is newer, the // chatbot was not brought up to date with that change: fix chatbot.js (canned + prompt), bump the date. +// Since the knowledge base (2026-10-20, kb.js) the assistant also answers from Admin > Knowledge base, so a +// KB change made after a release counts too: the guard takes the later of KNOWLEDGE_DATE and the site's +// newest KB edit by a person (/api/chat/kb-stamp, a Central-time day; seed refreshes from the code do not count). Either way a release must be followed by a +// knowledge update, in the code or in the admin pane. // node qa/chatbot-sync.mjs (checks the live site's /api/releases) // LOCAL=http://127.0.0.1:8796 node qa/chatbot-sync.mjs import fs from 'node:fs'; @@ -8,14 +12,18 @@ const B = process.env.LOCAL || 'https://instantadpay.com'; const src = fs.readFileSync(new URL('../chatbot.js', import.meta.url), 'utf8'); const m = /KNOWLEDGE_DATE = '(\d{4}-\d{2}-\d{2})'/.exec(src); if (!m) { console.log('[bug] chatbot.js has no KNOWLEDGE_DATE constant'); process.exit(1); } -const known = m[1]; +let known = m[1], via = 'chatbot.js KNOWLEDGE_DATE'; +try { + const st = await (await fetch(B + '/api/chat/kb-stamp')).json(); + if (st && /^\d{4}-\d{2}-\d{2}$/.test(st.updated || '') && st.updated > known) { known = st.updated; via = 'knowledge base (' + st.count + ' entries)'; } +} catch (e) { console.log('[warn] no knowledge-base stamp from ' + B + ' (' + e.message + '), using KNOWLEDGE_DATE only'); } let notes = []; try { const r = await (await fetch(B + '/api/releases')).json(); notes = r.notes || []; } catch (e) { console.log('[warn] could not read ' + B + '/api/releases: ' + e.message); process.exit(0); } const newer = notes.filter(n => (n.date || '') > known); if (newer.length) { console.log('[bug] chatbot knowledge date ' + known + ' is older than ' + newer.length + ' release note(s):'); for (const n of newer) console.log(' ' + n.date + ' ' + n.title); - console.log(' -> update chatbot.js (canned answers + systemPrompt) for each, then bump KNOWLEDGE_DATE.'); + console.log(' -> update chatbot.js (canned answers + systemPrompt) or the entries in Admin > Knowledge base for each, then bump KNOWLEDGE_DATE.'); process.exit(1); } -console.log('chatbot knowledge date ' + known + ' covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')'); +console.log('chatbot knowledge date ' + known + ' (' + via + ') covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')'); diff --git a/qa/kb-chat.mjs b/qa/kb-chat.mjs new file mode 100644 index 0000000..65fed6c --- /dev/null +++ b/qa/kb-chat.mjs @@ -0,0 +1,130 @@ +// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20). +// node qa/kb-chat.mjs (or: bash qa/run.sh kb) +// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB) and a mock OpenRouter that +// records every request and answers from the "Knowledge base" block it was given. Nothing touches production: +// OPENROUTER_URL points at the mock and the key is a throwaway string. +// Covers: the Coinbase question answered from the KB through the AI path, the CANNED fast path served from the +// KB (no AI call), an off-topic question told to say "I'm not sure, ask support", admin create / edit / test / +// delete, an admin edit to a canned entry changing the instant answer, and /api/chat/kb-stamp. Exit 1 on failure. +import http from 'node:http'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; + +const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +const PORT = Number(process.env.KB_PORT || 8799), MOCK = PORT + 100; +const B = 'http://127.0.0.1:' + PORT; +const ADMIN = 'localtest'; +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kb-')); fs.mkdirSync(path.join(DATA, 'uploads')); +let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +// -- the mock OpenRouter: answers with the first KB answer it was handed, or the not-sure line +const calls = []; +const mock = http.createServer((req, res) => { + let raw = ''; req.on('data', c => raw += c); req.on('end', () => { + let body = {}; try { body = JSON.parse(raw); } catch (e) {} + calls.push({ url: req.url, auth: req.headers.authorization, body }); + const sys = ((body.messages || [])[0] || {}).content || ''; + const m = /\nAnswer: ([^\n]+)/.exec(sys.slice(sys.indexOf('KNOWLEDGE BASE'))); + const content = m ? m[1] : "I'm not sure, ask support: open Help at https://instantadpay.com/my#help."; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('\n\n' + JSON.stringify({ choices: [{ message: { content } }] })); // keepalive padding first, like the real thing + }); +}); +await new Promise(r => mock.listen(MOCK, '127.0.0.1', r)); + +let srv = null, srvLog = ''; +async function boot() { + srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'], + env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, + OPENROUTER_API_KEY: 'qa-throwaway', OPENROUTER_URL: 'http://127.0.0.1:' + MOCK + '/api/v1/chat/completions', DATABASE_URL: '' }) }); + srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d); + let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } } + if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000)); +} +async function halt() { if (!srv) return; const s = srv; srv = null; s.kill(); await new Promise(r => { s.once('exit', r); setTimeout(r, 3000); }); await sleep(300); } +const cleanup = async () => { try { await halt(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} }; + +try { + await boot(); + const api = async (p, data, method, hdr) => { const r = await fetch(B + p, data !== undefined || method ? { method: method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: data === undefined ? undefined : JSON.stringify(data) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; }; + const adminH = { Authorization: 'Bearer ' + ADMIN }; + const chat = message => api('/api/chat', { message }, 'POST'); // six questions in all, under the 10-a-minute chat limit + + // 1. seeds landed in DATA_DIR/kb.json + await sleep(300); + const list0 = await api('/api/admin/kb', undefined, undefined, adminH); + const ids = (list0.j && list0.j.entries || []).map(e => e.id); + ok(ids.includes('f-coinbase') && ids.includes('c-withdraw') && ids.length >= 55, 'KB seeded from CANNED + FAQ + the Coinbase ticket', ids.length + ' entries'); + ok(fs.existsSync(path.join(DATA, 'kb.json')), 'JSON store at DATA_DIR/kb.json'); + + // 2. the Coinbase question goes to the AI with the Coinbase entry in its knowledge base + let n = calls.length; + const cb = await chat('Can I use my regular Coinbase account?'); + const sys = calls[n] && calls[n].body.messages[0].content || ''; + ok(cb.status === 200 && calls.length === n + 1, 'Coinbase question goes to the AI path (one call)', 'status ' + cb.status); + ok(sys.includes('KNOWLEDGE BASE') && sys.includes('Coinbase is an exchange') && sys.indexOf('[1] Can I use my regular Coinbase account?') > 0, 'system prompt carries the Coinbase entry first'); + ok(sys.includes('NEVER promise or estimate income') && sys.includes('No em dashes'), 'compliance rules still in the prompt'); + ok(calls[n] && calls[n].body.reasoning && calls[n].body.reasoning.enabled === false, 'reasoning stays off'); + ok(cb.j && /Coinbase is an exchange/.test(cb.j.reply) && (cb.j.kb || [])[0] === 'f-coinbase', 'reply drawn from the KB entry', JSON.stringify(cb.j).slice(0, 140)); + + // 3. the CANNED fast path, now served from the KB: no AI call + n = calls.length; + const wd = await chat('how do I withdraw my money'); + ok(wd.j && wd.j.canned && wd.j.kb === 'c-withdraw' && /no withdrawals here/.test(wd.j.reply) && calls.length === n, 'canned answer served from the KB, no AI call', JSON.stringify(wd.j).slice(0, 100)); + const sup = await chat('I want to talk to a real person'); + ok(sup.j && sup.j.handoff && sup.j.kb === 'c-support', 'support hand-off flag kept on the instant answer'); + + // 4. nothing fits: the prompt says so and the reply hands off + n = calls.length; + const off = await chat('What is the capital of Mongolia?'); + const sys2 = calls[n] && calls[n].body.messages[0].content || ''; + ok(/no entry matches this question/.test(sys2) && /I'm not sure, ask support/.test(sys2), 'off-topic: prompt tells the AI to say it is not sure'); + ok(off.j && off.j.handoff, 'off-topic reply offers "Send this to support"'); + + // 5. admin: create, find, test, edit, delete + const cr = await api('/api/admin/kb', { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?', 'Do you take PayPal'], answer: 'No. Packages are paid in POL on Polygon only — PayPal is not accepted.', tags: 'paypal, payment' }, 'POST', adminH); + ok(cr.j && cr.j.ok && cr.j.entry.answer.indexOf('—') < 0, 'admin creates an entry (em dash cleaned)', cr.j && cr.j.entry && cr.j.entry.answer); + const kid = cr.j && cr.j.entry && cr.j.entry.id; + const noAuth = await api('/api/admin/kb', { title: 'x', answer: 'y' }, 'POST'); + ok(noAuth.status === 401, 'KB admin routes need the admin'); + const t = await api('/api/admin/kb/test', { question: 'do you accept paypal' }, 'POST', adminH); + ok(t.j && t.j.ranked[0] && t.j.ranked[0].id === kid && t.j.ranked[0].used, 'Try a question ranks the new entry first'); + n = calls.length; + await chat('can I pay using paypal?'); + ok(calls[n] && calls[n].body.messages[0].content.includes('PayPal is not accepted'), 'new entry reaches the AI prompt right away'); + const ed = await api('/api/admin/kb/' + kid, { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?'], answer: 'No, PayPal is not accepted. Packages are paid in POL on Polygon.', tags: ['paypal'] }, 'PUT', adminH); + ok(ed.j && ed.j.ok && ed.j.entry.answer.startsWith('No, PayPal'), 'admin edits the entry'); + const srch = await api('/api/admin/kb?q=paypal', undefined, undefined, adminH); + ok(srch.j && srch.j.entries[0] && srch.j.entries[0].id === kid, 'admin search finds it'); + const bad = await api('/api/admin/kb', { title: 'x', answer: 'y', pattern: '(' }, 'POST', adminH); + ok(bad.status === 400, 'a broken instant-answer pattern is refused'); + const del = await api('/api/admin/kb/' + kid, undefined, 'DELETE', adminH); + const gone = await api('/api/admin/kb/' + kid, undefined, undefined, adminH); + ok(del.j && del.j.ok && gone.status === 404, 'admin deletes it'); + + // 6. editing a canned entry changes the instant answer (one source) + const cw = (await api('/api/admin/kb/c-withdraw', undefined, undefined, adminH)).j.entry; + await api('/api/admin/kb/c-withdraw', Object.assign({}, cw, { answer: cw.answer + ' (edited in QA)' }), 'PUT', adminH); + const wd2 = await chat('how do I withdraw'); + ok(wd2.j && /\(edited in QA\)$/.test(wd2.j.reply), 'admin edit to a canned entry is what the fast path serves'); + + // 7. the sync guard's stamp: today (Central), because a person just edited entries + const st = await api('/api/chat/kb-stamp'); + const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); + ok(st.j && st.j.updated === today && st.j.count >= 55, '/api/chat/kb-stamp reports the newest human edit', JSON.stringify(st.j)); + + // 8. a restart (the seed sync runs again) keeps admin work and does not bring a deleted seed back + await api('/api/admin/kb/f-refunds', undefined, 'DELETE', adminH); + await halt(); await boot(); + const after = await api('/api/admin/kb', undefined, undefined, adminH); + const aIds = (after.j && after.j.entries || []).map(e => e.id); + const cw2 = (after.j && after.j.entries || []).find(e => e.id === 'c-withdraw'); + ok(!aIds.includes('f-refunds') && aIds.includes('f-coinbase'), 'restart: a deleted seed stays deleted'); + ok(cw2 && /\(edited in QA\)$/.test(cw2.answer) && cw2.edited, 'restart: an admin edit to a seed is not overwritten by the code'); +} catch (e) { ok(false, 'run', e.message); } +await cleanup(); +console.log(fails ? fails + ' failure(s)' : 'all KB chat checks passed'); +process.exit(fails ? 1 : 0); diff --git a/qa/kb-retrieval.cjs b/qa/kb-retrieval.cjs new file mode 100644 index 0000000..f68cd8e --- /dev/null +++ b/qa/kb-retrieval.cjs @@ -0,0 +1,49 @@ +// Knowledge-base retrieval unit test (kb.js): the right entry must rank first for each sample question, +// scored over the real seeds (chatbot.js CANNED + kb-seed.js). No server, no network. +// node qa/kb-retrieval.cjs +const path = require('path'); +const kb = require(path.join(__dirname, '..', 'kb.js')); +const chatbot = require(path.join(__dirname, '..', 'chatbot.js')); +const { buildIndex, rank, relevant, validate } = kb._pure; + +const entries = chatbot.seeds(); +const idx = buildIndex(entries); +const CASES = [ + ['Can I hook up my Coinbase account to pay for a package?', 'f-coinbase'], + ['can i just use coinbase', 'f-coinbase'], + ['Is my payment refundable if I change my mind?', 'f-refunds'], + ['Can I give some of my credits to a friend?', 'f-credits-transfer'], + ['Why does the amount of POL keep changing when I buy?', 'f-price-feed'], + ['What is the smart contract address on polygonscan?', 'f-contract'], + ['My video stopped playing when I switched tabs', 'f-active-viewing'], + ['How many extra POL should I keep for gas fees?', 'f-how-much-pol'], + ['My bank refused my card on MoonPay', 'f-moonpay-declined'], + ['Trust wallet says this will drain my wallet', 'c-trust-drain'], + ['How do I adopt somebody from the holding tank?', 'c-holding-tank'], + ['I keep getting signed out every few hours', 'c-session-4h'], + ['Where does the 20 percent platform share go?', 'f-platform-share'] +]; +let bad = 0; +for (const [q, want] of CASES) { + const hits = rank(idx, q, 5), top = hits[0]; + const ok = top && top.entry.id === want && relevant(hits).length > 0; + if (!ok) bad++; + console.log((ok ? 'ok ' : 'FAIL ') + q + ' -> ' + hits.slice(0, 3).map(h => h.entry.id + ' ' + h.score).join(', ') + (ok ? '' : ' (wanted ' + want + ')')); +} +// off-topic questions should bring nothing back, so the prompt says "I'm not sure, ask support" +for (const q of ['What is the weather in Paris tomorrow?', 'Recommend a good pizza recipe']) { + const r = relevant(rank(idx, q, 5)); + if (r.length) bad++; + console.log((r.length ? 'FAIL ' : 'ok ') + 'off-topic: ' + q + ' -> ' + (r.map(h => h.entry.id + ' ' + h.score).join(', ') || 'nothing')); +} +// admin input hygiene: em dashes are turned into commas, a bad pattern is refused +const v = validate({ title: 'T', answer: 'One — two', questions: 'a\nb', tags: 'X, y' }); +if (v.answer !== 'One, two' || v.questions.length !== 2 || v.tags[0] !== 'x') { bad++; console.log('FAIL validate', v); } else console.log('ok validate cleans em dashes, splits questions and tags'); +if (!validate({ title: 'T', answer: 'a', pattern: '(' }).error) { bad++; console.log('FAIL validate accepted a broken pattern'); } else console.log('ok validate refuses a broken pattern'); +// every CANNED regex still answers through the KB fast path in the same order +const ordered = entries.filter(e => e.pattern).sort((a, b) => a.order - b.order); +const first = msg => ordered.find(e => new RegExp(e.pattern, 'i').test(msg)); +const canned = chatbot.CANNED.find(c => c.re.test('how do I withdraw')); +if (!first('how do I withdraw') || first('how do I withdraw').answer !== canned.a) { bad++; console.log('FAIL fast-path order'); } else console.log('ok fast path keeps CANNED order'); +console.log(bad ? bad + ' failure(s)' : 'all retrieval checks passed'); +process.exit(bad ? 1 : 0); diff --git a/qa/run.sh b/qa/run.sh index 120c3a0..8b1765e 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -4,6 +4,7 @@ # bash qa/run.sh member # local copy: member + admin walk # bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min) # bash qa/run.sh all # public + member + earn +# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter # bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) # bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) # bash qa/run.sh sov-passes # Explorer/Champion tiers: store unit checks + admin buys Explorer with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes) @@ -34,6 +35,9 @@ if [ "$MODE" = "public" ]; then node qa/chatbot-sync.mjs || status=1 elif [ "$MODE" = "member" ]; then start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 +elif [ "$MODE" = "kb" ]; then + node qa/kb-retrieval.cjs || status=1 + node qa/kb-chat.mjs || status=1 elif [ "$MODE" = "door" ]; then node qa/door.mjs || status=1 elif [ "$MODE" = "gamepass" ]; then diff --git a/qa/walk.mjs b/qa/walk.mjs index 59d6efc..9b0c212 100644 --- a/qa/walk.mjs +++ b/qa/walk.mjs @@ -177,7 +177,7 @@ if (MODE === 'member' || MODE === 'all') { // admin await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' }); await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200); - for (const pn of ['overview', 'house', 'campaigns', 'members', 'support', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'settings']) { + for (const pn of ['overview', 'house', 'campaigns', 'members', 'support', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'kb', 'settings']) { const label = L + 'admin#' + pn; await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200); const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn); @@ -206,6 +206,20 @@ if (MODE === 'member' || MODE === 'all') { if (!/internal note/.test(txt) || !/Waiting on member/.test(await page.$eval('#spSt', e => e.selectedOptions[0].textContent).catch(() => ''))) note('bug', L + 'admin#support', 'note/reply/status not reflected'); await page.selectOption('#spPr', 'high'); await page.waitForTimeout(800); await domChecks(page, L + 'admin#support (ticket)'); console.log('ok admin Support ticket', helpRef); + // "Save as KB entry" under the reply: a prefilled knowledge-base draft (question from the member, answer from the reply) that saves + flush(bag, L + 'admin#support (ticket)'); + const save = await page.$('#spView [data-kbsave]'); + if (!save) note('bug', L + 'admin#support', 'no "Save as KB entry" button under the sent reply'); + else { + await save.click(); await page.waitForTimeout(1200); + const draft = await page.evaluate(() => ({ q: (document.getElementById('kbQs') || {}).value || '', a: (document.getElementById('kbAns') || {}).value || '', vis: !document.getElementById('kbEdit').hidden })); + if (!draft.vis || !draft.q.trim() || !draft.a.trim()) note('bug', L + 'admin#kb', 'Save as KB entry did not open a prefilled draft ' + JSON.stringify(draft).slice(0, 160)); + await domChecks(page, L + 'admin#kb (draft from ticket)'); + await page.click('#kbSave'); await page.waitForTimeout(1200); + const listed = await page.$eval('#kbTable', e => e.textContent).catch(() => ''); + if (!/from a ticket/.test(listed)) note('bug', L + 'admin#kb', 'entry saved from the ticket is not in the list'); + flush(bag, L + 'admin#kb (saved from ticket)'); console.log('ok admin Save as KB entry'); + } } flush(bag, L + 'admin#support (ticket)'); await page.screenshot({ path: OUT + '/admin-support-ticket.png' }).catch(() => {}); diff --git a/server.js b/server.js index 05f4bbb..0d1bdc8 100644 --- a/server.js +++ b/server.js @@ -24,6 +24,7 @@ const drip = require('./drip'); const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } const chatbot = require('./chatbot'); +const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20) const fraud = require('./fraud'); const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats const tank = require('./tank'); @@ -2162,6 +2163,9 @@ const server = http.createServer(async (req, res) => { const r = await chatbot.answer(b.message, b.history); return json(res, r.error ? 400 : 200, r); } + if (p === '/api/chat/kb-stamp' && req.method === 'GET') { // qa/chatbot-sync.mjs: the newest knowledge-base change (Central day) and the entry count + return json(res, 200, await kb.stamp(), { 'Cache-Control': 'no-store' }); + } // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off if (p === '/api/inbound/email' && req.method === 'POST') { // SendGrid Inbound Parse: secret key in the URL, always 200 once it matches @@ -4706,6 +4710,26 @@ const server = http.createServer(async (req, res) => { const cur = siteConfig(); cur.supportTemplates = list; fs.writeFileSync(SITE_FILE, JSON.stringify(cur, null, 2)); return json(res, 200, { ok: true, templates: read() }); } + // -- the assistant's knowledge base (2026-10-20, kb.js): Admin > Knowledge base, and "Save as KB entry" on a ticket reply + if (p === '/api/admin/kb' && (req.method === 'GET' || req.method === 'POST')) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') return json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }, { 'Cache-Control': 'no-store' }); + const r = await kb.create(await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/kb/test' && req.method === 'POST') { // which entry would answer this question, and what would ride along to the AI + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, await kb.test(b.question)); + } + m = /^\/api\/admin\/kb\/([a-z0-9-]{1,64})$/.exec(p); + if (m) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + if (req.method === 'GET') { const e = await kb.get(m[1]); return e ? json(res, 200, { entry: e }) : json(res, 404, { error: 'Entry not found.' }); } + if (req.method === 'PUT') { const r = await kb.update(m[1], await readBody(req)); return json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); } + if (req.method === 'DELETE') { const r = await kb.remove(m[1]); return json(res, r.error ? 404 : 200, r); } + return json(res, 405, { error: 'method' }); + } m = /^\/api\/admin\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); if (m) { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); From 6f194596fe0d788448b57b281dbd66e3dc6b985c Mon Sep 17 00:00:00 2001 From: martbost Date: Tue, 20 Oct 2026 05:39:02 -0500 Subject: [PATCH 2/2] Support: no 'Save as KB entry' on LinkSpin tickets (they would land in the InstantAdPay knowledge base; LinkSpin keeps its own) Co-Authored-By: Claude Opus 5.5 --- public/assets/admin.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/assets/admin.js b/public/assets/admin.js index 03d20f2..4fee5db 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -916,7 +916,7 @@ + v.messages.map(m => '
' + '
' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '' + esc(ctWhen(m.created)) + '
' + '
' + spLink(m.body) + '
' - + (m.author === 'admin' && !m.internal && window.IAPKB ? '

' : '') + + (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '

' : '') + (m.bodyEn ? '
🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)\n' + spLink(m.bodyEn) + '
' : '') + ((m.attachments || []).length ? '
' + m.attachments.map(a => 'attachment').join('') + '
' : '') + '
').join('') + ''