Site assistant (Marty 2026-11-15): chat widget in the 5xYourTeam draft-night look on every page, CANNED + FACTS from this repo's code (position $10 one time, 5 picks, sponsor 25% + L2-5 5% + pot 10% + company 45%, pass-up 20 places, Monday 7 PM Central draft, earned order, 3-day return, 48 h hold, 10 open picks, no contact data), retrieval over the shared network knowledge base on the hub (netkb.js, home entries boosted, another site named = its answer), reasoning off, account problems hand off to network support. chatbot.test 187, unit 62/62, smoke 160/160, iap-tank 35/35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 12:53:16 -06:00
parent c25ae40f8b
commit 2b91ff5b8c
51 changed files with 971 additions and 4 deletions
+8
View File
@@ -82,3 +82,11 @@ the coach's line. Picks keep their 3-day window there too; whichever sweep runs
Hub `HUB_SITES` entry `fivex` + secret; `TANK_MODE=iap` + `DRAFT_PARTNER_SECRET` + `IAP_URL` (above); the network-sites list
and LinkSpin `nw5x`; the contract on chain with the prize wallet; DOCSTORE_URL; old-member reconciliation; PolHunter mission.
## Site assistant (2026-11-15)
Chat widget on every page (`public/assets/chat.js` + `chat.css` in the draft-night look). `chatbot.js` holds what it knows (CANNED +
FACTS from this repo's code); `chatcore.js`, `kb.js` (`kb.json` = a MySQL document) and `netkb.js` (the shared network knowledge on
the hub) are the same files on every rebuilt site. OpenRouter key: `/app/data/openrouter.key` on the volume. Account problems hand off
to `https://instantadpay.com/support?from=fivex`. Admin API (x-admin-token): `/api/admin/kb`, `/api/admin/kb/<id>`,
`/api/admin/kb/test`, `/api/admin/kb/network?refresh=1&publish=1`. Test: `node qa/chatbot.test.mjs` (Q&A in `qa/chat-qa.json`).
+104
View File
@@ -0,0 +1,104 @@
// 5xYourTeam's site assistant (Marty 2026-11-15): what it knows. The engine is chatcore.js (the same on every rebuilt site);
// retrieval also covers the other network sites through the hub (netkb.js), this site's entries first.
//
// Every fact below was checked against this repo on KNOWLEDGE_DATE: config.js (position $10, 5 picks on buy, max 10 per purchase;
// split sponsor 25% + L2-5 5% + pot 10% + company 45%, 20 places; draft Monday 7 PM Central, 5 rounds, 90 s clock, away = auto-pick;
// picks return after 3 days, 48 h release hold, 10 open picks, 24 h sign-up grace; pot places 50/30/20), ../contracts DraftPosition
// (SPONSOR_BPS 2500, LEVEL_BPS 500, PRIZE_BPS 1000, MAX_DEPTH 20, pass-up over non-holders, no owner withdraw, failed sends claimable),
// draft.js (earned order), tankpool.js (who can be drafted, 2-adoption rule), league.js, public/*.html (index, join, cards, terms).
// HOUSE RULE: when a feature changes, update CANNED and FACTS in the same commit and bump KNOWLEDGE_DATE.
// Plain words, no em dashes, never a promise of income, "SafePal or any other crypto wallet", never RM Circle.
'use strict';
const core = require('./chatcore');
const C = require('./config').get();
const KNOWLEDGE_DATE = '2026-11-15';
const URL_ = 'https://' + C.site;
const SUPPORT = 'https://instantadpay.com/support';
const PO = C.position, SP = C.split, D = C.draft, PK = C.picks;
const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const hour12 = h => (h % 12 || 12) + (h < 12 ? ' AM' : ' PM');
const WHEN = DAYS[D.dow] + ' at ' + hour12(D.hour) + ' Central';
const NOT_INCOME = 'A position buys a draft spot and coaching tools, not income. Nothing is promised.';
const POT = C.pot.split.join('/');
const CANNED = [
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My position did not show up', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
re: core.SUPPORT_RE, handoff: true,
a: 'Network support handles every network site, 5xYourTeam included: open ' + SUPPORT + ', say it is about 5xYourTeam, and include your username, your wallet address and the transaction link if it is about a position. Marty answers there and by email. Tap "Open network support" below and your question goes with you.' },
{ id: 'refund', title: 'Refunds', q: ['Can I get a refund on my position?', 'Can I cancel my position?'], tags: ['refund', 'cancel'],
re: /\brefund|cancel (my |the |a )?position|money back|reverse (my |a |the )?(payment|transaction)/i, handoff: true,
a: 'Positions are paid on Polygon and are final once confirmed, so they cannot be reversed or refunded. A position is one payment that never renews, so there is nothing to cancel. If something went wrong with a payment, open network support at ' + SUPPORT + ' with the transaction link.' },
{ id: 'about', title: 'What is 5xYourTeam?', q: ['What is 5xYourTeam?', 'How does The Draft work?', 'What is 5x?'], tags: ['5xyourteam', 'the draft', 'overview', 'coach'],
re: /(what('s| is) (5 ?x ?your ?team|5x|the draft|this (site|place))|how does (5 ?x ?your ?team|5x|the draft|this site|it) work)/i,
a: '5xYourTeam is The Draft: a weekly draft for people in the network who joined without a sponsor. A $' + PO.usd + ' one-time position gives you ' + PO.picksOnBuy + ' picks right away and a spot in every draft, ' + WHEN + ', ' + D.rounds + ' rounds. Each pick becomes yours to sponsor and coach through site messages. Draft order is earned: coaches whose picks started last week pick first. See ' + URL_ },
{ id: 'withdraw', title: 'Withdrawals', q: ['How do I withdraw?', 'Where is my balance?', 'How do I withdraw my earnings?'], tags: ['withdraw', 'balance', 'cash out'],
re: /(withdraw|cash ?out|my balance|pending (pay|commission))/i,
a: 'There is nothing to withdraw. Each share goes straight to the person\'s wallet inside the buyer\'s transaction, so the contract keeps nothing (a payment that fails to send waits in the contract for that wallet to claim). Every payment shows in the live ledger at ' + URL_ + '/ledger' },
{ id: 'split', title: 'Where the $10 goes: the split', q: ['How do payouts work?', 'Where does the $10 go?', 'Who gets paid when I buy?', 'What is the commission?'], tags: ['split', 'payout', 'commission', 'levels', 'pass-up', 'pot'],
re: /(split|payouts?|commission|who gets paid|where does (my|the) (money|\$ ?10) go|percent|pass(ed)? over|pass.?up|qualif|earn|get paid)/i,
a: 'The DraftPosition contract splits every $' + PO.usd + ' position in the same transaction: ' + SP.sponsorPct + '% to your sponsor, ' + SP.levelPct + '% to each of levels 2 to 5 of your network sponsor line, ' + SP.potPct + '% to the weekly Best Coach pot and ' + SP.companyPct + '% to 5xYourTeam. Only people who hold a position can receive a share; anyone who does not is passed over to the next person up who does, looking up to ' + SP.maxDepth + ' places. ' + NOT_INCOME },
{ id: 'position', title: 'A position: price and what you get', q: ['How much is a position?', 'What do I get for $10?', 'Is it a subscription?', 'Can I buy more than one position?'], tags: ['position', 'price', '$10', 'picks', 'buy'],
re: /(\bposition|\$ ?10\b|ten dollars|how much(?! pol)|price|cost|subscription|what do i get)/i,
a: 'A position is $' + PO.usd + ' one time in POL, never a subscription. It gives ' + PO.picksOnBuy + ' instant picks from this week\'s pool, a spot in every weekly draft (' + D.rounds + ' rounds), the coaching tools (scouting stats, the getting-started steps, site messages, who to help first), a coach page and trading cards, and up to ' + PK.maxOpen + ' open picks at a time. You can buy 1 to ' + PO.maxQty + ' in one payment. ' + NOT_INCOME + ' Get one at ' + URL_ + '/join' },
{ id: 'draft', title: 'When the draft runs and how picking works', q: ['When is the draft?', 'What if I miss the draft?', 'How long do I have to pick?'], tags: ['draft', 'monday', 'rounds', 'auto-pick', 'queue'],
re: /(when is the draft|draft (day|night|time|room|clock)|miss(ed)? the draft|auto.?pick|my queue|rounds?|how long do i have to pick|monday)/i,
a: 'The draft runs every ' + WHEN + ', ' + D.rounds + ' rounds in straight order. A coach in the draft room gets a ' + D.pickSeconds + '-second clock. Away? You are auto-picked at once from your own queue, or the best available player by scouting score. A coach who already has ' + PK.maxOpen + ' open picks is skipped for that slot.' },
{ id: 'order', title: 'How draft order is earned', q: ['How is draft order decided?', 'How do I pick first?', 'Why am I last in the draft?'], tags: ['draft order', 'earned', 'started'],
re: /(draft order|pick first|picking first|my (draft )?spot|why am i (last|first)|order (is|was) (decided|earned))/i,
a: 'Draft order is earned: first the coaches with the most of last week\'s picks started (switched on payouts or made a first purchase), then the most started ever, then who got their position first. Help your picks get going this week and you move up next ' + DAYS[D.dow] + '.' },
{ id: 'picks', title: 'Who can be drafted, and when picks return', q: ['Who is in the pool?', 'What happens to a pick that does not start?', 'Can I release a pick?', 'Do I get their email?'], tags: ['pool', 'picks', 'return', 'release', 'adoption', 'contact'],
re: /(the pool|who (is|are) in the pool|picks? (that )?(do|does|did) ?(n.?t| not) start|unstarted|who can be drafted|picks? (go|goes|come|comes|return)|back to the pool|release (a |my )?pick|their (email|phone|contact)|contact (details|info))/i,
a: 'The pool is people in the network waiting for a sponsor. Nobody locked on a network contract, already sponsored, adopted twice, spam, or inside their first ' + PK.graceHours + ' hours is ever in it. A pick that has not started returns to the pool after ' + PK.returnDays + ' days (unless they have now had 2 adoptions); a started pick stays. You cannot release a pick in its first ' + PK.holdHours + ' hours. You never get their email or any contact details: you coach through site messages.' },
{ id: 'pot', title: 'The Best Coach pot', q: ['What is the Best Coach pot?', 'How is the pot shared?', 'How do I win Best Coach?'], tags: ['best coach', 'pot', 'prize', 'weekly'],
re: /(best coach|\bpot\b|prize|rookie of the week|standings)/i,
a: SP.potPct + '% of every position goes to a separate prize wallet fixed in the contract. Each week the pot is shared among the coaches whose picks started the most that Central week (' + POT + ' percent of that week\'s pot to the top places; a tie goes to whoever got there first). Every pot payout is listed on the ledger with its transaction. Prizes depend on that week\'s pot and are not promised.' },
{ id: 'coaching', title: 'Coaching your picks', q: ['How do I coach my picks?', 'How do I message my pick?', 'What are the getting-started steps?'], tags: ['coaching', 'team', 'messages', 'steps'],
re: /(coach(ing)? (my|your|the) picks?|message (my|a) pick|getting.?started steps|the steps|my team page|\/team|who to help)/i,
a: 'Your team page (' + URL_ + '/team) shows each pick\'s scouting stats, the five getting-started steps, one-tap messages and a thread with them, and who to help first: picks about to return to the pool, picks one step from payouts, and quiet ones. Messages go through the site only. Helping a pick link a wallet and switch on payouts is what counts as started.' },
{ id: 'cards', title: 'Trading cards', q: ['What are the trading cards?', 'What are the card tiers?'], tags: ['cards', 'rookie', 'starter', 'all-star', 'hall of fame'],
re: /(trading cards?|cards?\b|rookie|starter|all.?star|hall of fame|tiers?)/i,
a: 'Each pick has a trading card that levels up as they do: Rookie when drafted, Starter when they link a wallet, Pro when they switch on payouts, All-Star at their first purchase, Hall of Fame when they hold a position of their own and coach a team. Public cards show milestones, never earnings. See ' + URL_ + '/cards' },
{ id: 'builder', title: 'The builder', q: ['What is the builder?', 'Where do I save my referral IDs?'], tags: ['builder', 'referral id', 'programs'],
re: /(\bbuilder\b|referral (id|link|code)s?|save (my )?(id|link))/i,
a: 'The builder (' + URL_ + '/builder) is the CryptoTeamBuild downline builder: outside programs run by third parties. Save your referral ID for each program you use, and your picks see your link for it.' },
{ id: 'wallet', title: 'Signing in and paying', q: ['How do I sign in?', 'Which wallet should I use?', 'How do I pay?'], tags: ['sign in', 'wallet', 'pol', 'safepal', 'pay'],
re: /(sign ?(in|up)|log ?in|which wallet|what wallet|wallet|metamask|safepal|\bpol\b|polygon|crypto|gas|fee|how (do|can) i (pay|buy))/i,
a: 'Sign in on ' + URL_ + ' with your wallet or your network account; the position goes to the wallet you are signed in with. Pay in POL on Polygon with SafePal or any other crypto wallet, keeping a little extra POL for the network fee. Anything you send above the exact price comes back in the same transaction.' },
{ id: 'safe', title: 'Is it safe? Is it a scheme?', q: ['Is this a pyramid scheme?', 'Is 5xYourTeam legit?', 'Who holds the money?'], tags: ['safe', 'legit', 'pyramid', 'contract'],
re: /(pyramid|ponzi|scam|scheme|legit|safe|trust|rug|who holds)/i,
a: 'A position buys a seat in the draft and the coaching tools. The DraftPosition contract on Polygon splits it in the same transaction with fixed shares and no owner withdraw; the contract keeps nothing. Check every payment at ' + URL_ + '/ledger and the contract at ' + URL_ + '/contract. Nobody receives anything unless real positions are bought in their line. ' + NOT_INCOME },
{ id: 'promote', title: 'Promote 5xYourTeam', q: ['Is there a promo kit?', 'Where are the banners?'], tags: ['promote', 'kit', 'banners'],
re: /(promo|promote|banners?|creatives?|kit|swipes?)/i,
a: 'The promo kit at ' + URL_ + '/promote has creatives in every common size and swipe copy, all carrying your network username. Your coach page is ' + URL_ + '/your-name.' }
];
const FAQ = [
{ id: 'f-network', title: '5xYourTeam and the other network sites', source: 'faq', tags: ['network', 'one account', 'holding tank'],
questions: ['Is 5xYourTeam part of InstantAdPay?', 'Where do the players in the pool come from?', 'Do I need a new account?'],
answer: '5xYourTeam is part of the network: one account, one username and one sponsor line across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner. The pool is the network\'s holding tank: people who joined without a sponsor. A pick is an adoption under the network\'s holding-tank rules, and the person gets the network\'s normal new-sponsor email.' },
{ id: 'f-started', title: 'What counts as a started pick', source: 'faq', tags: ['started', 'payouts on', 'first purchase'],
questions: ['What counts as started?', 'When does a pick count for Best Coach?'],
answer: 'A pick counts as started when they switch on payouts or make a first purchase. Started picks stay on your team, decide next week\'s draft order and count for Best Coach that Central week.' }
];
const FACTS = () => [
'- WHAT IT IS: 5xYourTeam (' + URL_ + ') is The Draft: coaches draft people waiting in the network holding tank. A $' + PO.usd + ' one-time position (in POL, never a subscription, 1 to ' + PO.maxQty + ' per payment) = ' + PO.picksOnBuy + ' instant picks + a spot in every weekly draft + coaching tools + a coach page ' + URL_ + '/<username> and trading cards. Up to ' + PK.maxOpen + ' open picks at a time.',
'- THE DRAFT: every ' + WHEN + ', ' + D.rounds + ' rounds, straight order. Order is EARNED: most of last week\'s picks started (payouts on or a first purchase), then started ever, then the earlier position, then a fixed shuffle. In the room = a ' + D.pickSeconds + '-second clock; away = auto-picked at once from the coach\'s queue, else the best available by scouting score. A coach with ' + PK.maxOpen + ' open picks is skipped. A draft missed by more than ' + D.lateHours + ' hours (app down) is skipped, never run late.',
'- PICKS ARE ADOPTIONS under the network holding-tank rules: never anyone locked on a network contract, already sponsored, adopted twice, spam/throwaway, or within ' + PK.graceHours + ' hours of sign-up. An unstarted pick returns to the pool after ' + PK.returnDays + ' days unless they have had 2 adoptions; a started pick stays; no release in the first ' + PK.holdHours + ' hours. Coaches never see email, phone or contact data; they coach through site messages; the pick gets the network\'s normal new-sponsor email.',
'- SPLIT (DraftPosition constants, no owner withdraw): sponsor ' + SP.sponsorPct + '%, levels 2-5 ' + SP.levelPct + '% each, Best Coach pot ' + SP.potPct + '%, company ' + SP.companyPct + '%, same transaction. Pass-up: only position holders receive; the first holder up the line gets the ' + SP.sponsorPct + '%, the next four ' + SP.levelPct + '% each, within ' + SP.maxDepth + ' places; an unclaimed level share goes to the company; the pot share always goes to the pot. A failed send waits in the contract for its owner to claim. Sponsor line from the network hub, signed on the first position and recorded link by link, never changed.',
'- BEST COACH POT: ' + SP.potPct + '% of every position to a prize wallet fixed in the contract; each Central week shared among the coaches whose picks started the most (places ' + POT + ' percent; tie = got there first), announced on the board, every payout on the ledger. Prizes depend on that week\'s pot, never promised. Boards also show Rookie of the Week and last week\'s top 3.',
'- CARDS: Rookie (drafted), Starter (wallet), Pro (payouts on), All-Star (first purchase), Hall of Fame (holds a position of their own). Public cards show milestones, never earnings; scouting earnings show to coaches only.',
'- PAGES: / (pool, tracker, standings), /join (buy), /team (coaching), /cards, /builder (CryptoTeamBuild builder, third-party programs), /promote, /ledger, /contract, /terms, /disclaimer, /privacy. Run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004.',
'- NO REFUNDS: blockchain payments are final. SUPPORT for account or payment problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site). ' + NOT_INCOME
].join('\n');
const SITE = {
id: 'fivex', hubSite: 'fivex', netId: 'fivex', name: '5xYourTeam', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS,
intro: 'You are the assistant on 5xYourTeam (' + URL_ + '), The Draft: coaches buy a $' + PO.usd + ' one-time position and draft people who joined the network without a sponsor every week, then coach them through site messages.',
quickTopics: ['How does The Draft work?', 'Where does the $10 go?', 'When is the draft?', 'What is Downline Banners?']
};
function init() { return core.init(SITE); }
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
+219
View File
@@ -0,0 +1,219 @@
// The site assistant's engine (Marty 2026-11-15: a chatbot on every rebuilt network site), ported from LinkSpin's chatbot.js.
// The site's own chatbot.js holds what it knows (CANNED instant answers + FACTS, written from that site's code); this file
// holds how it answers, the same on every site:
// 1. the knowledge base's instant answers (kb.js, seeded from CANNED; first matching pattern wins, no AI call)
// 2. retrieval over the merged NETWORK knowledge base (this site's entries boosted, netkb.js), into the system prompt
// 3. OpenRouter (deepseek/deepseek-v4-flash:nitro, reasoning OFF, retried once), house rules in the prompt and on the way out
// Account problems go to the network support desk on InstantAdPay (handoff: true makes the widget offer it).
// Routes: POST /api/chat, GET /api/chat/kb-stamp, admin GET/POST /api/admin/kb, GET/PUT/DELETE /api/admin/kb/<id>,
// POST /api/admin/kb/test, GET /api/admin/kb/network (x-admin-token, the site's own isAdmin).
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
'use strict';
const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');
const kb = require('./kb');
const netkb = require('./netkb');
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
let S = null; // the site: { id, hubSite, name, url, dataDir, canned, faq, facts(), about, supportUrl, linkFor, quickTopics }
function key() {
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
if (!S || !S.dataDir) return '';
try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
}
const enabled = () => !!key();
// CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence)
function seeds() {
return S.canned.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re ? c.re.source : '',
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(S.faq || []);
}
const supportUrl = () => S.supportUrl || 'https://instantadpay.com/support';
// asking for a person, or one person's own account problem: every site's first CANNED entry uses this (handoff: true)
const SUPPORT_RE = /((contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|someone|a (human|person|real person))|real person|\bhuman\b|customer (service|support)|open a ticket|support (ticket|desk|team|email)|help ?desk|(my|the) (boost|purchase|payment|payout|order|account|sign.?in|log.?in|pro|upgrade|ad|banner|pick)s? (is |was |has |did |does )?(not|never|n.?t|missing|stuck|wrong|failed|broken|lost|gone)|(did ?n.?t|did not|never|has ?n.?t|have ?n.?t) (show|arriv|appear|receiv|get paid|go through|work|confirm)|i (was|got) (charged|scammed)|charged twice)/i;
const HOUSE_RULES = () => `RULES:
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page.
- Your main job is ${S.name}. Questions about another network site: answer from that site's knowledge-base entry, say which site it is about, and give that site's link exactly as the entry gives it. Never mix two sites' prices, splits or rules.
- NEVER promise or estimate income, and never state a maximum or total anyone can earn. This is advertising with a referral program, never an investment. Nobody earns unless real purchases happen in their line. Crypto payments are final.
- Whenever ad credits come up, say: Ad credits buy advertising, not income.
- Wallets: say "SafePal or any other crypto wallet". Never recommend MetaMask.
- Never mention RM Circle. It is not part of this network.
- No em dashes. If you do not know, say so plainly; never guess a price, a percentage or a rule.
- Anything about one person's own account (a missing payout, a sign-in that will not work, a purchase that did not show, a bug) you cannot look up: say so and send them to network support at ${supportUrl()}.`;
function networkLine() {
const list = netkb.sites();
if (!list.length) return '';
return '\nNETWORK SITES (one network account works across them; link to use for each):\n' + list.map(s => '- ' + s.name + ': ' + s.go).join('\n') + '\n';
}
function systemPrompt(kbBlock) {
return S.intro + '\n\nFACTS (checked against this site\'s code on ' + S.knowledgeDate + '):\n' + S.facts() + '\n' + networkLine() + '\n' + HOUSE_RULES() + (kbBlock ? '\n\n' + kbBlock : '');
}
function endpoint() {
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
}
function askOnce(message, historyText, kbBlock) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({
model: MODEL,
reasoning: { enabled: false }, // deepseek-v4-flash reasons by default and can spend the whole max_tokens on it (2026-10-16)
max_tokens: 320,
messages: [
{ role: 'system', content: systemPrompt(kbBlock) },
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + String(historyText).slice(0, 800) }] : []),
{ role: 'user', content: String(message).slice(0, 600) }
]
});
const ep = endpoint();
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
'HTTP-Referer': S.url, 'X-Title': S.name + ' assistant' }, timeout: 30000 },
res => {
let d = '';
res.on('data', c => { d += c; });
res.on('end', () => {
// OpenRouter can pad a slow upstream with keepalive lines before the JSON (IAP, 2026-09-17): find the object
const i = d.indexOf('{'); let txt = '';
try { txt = String(JSON.parse(i < 0 ? d : d.slice(i)).choices[0].message.content || '').trim(); }
catch (e) { return reject(new Error('openrouter ' + res.statusCode + ': ' + d.slice(0, 150))); }
if (!txt) return reject(new Error('openrouter ' + res.statusCode + ': empty content'));
resolve(txt);
});
});
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('openrouter timeout')));
req.end(body);
});
}
async function askAI(message, historyText, kbBlock) {
try { return await askOnce(message, historyText, kbBlock); }
catch (e) { await new Promise(r => setTimeout(r, 700)); return askOnce(message, historyText, kbBlock); } // one provider dropping it is the usual cause
}
// house rules on the way out, whatever the model wrote
const RMC_RE = /\brm ?circle\b|rmcircle/i;
function scrub(t) {
let s = String(t || '').replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ');
s = s.replace(/\*\*(.+?)\*\*/g, '$1').replace(/^#+\s*/gm, '');
s = s.replace(/\bMeta ?Mask\b(\s*(,|or|and)\s*)?/gi, '').replace(/\s{2,}/g, ' ').trim();
return s;
}
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) ?not (see|check|look)|contact support|network support|support desk|\/support\b)/i;
async function answer(message, historyText) {
const r = await answerRaw(message, historyText);
if (r && typeof r.reply === 'string') {
r.reply = scrub(r.reply);
if (RMC_RE.test(r.reply)) r.reply = 'I can only help with ' + S.name + ' and the network sites. For anything else, network support at ' + supportUrl() + ' can point you the right way.';
}
return r;
}
async function answerRaw(message, historyText) {
const msg = String(message || '').trim().slice(0, 600);
if (!msg) return { error: 'Say something first.' };
let hit = null, kbOk = true, other = [];
try {
await kb.load();
// a question about another network site (named, and this site not named) skips this site's instant answers, except a hand-off
other = kb.namesOther(msg, S.hubSite);
if (other.length && new RegExp('\\b' + S.name.replace(/[^A-Za-z0-9]+/g, '\\s*') + '\\b', 'i').test(msg)) other = [];
hit = await kb.fastPath(msg);
if (hit && other.length && !hit.handoff) hit = null;
} catch (e) { kbOk = false; console.error('kb fast path', e.message); }
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
let kbBlock = '', kbIds = [], hits = [];
try {
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
hits = await kb.context(query, 6);
kbBlock = kb.promptBlock(hits); kbIds = hits.map(h => h.entry.id);
} catch (e) { console.error('kb search', e.message); }
if (!enabled()) {
// no AI: the best matching entry, if it is a clear match, else the honest fallback
if (hits.length) { const e = hits[0].entry; return { reply: e.answer + (e.site ? ' More at ' + e.go : ''), kb: [e.id] }; }
return { reply: S.fallback || ('Good question. The quick answers I have cover how ' + S.name + ' works, what it costs and how payouts work. For anything else, network support at ' + supportUrl() + ' will help.'), handoff: true };
}
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
catch (e) {
console.error('chat AI failed', e.message);
if (hits.length) { const x = hits[0].entry; return { reply: x.answer + (x.site ? ' More at ' + x.go : ''), kb: [x.id] }; }
return { reply: 'I hit a snag answering that one, on our side. The live ledger at ' + S.url + '/ledger and the contract page at ' + S.url + '/contract cover most deep questions, or network support at ' + supportUrl() + ' will answer.', handoff: true };
}
}
// ---- rate limit: per visitor, in memory ----
const hits = new Map();
function limited(ip) {
const now = Date.now(); const h = hits.get(ip) || { m: 0, mAt: now, d: 0, dAt: now };
if (now - h.mAt > 60000) { h.m = 0; h.mAt = now; }
if (now - h.dAt > 86400000) { h.d = 0; h.dAt = now; }
h.m++; h.d++; hits.set(ip, h);
if (hits.size > 20000) hits.clear();
return h.m > 12 || h.d > 300;
}
const ipOf = req => String(req.headers['cf-connecting-ip'] || String(req.headers['x-forwarded-for'] || '').split(',')[0] || (req.socket && req.socket.remoteAddress) || 'x').trim();
// h: { json(res, code, obj, extra), readBody(req), isAdmin(req) }; returns true when it answered
async function handle(req, res, p, u, h) {
if (p === '/api/chat' && req.method === 'POST') {
if (limited(ipOf(req))) { h.json(res, 429, { error: 'Give it a minute, then ask again.' }); return true; }
const b = await h.readBody(req);
const hist = Array.isArray(b.history) ? b.history.map(x => String(x || '')).join(' ').slice(-800) : String(b.history || '').slice(-800);
const r = await answer(b.message, hist);
if (r.handoff) r.support = supportLink(b.message);
h.json(res, r.error ? 400 : 200, r); return true;
}
if (p === '/api/chat/config' && req.method === 'GET') { h.json(res, 200, { name: S.name, support: supportUrl(), topics: S.quickTopics || [] }, { 'Cache-Control': 'public, max-age=300' }); return true; }
if (p === '/api/chat/kb-stamp' && req.method === 'GET') { h.json(res, 200, Object.assign(await kb.stamp(), { knowledgeDate: S.knowledgeDate }), { 'Cache-Control': 'no-store' }); return true; }
if (!p.startsWith('/api/admin/kb')) return false;
if (!h.isAdmin(req)) { h.json(res, 401, { error: 'no' }); return true; }
if (p === '/api/admin/kb') {
if (req.method === 'GET') { h.json(res, 200, { entries: await kb.list(u.searchParams.get('q') || ''), stamp: await kb.stamp() }); return true; }
if (req.method === 'POST') { const r = await kb.create(await h.readBody(req)); h.json(res, r.error ? 400 : 200, r); return true; }
}
if (p === '/api/admin/kb/test' && req.method === 'POST') { const b = await h.readBody(req); h.json(res, 200, Object.assign(await kb.test(b.question), b.answer ? { answer: await answer(b.question) } : {})); return true; }
if (p === '/api/admin/kb/network' && req.method === 'GET') {
if (u.searchParams.get('refresh') === '1') await netkb.refresh();
if (u.searchParams.get('publish') === '1') await netkb.publish();
h.json(res, 200, Object.assign(netkb.view(), { ai: enabled(), model: MODEL })); return true;
}
const m = /^\/api\/admin\/kb\/([A-Za-z0-9._:-]{1,80})$/.exec(p);
if (m) {
if (req.method === 'GET') { const e = await kb.get(m[1]); h.json(res, e ? 200 : 404, e ? { entry: e } : { error: 'Entry not found.' }); return true; }
if (req.method === 'PUT') { const r = await kb.update(m[1], await h.readBody(req)); h.json(res, r.error ? (r.error === 'Entry not found.' ? 404 : 400) : 200, r); return true; }
if (req.method === 'DELETE') { const r = await kb.remove(m[1]); h.json(res, r.error ? 404 : 200, r); return true; }
}
h.json(res, 404, { error: 'Not found' }); return true;
}
// the support desk link the widget offers: InstantAdPay's public form, told which site and question it came from
function supportLink(q) {
const qs = new URLSearchParams({ from: S.id, subject: (S.name + ': ' + String(q || '').replace(/\s+/g, ' ').trim()).slice(0, 120) });
return supportUrl() + '?' + qs.toString();
}
// the link to another network site: its LinkSpin tracked link with ?src=<this site> (netsites.js), else its plain address
const hostOf = x => { try { return new URL(x).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
function linkVia(netId) {
return url => {
try {
const ns = require('./netsites'); const h = hostOf(url);
const m = ns.list().concat(ns.FALLBACK || []).find(s => hostOf(s.url) === h);
return (m && netId && m.id !== netId && ns.tracked(m.id, netId)) || url;
} catch (e) { return url; }
};
}
// site: see S above. Call after docstore.init (kb.json is a MySQL document there).
function init(site) {
S = site; if (!S.linkFor) S.linkFor = linkVia(S.netId);
const ready = kb.init({ dataDir: site.dataDir, seeds: seeds(), siteUrl: site.url, helpText: 'network support at ' + supportUrl() });
netkb.init({ dataDir: site.dataDir, site: site.hubSite, name: site.name, url: site.url, entries: () => kb.own(), linkFor: site.linkFor });
return ready;
}
module.exports = { init, handle, answer, enabled, seeds, systemPrompt, scrub, supportLink, linkVia, SUPPORT_RE, _limited: limited };
+289
View File
@@ -0,0 +1,289 @@
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
// The chatbot answers from maintained entries, and good support replies become entries.
//
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
// updated, created, edited, deleted, seedHash }
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
// path serves the new text.
// source canned | faq | ticket | admin
//
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
//
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
//
// Store: DATA_DIR/kb.json (written to a temp file and renamed), which docstore.js keeps in MySQL when DOCSTORE_URL is set
// (Marty's database rule). Ported from LinkSpin's kb.js (2026-11-15); keep the scoring and seed rules in step.
//
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's
// own entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries instead
// (NAMED_BOOST). Other sites' entries never take the instant-answer fast path: they only ride along as context, labelled
// with the site and the link to send people to. This site's own entries are published to the hub (netkb.publish).
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
let DATA_DIR = null, SEEDS = [], ready = null, SITE_URL = '', HELP_TEXT = '', MEMORY = false;
let cache = null, cacheAt = 0, index = null;
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
function stem(w) {
if (SYN[w]) return SYN[w];
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
return w;
}
function words(text) {
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
}
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
function terms(text) {
const w = words(text), out = w.slice();
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
return out;
}
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
const K1 = 1.2, B = 0.75;
function fieldText(e, f) {
if (f === 'questions') return (e.questions || []).join(' . ');
if (f === 'tags') return (e.tags || []).join(' . ');
return e[f] || '';
}
function buildIndex(entries) {
const docs = entries.map(e => {
const d = { e, f: {} };
for (const f of Object.keys(FIELDS)) {
const t = terms(fieldText(e, f)), tf = new Map();
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
d.f[f] = { tf, len: t.length };
}
return d;
});
const df = new Map(), avg = {};
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
for (const d of docs) {
const seen = new Set();
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
}
return { docs, df, avg, n: docs.length };
}
const HOME_BOOST = 2, NAMED_BOOST = 3;
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
function namedSites(query, idx) {
const q = norm(query); const out = new Set();
for (const s of (idx && idx.sites) || []) {
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
}
return out;
}
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside and the
// answer comes from retrieval over the whole network (a "how much" about another site must not get this site's price).
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
function namesOther(query, self) {
const q = norm(query); const out = [];
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
for (const id of ids) {
if (id === self) continue;
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
}
return out;
}
function rank(idx, query, k) {
if (!idx || !idx.n) return [];
const qt = [...new Set(terms(query))];
if (!qt.length) return [];
const named = namedSites(query, idx);
const out = [];
for (const d of idx.docs) {
let s = 0;
for (const t of qt) {
const n = idx.df.get(t); if (!n) continue;
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
for (const f of Object.keys(FIELDS)) {
const tf = d.f[f].tf.get(t); if (!tf) continue;
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
}
}
if (s > 0 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
}
out.sort((a, b) => b.score - a.score);
return out.slice(0, k || 5);
}
// keep hits that are close to the best one, and only when the best is a real match
const MIN_SCORE = 3;
function relevant(hits) {
if (!hits.length || hits[0].score < MIN_SCORE) return [];
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
return hits.filter(h => h.score >= floor);
}
// ---------------------------------------------------------------- store
const mem = { entries: [] }; // a site with no data volume (Stack POL): seeds in memory only
const J = {
file: () => path.join(DATA_DIR, 'kb.json'),
async ensure() {},
async all() { if (MEMORY) return mem.entries.slice(); try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
async put(e) {
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
if (i >= 0) all[i] = e; else all.push(e);
if (MEMORY) { mem.entries = all; return; }
const tmp = J.file() + '.tmp';
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
fs.renameSync(tmp, J.file());
}
};
const store = () => J;
// ---------------------------------------------------------------- seeds
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
function seedEntry(s) {
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
order: s.order == null ? null : s.order, source: s.source || 'faq' };
}
async function syncSeeds() {
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
const seedIds = new Set(SEEDS.map(s => s.id));
let added = 0, refreshed = 0, retired = 0;
for (const s of SEEDS) {
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
}
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
}
// opts: { dataDir (null = memory only), seeds, siteUrl, helpText (where a member gets a person) }
function init(opts) {
DATA_DIR = opts.dataDir || null; MEMORY = !DATA_DIR; SEEDS = opts.seeds || []; cache = null; index = null; mem.entries = [];
SITE_URL = String(opts.siteUrl || '').replace(/\/+$/, ''); HELP_TEXT = opts.helpText || 'network support at https://instantadpay.com/support';
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
return ready;
}
// this site's own entries, for netkb.publish
async function own() { await load(); return cache.slice(); }
async function load(force) {
if (ready) await ready;
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
const all = await store().all();
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear();
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
return cache;
}
const rx = new Map();
function compiled(src) {
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
return rx.get(src);
}
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
// ---------------------------------------------------------------- the chatbot side
async function fastPath(msg) {
const list = (await load()).filter(e => e.pattern).sort(byOrder);
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
return null;
}
async function search(query, k) { await load(); return rank(index, query, k || 5); }
async function context(query, k) { return relevant(await search(query, k || 6)); }
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
function promptBlock(hits) {
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP_TEXT + '.';
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + label(h.entry) + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
}
// ---------------------------------------------------------------- the admin side
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
function validate(o, cur) {
o = o || {};
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
const answer = clean(o.answer).slice(0, 4000);
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
if (!title) return { error: 'Give the entry a title or at least one question.' };
if (!answer) return { error: 'The answer is empty.' };
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
}
async function list(q) {
const all = (await load(true)).slice();
if (!q) return all.sort((a, b) => b.updated - a.updated);
const ranked = rank(index, q, 50).filter(h => !h.entry.site).map(h => Object.assign({ score: h.score }, h.entry));
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
return ranked.concat(plain);
}
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
async function create(o) {
const v = validate(o); if (v.error) return v;
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
return { ok: true, entry: e };
}
async function update(id, o) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
const v = validate(o, cur); if (v.error) return v;
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
return { ok: true, entry: e };
}
async function remove(id) {
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); if (netkb) netkb.publishSoon();
return { ok: true };
}
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
// KNOWLEDGE_DATE already speaks for the code.
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
async function stamp() {
const all = await load();
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
return { updated: max ? ctDay(max) : '', count: all.length };
}
async function test(question) {
const fast = await fastPath(String(question || ''));
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
}
module.exports = { init, load, own, namesOther, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };
+105
View File
@@ -0,0 +1,105 @@
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
// Banners, Stack POL). Keep them identical.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const REFRESH_MS = 10 * 60 * 1000;
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
const secret = () => String(process.env.HUB_SECRET || '').trim();
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
async function call(method, route, body, headers) {
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
return { status: r.status, body: j };
}
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
async function publish() {
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
const body = { name: O.name, url: O.url, entries };
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
if (h === publishedHash) return { same: true };
try {
const r = await call('PUT', '/v1/kb', body);
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
return r.body;
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
}
// an admin edit: publish a few seconds later (several quick edits go as one)
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
function readCache() {
const f = cacheFile(); if (!f) return;
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
}
function writeCache() {
const f = cacheFile(); if (!f) return;
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
}
async function refresh() {
if (!enabled()) return { skipped: true };
try {
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
stats.lastReadAt = Date.now();
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
writeCache();
return { version: merged.version, count: merged.entries.length };
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
}
// other sites' entries, ready for the chatbot's index: id "<site>:<id>", plus where they come from and the link to send people to
function remote() {
const me = siteName(); const out = [];
for (const e of merged.entries || []) {
if (!e || e.site === me) continue;
const s = (merged.sites || {})[e.site] || {};
const url = s.url || e.link || '';
out.push({ id: e.site + ':' + e.id, title: e.title, questions: e.questions || [], answer: e.answer, tags: e.tags || [],
site: e.site, siteName: s.name || e.site, siteUrl: url, go: (O && typeof O.linkFor === 'function' && url ? O.linkFor(url) : '') || url });
}
return out;
}
// the network's sites as the hub knows them (name, link), this one left out
function sites() {
const me = siteName();
return Object.entries(merged.sites || {}).filter(([k]) => k !== me).map(([k, s]) => ({ site: k, name: s.name || k, url: s.url || '', go: (O && typeof O.linkFor === 'function' && s.url ? O.linkFor(s.url) : '') || s.url || '', count: s.count || 0 }));
}
// opts: { dataDir, site (hub site id), name, url, entries: async () => [...], linkFor: url => tracked link }
function init(opts) {
O = opts || {}; readCache();
if (!enabled()) return;
const first = setTimeout(async () => { await publish().catch(() => {}); await refresh().catch(() => {}); }, Math.max(0, Number(process.env.NETKB_FIRST_MS) || 8000));
if (first.unref) first.unref();
timer = setInterval(async () => { await refresh().catch(() => {}); if (!publishedHash) await publish().catch(() => {}); }, Math.max(1000, Number(process.env.NETKB_REFRESH_MS) || REFRESH_MS));
if (timer.unref) timer.unref();
}
function view() { return Object.assign({ enabled: enabled(), site: siteName(), version: merged.version, sites: Object.keys(merged.sites || {}), entries: (merged.entries || []).length, remote: remote().length, loadedAt }, stats); }
function _set(m) { merged = m; } // tests
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, _set };
+1
View File
@@ -30,5 +30,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+37
View File
@@ -0,0 +1,37 @@
/* Site assistant widget, 5xYourTeam look (fx.css): draft night. Stadium navy panel, gold rule and accents, red week tag on the
title, white scouting-card bubbles with navy ink, Oswald headings. Fallbacks match fx.css. */
#scChat{--sc-bg:var(--panel,#13214a);--sc-ink:var(--ink,#eef2fb);--sc-sub:var(--muted,#b8c4e0);--sc-head:var(--bar,#07102a);--sc-head-ink:var(--ink,#eef2fb);
--sc-accent:var(--gold,#ffc93c);--sc-accent-ink:var(--paperInk,#0b1530);--sc-me:var(--gold,#ffc93c);--sc-me-ink:var(--paperInk,#0b1530);
--sc-bot:var(--paper,#fff);--sc-bot-ink:var(--paperInk,#0b1530);--sc-line:var(--line,#2a3a6e);--sc-red:var(--red,#ff4d4d);
--sc-font:var(--text,Inter,system-ui,sans-serif);--sc-disp:var(--disp,Oswald,Impact,'Arial Narrow',sans-serif);
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
#scBtn{width:58px;height:58px;border-radius:12px;border:2px solid var(--sc-accent);cursor:pointer;background:var(--sc-head);color:var(--sc-accent);display:flex;align-items:center;justify-content:center;
box-shadow:0 8px 22px rgba(0,0,0,.45)}
#scBtn:hover{background:var(--sc-accent);color:var(--sc-accent-ink)}
#scBtn:focus-visible{outline:3px solid var(--sc-red);outline-offset:3px}
#scPanel{position:absolute;right:0;bottom:72px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column;
background:var(--sc-bg);color:var(--sc-ink);border:1px solid var(--sc-line);border-radius:12px;box-shadow:0 18px 48px rgba(0,0,0,.5);overflow:hidden}
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--sc-head);color:var(--sc-head-ink);border-bottom:3px solid var(--sc-accent)}
.sc-head>div{flex:1;min-width:0}
.sc-title{display:block;font-family:var(--sc-disp);font-weight:700;font-size:20px;letter-spacing:.04em;text-transform:uppercase}
.sc-title::before{content:"24/7";display:inline-block;background:var(--sc-red);color:#fff;font:700 10px/1 var(--sc-font);letter-spacing:.08em;padding:4px 6px;border-radius:3px;margin-right:8px;vertical-align:4px}
.sc-sub{display:block;font-size:12.5px;color:var(--sc-sub)}
#scClose{background:transparent;border:0;color:inherit;font-size:26px;line-height:1;cursor:pointer;padding:0 2px}
.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:9px}
.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;border-radius:10px;overflow-wrap:anywhere}
.sc-m.bot{align-self:flex-start;background:var(--sc-bot);color:var(--sc-bot-ink);border-top:4px solid var(--sc-head);border-radius:6px 10px 10px 10px}
.sc-m.me{align-self:flex-end;background:var(--sc-me);color:var(--sc-me-ink);font-weight:600}
.sc-m a{color:inherit;text-decoration:underline}
.sc-m.bot a{color:#1d47c9}
.sc-m.wait{opacity:.6}
.sc-cta{display:inline-block;background:var(--sc-accent);color:var(--sc-accent-ink)!important;text-decoration:none!important;font-weight:700;padding:8px 14px;border-radius:8px;font-family:var(--sc-disp);text-transform:uppercase;letter-spacing:.04em}
.sc-handoff{background:transparent!important;border:0!important;padding:0!important}
.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px}
.sc-topics button{background:transparent;color:var(--sc-accent);border:1px solid var(--sc-accent);border-radius:999px;font:600 12.5px var(--sc-font);padding:5px 11px;cursor:pointer}
.sc-topics button:hover{background:var(--sc-accent);color:var(--sc-accent-ink)}
.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line);background:var(--panel2,#1b2c5e)}
.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);border-radius:8px;padding:10px 12px;font:15px var(--sc-font);color:var(--sc-bot-ink);background:#fff}
.sc-input input:focus{outline:2px solid var(--sc-accent);outline-offset:-1px}
.sc-input button{background:var(--sc-accent);color:var(--sc-accent-ink);border:0;border-radius:8px;font:700 15px var(--sc-disp);text-transform:uppercase;letter-spacing:.04em;padding:0 16px;cursor:pointer}
.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:6px 0 10px;background:var(--panel2,#1b2c5e)}
@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:64px;height:calc(100vh - 100px)}}
+72
View File
@@ -0,0 +1,72 @@
// Site assistant widget (2026-11-15): a round button bottom right, a panel that asks /api/chat. The look is this site's own,
// in /assets/chat.css (colors and fonts from the site's stylesheet). When an answer cannot help, or the visitor asks for a
// person, it offers "Open network support": InstantAdPay's support desk, which already knows the question and the site.
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
(function () {
if (window.__siteChat || /^\/admin/.test(location.pathname)) return;
window.__siteChat = 1;
var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/assets/chat.css?v=20261115c'; document.head.appendChild(css);
var NAME = 'this site', TOPICS = [];
var root = document.createElement('div'); root.id = 'scChat';
root.innerHTML = '<button id="scBtn" type="button" aria-label="Ask a question" aria-expanded="false">'
+ '<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true"><path fill="currentColor" d="M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-5 4v-4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm3 6.5a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01z"/></svg></button>'
+ '<section id="scPanel" role="dialog" aria-label="Questions" hidden>'
+ '<header class="sc-head"><div><b class="sc-title" id="scTitle">Ask a question</b><span class="sc-sub">Straight answers about this site and the network</span></div>'
+ '<button id="scClose" type="button" aria-label="Close">&times;</button></header>'
+ '<div class="sc-msgs" id="scMsgs" aria-live="polite"></div>'
+ '<div class="sc-topics" id="scTopics"></div>'
+ '<form class="sc-input" id="scForm"><input id="scIn" autocomplete="off" maxlength="600" placeholder="Type your question" aria-label="Your question">'
+ '<button type="submit" id="scSend">Send</button></form>'
+ '<a class="sc-human" id="scHuman" href="https://instantadpay.com/support" target="_blank" rel="noopener">Need a person? Open network support</a>'
+ '</section>';
document.body.appendChild(root);
var $ = function (id) { return document.getElementById(id); };
var msgs = $('scMsgs'), input = $('scIn'), panel = $('scPanel'), btn = $('scBtn');
var history = [], greeted = false, support = 'https://instantadpay.com/support';
fetch('/api/chat/config').then(function (r) { return r.json(); }).then(function (c) {
if (c.name) { NAME = c.name; $('scTitle').textContent = 'Ask ' + c.name; }
if (c.support) { support = c.support; $('scHuman').href = c.support; }
TOPICS = c.topics || [];
}).catch(function () {});
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
function add(text, who) {
var d = document.createElement('div'); d.className = 'sc-m ' + who;
d.innerHTML = esc(text).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)])/g, '<a href="$1" target="_blank" rel="noopener">$1</a>');
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; return d;
}
function offer(link) {
var old = msgs.querySelector('.sc-handoff'); if (old) old.remove();
var d = document.createElement('div'); d.className = 'sc-m bot sc-handoff';
var a = document.createElement('a'); a.className = 'sc-cta'; a.href = link || support; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open network support';
d.appendChild(a); msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
function open() {
panel.hidden = false; btn.setAttribute('aria-expanded', 'true'); root.className = 'open';
if (!greeted) {
greeted = true;
add('Hi. Ask me how ' + NAME + ' works, what it costs, how payouts work, or about any other site in the network. Straight answers, no income hype.', 'bot');
var t = $('scTopics'); TOPICS.slice(0, 4).forEach(function (q) {
var b = document.createElement('button'); b.type = 'button'; b.textContent = q; b.addEventListener('click', function () { input.value = q; send(); }); t.appendChild(b);
});
}
setTimeout(function () { input.focus(); }, 50);
}
function close() { panel.hidden = true; btn.setAttribute('aria-expanded', 'false'); root.className = ''; }
btn.addEventListener('click', function () { panel.hidden ? open() : close(); });
$('scClose').addEventListener('click', close);
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !panel.hidden) close(); });
async function send() {
var q = input.value.trim(); if (!q) return;
input.value = ''; $('scTopics').innerHTML = '';
add(q, 'me'); var wait = add('...', 'bot wait');
try {
var r = await (await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: q, history: history.slice(-6) }) })).json();
wait.remove();
add(r.reply || r.error || 'Something went wrong. Try again in a moment.', 'bot');
history.push(q, r.reply || '');
if (r.handoff) offer(r.support);
} catch (e) { wait.remove(); add('I could not reach the assistant just now. Try again in a moment, or open network support.', 'bot'); offer(); }
}
$('scForm').addEventListener('submit', function (e) { e.preventDefault(); send(); });
})();
+1
View File
@@ -31,5 +31,6 @@
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -30,5 +30,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/cards.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -29,5 +29,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/coach.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -28,5 +28,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/contract.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -32,5 +32,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -57,5 +57,6 @@
<script src="https://polhunter.com/embed.js" data-slots="3" data-selector=".how .s" async></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/board.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -37,5 +37,6 @@
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=3"></script>
<script src="/assets/join.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -30,5 +30,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/ledger.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -34,5 +34,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -31,5 +31,6 @@
<script src="/assets/common.js?v=3"></script>
<script src="/assets/kitpage.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -55,5 +55,6 @@
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=3"></script>
<script src="/assets/team.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+1
View File
@@ -39,5 +39,6 @@
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/misc.js?v=3"></script>
<script src="/assets/chat.js?v=1" defer></script>
</body>
</html>
+22
View File
@@ -0,0 +1,22 @@
{
"site": "fivex",
"home": [
{ "q": "What is 5xYourTeam?", "kb": "about", "must": ["draft", "\\$10", "Monday"] },
{ "q": "How much is a position and what do I get?", "kb": "position", "must": ["\\$10", "5 instant picks", "never a subscription"] },
{ "q": "Where does the $10 go?", "kb": "split", "must": ["25%", "5%", "10%", "45%"] },
{ "q": "When is the draft?", "kb": "draft", "must": ["Monday at 7 PM Central", "5 rounds", "auto-picked"] },
{ "q": "How is draft order decided?", "kb": "order", "must": ["earned", "started"] },
{ "q": "What happens to a pick that does not start?", "kb": "picks", "must": ["3 days", "48 hours"] },
{ "q": "Do I get my picks' email addresses?", "kb": "picks", "must": ["never get their email", "site messages"] },
{ "q": "How is the Best Coach pot shared?", "kb": "pot", "must": ["10%", "50/30/20", "not promised"] },
{ "q": "How do I withdraw my earnings?", "kb": "withdraw", "must": ["nothing to withdraw"] },
{ "q": "Is this a pyramid scheme?", "kb": "safe", "must": ["contract", "not income"] }
],
"cross": [
{ "q": "How much is Pro on DownlineHydra?", "site": "downlinehydra" },
{ "q": "What is a ViralAdBlitz Boost?", "site": "viraladblitz" },
{ "q": "How do Downline Banners spots work?", "site": "bannerline" },
{ "q": "What is a LinkSpin spin link?", "site": "linkspin" },
{ "q": "What are InstantAdPay ad packages?", "site": "iap" }
]
}
+87
View File
@@ -0,0 +1,87 @@
// Site assistant checks (2026-11-15): node qa/chatbot.test.mjs
// No network: a stand-in OpenRouter and a stand-in hub. Checks the instant answers route every example question to its own entry,
// the house rules (no em dashes, no MetaMask, never RM Circle, ad-credits line where credits come up, no income promises),
// the network merge (home boosted, a named site boosted), the support hand-off, and the site's scripted Q&A (qa/chat-qa.json:
// home questions must land on the named entry and contain the expected facts).
// The SAME file ships in every rebuilt network site.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'chat-'));
process.env.DATA_DIR = DIR; delete process.env.DOCSTORE_URL; process.env.NETKB = '0'; delete process.env.OPENROUTER_API_KEY;
let pass = 0, fail = 0; const bad = [];
const ok = (c, m) => { if (c) pass++; else { fail++; bad.push(m); console.log('FAIL', m); } };
// stand-in OpenRouter: answers with what the system prompt says about the first KB entry, so we can see the prompt
let lastPrompt = '', reply = 'Fine.';
const or = http.createServer((req, res) => { let b = ''; req.on('data', c => { b += c; }); req.on('end', () => {
const j = JSON.parse(b); lastPrompt = j.messages[0].content; ok(j.reasoning && j.reasoning.enabled === false, 'reasoning is switched off');
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('\n\n' + JSON.stringify({ choices: [{ message: { content: reply } }] })); }); });
await new Promise(r => or.listen(0, r));
process.env.OPENROUTER_URL = 'http://127.0.0.1:' + or.address().port + '/v1/chat/completions';
const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset();
const bot = require(path.join(ROOT, 'chatbot.js'));
const core = require(path.join(ROOT, 'chatcore.js'));
const kb = require(path.join(ROOT, 'kb.js'));
const netkb = require(path.join(ROOT, 'netkb.js'));
const dataDir = bot.SITE.dataDir;
await bot.init();
// 1. seeds and the fast path: every example question of a canned entry lands on that entry (first match wins)
const seeds = core.seeds();
ok(seeds.length >= 12, 'at least 12 seeded entries (' + seeds.length + ')');
for (const c of bot.CANNED) {
ok(c.re instanceof RegExp, c.id + ' has a pattern');
for (const q of c.q || []) { const hit = await kb.fastPath(q); ok(hit && hit.id === 'c-' + c.id, 'example "' + q + '" -> ' + c.id + ' (got ' + (hit && hit.id) + ')'); }
}
// 2. house rules in every seeded answer
for (const s of seeds) {
ok(!/[—―]/.test(s.answer + s.title), s.id + ': no em dashes');
ok(!/metamask/i.test(s.answer), s.id + ': never recommends MetaMask');
ok(!/rm ?circle/i.test(s.answer), s.id + ': never RM Circle');
ok(!/(guarantee[ds]? (income|earnings|profit)|you will (earn|make)|passive income|get rich|up to \$?\d[\d,.]* (a|per) (day|week|month))/i.test(s.answer), s.id + ': no income promise');
if (/\bad credits?\b/i.test(s.answer)) ok(/Ad credits buy advertising, not income\./.test(s.answer), s.id + ': ad credits line');
if (/wallet/i.test(s.answer) && /(which|use|recommend)/i.test(s.answer) && /safepal/i.test(s.answer)) ok(/SafePal or any other crypto wallet/i.test(s.answer), s.id + ': wallet wording');
}
// 3. the engine: scrub, support hand-off, the AI path
ok(core.scrub('A — B, use MetaMask or SafePal') === 'A, B, use SafePal', 'scrub: em dash and MetaMask (' + core.scrub('A — B, use MetaMask or SafePal') + ')');
{ const r = await bot.answer('I need to talk to a real person about my account'); ok(r.handoff === true, 'asking for a person hands off'); }
{ const r = await bot.answer(''); ok(!!r.error, 'empty question refused'); }
fs.writeFileSync(path.join(dataDir || DIR, 'openrouter.key'), 'test-key');
reply = 'Sure — try RM Circle'; { const r = await bot.answer('zzqx unrelated words nobody wrote down'); ok(!/rm ?circle/i.test(r.reply) && !/—/.test(r.reply), 'an RM Circle or em dash reply never leaves (' + r.reply + ')'); }
ok(/NEVER promise or estimate income/.test(lastPrompt) && /SafePal or any other crypto wallet/.test(lastPrompt) && /Ad credits buy advertising, not income\./.test(lastPrompt), 'house rules in the system prompt');
reply = 'Fine.';
// 4. the network merge: home boosted, a named site boosted, labelled with the site and its link
const GENERAL = bot.CANNED.find(c => !['support', 'refund', 'about'].includes(c.id) && (c.q || []).length).q[0].replace(/\?$/, '');
netkb._set({ version: 'v1', sites: { othersite: { name: 'Other Site', url: 'https://other.example', count: 1 }, [process.env.HUB_SITE || bot.SITE.hubSite]: { name: bot.SITE.name, url: bot.SITE.url } },
entries: [{ site: 'othersite', id: 'about', title: 'What is Other Site?', questions: ['What is Other Site?', GENERAL + ' on Other Site'], answer: 'Other Site is a test site with its own rules.', tags: ['test'] }] });
await kb.load(true);
{ const hits = await kb.search(GENERAL, 8); const top = hits[0] && hits[0].entry; ok(top && !top.site, 'home entries first for a general question (top ' + (top && top.id) + ')'); }
{ const hits = await kb.search(GENERAL + ' on Other Site', 8); const top = hits[0] && hits[0].entry; ok(top && top.site === 'othersite', 'a named site boosts its own entry (top ' + (top && top.id) + ')'); }
{ const block = kb.promptBlock(await kb.context('What is Other Site', 6)); ok(/about Other Site, another network site; send people to https:\/\/other\.example/.test(block), 'remote entry labelled with site and link'); }
{ const fp = await kb.fastPath('What is Other Site?'); ok(!fp || !String(fp.id).startsWith('othersite:'), 'other sites never take the fast path'); }
{ const r = await bot.answer(GENERAL + ' on Other Site'); ok(!r.canned, 'a question naming another site skips this site\'s instant answers (' + r.kb + ')'); }
{ const r = await bot.answer('I need a real person, my order on Other Site failed'); ok(r.handoff === true, 'a hand-off still wins when another site is named'); }
{ const r = await bot.answer(bot.CANNED.find(c => c.id === 'about').q[0]); ok(r.canned && r.kb === 'c-about', 'this site\'s own name keeps the instant answer'); }
{ const own = await kb.own(); ok(own.length === seeds.length && own.every(e => !e.site), 'publish set = this site\'s own entries only'); }
// 5. the scripted Q&A (home questions)
const qaFile = path.join(ROOT, 'qa', 'chat-qa.json');
if (fs.existsSync(qaFile)) {
const qa = JSON.parse(fs.readFileSync(qaFile, 'utf8'));
for (const t of qa.home || []) {
const r = await bot.answer(t.q);
if (t.kb) ok(r.kb === 'c-' + t.kb || (Array.isArray(r.kb) && r.kb.includes('c-' + t.kb)), 'Q&A "' + t.q + '" -> ' + t.kb + ' (got ' + JSON.stringify(r.kb) + ')');
for (const m of t.must || []) ok(new RegExp(m, 'i').test(r.reply) || new RegExp(m, 'i').test(lastPrompt), 'Q&A "' + t.q + '" mentions /' + m + '/');
}
}
or.close();
console.log((fail ? 'FAILED ' : 'ok ') + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 439 KiB

After

Width:  |  Height:  |  Size: 341 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 290 KiB

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 683 KiB

After

Width:  |  Height:  |  Size: 666 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 KiB

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 562 KiB

After

Width:  |  Height:  |  Size: 456 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 195 KiB

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 454 KiB

After

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 481 KiB

After

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 KiB

After

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 492 KiB

After

Width:  |  Height:  |  Size: 474 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 238 KiB

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 525 KiB

After

Width:  |  Height:  |  Size: 413 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 188 KiB

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 KiB

After

Width:  |  Height:  |  Size: 275 KiB

+1 -1
View File
@@ -1 +1 @@
2026-11-15T13:45:12.044Z 156 passed, 0 failed
2026-11-15T18:52:47.772Z 160 passed, 0 failed
+9 -1
View File
@@ -114,7 +114,7 @@ listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), t
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', ALLOW_TEST_CLOCK: '1', TANK_MODE: 'stub',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0', DRAFT_TICK_MS: '200', DRAFT_PICK_SECONDS: '300',
CONTRACT_ADDRESS: SHOP, PRIZE_WALLET: PRIZE, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'fivex', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
HUB_ENABLED: '1', NETKB: '0', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'fivex', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
TG_LIVE: '1', TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT, OWNER_USERNAME: 'coachann' });
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
@@ -185,6 +185,14 @@ async function main() {
let r = await anon.req('/team'); ok(r.headers.get('x-frame-options') === 'DENY', '/team is never framed');
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the draft board/.test(await r.text()), 'an unknown coach name: 404');
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
// the site assistant (2026-11-15): widget on every page, canned answers without AI, account problems hand off, admin KB behind the token
{ const home = await (await anon.req('/')).text();
ok(/<script src="\/assets\/chat\.js\?v=\d+" defer><\/script>/.test(home) && /polhunter\.com/.test(home) && (await anon.req('/assets/chat.js')).status === 200 && (await anon.req('/assets/chat.css')).status === 200, 'chat widget on the page (PolHunter embed kept), its script and styles served'); }
{ const cr = await anon.req('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Where does the $10 go?' }) }); const cj = await cr.json();
ok(cr.status === 200 && cj.canned && /25%/.test(cj.reply) && /45%/.test(cj.reply), 'chat: canned split answer', cj); }
{ const cr = await anon.req('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'my position did not show up' }) }); const cj = await cr.json();
ok(cj.handoff === true && /^https:\/\/instantadpay\.com\/support\?from=fivex/.test(cj.support || ''), 'chat: account problem hands off to network support', cj); }
ok((await anon.req('/api/admin/kb')).status === 401, 'admin KB needs the token');
let b = await anon.json('/api/board');
ok(b.poolSize === 29 && b.pool.length === 24 && b.pool.every(p => p.gameWei === undefined && p.surfWei === undefined), 'the pool (stub tank: 29 draftable of 35); visitors see scouting facts but no earnings', { size: b.poolSize, keys: Object.keys(b.pool[0]) });
ok(!b.pool.some(p => /lockedlarry|hasasponsor|xx_spam_xx|temp_mail_9|brandnew|twiceadopted/.test(p.username)), 'never locked, sponsored, spam, throwaway, inside the grace or adopted twice', b.pool.map(p => p.username));
+3
View File
@@ -24,6 +24,7 @@ const tank = require('./tankpool');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit');
const chatbot = require('./chatbot'); // the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js)
const hubreport = require('./hubreport');
const hubpeople = require('./hubpeople');
const hubline = require('./hubline');
@@ -211,6 +212,7 @@ const server = http.createServer(async (req, res) => {
try {
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files', tank: C.tankMode });
@@ -459,6 +461,7 @@ const server = http.createServer(async (req, res) => {
shop.init(C);
const loop = () => league.tick().catch(e => console.error('league tick', e.message)).finally(() => setTimeout(loop, C.draft.tickMs).unref());
setTimeout(loop, 300).unref();
chatbot.init(); // after docstore.init: kb.json is a MySQL document
server.listen(C.port, () => console.log('5xYourTeam on :' + C.port + ', position $' + C.position.usd + ', tank ' + C.tankMode + ', store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
process.on('SIGINT', () => { store.flush(); process.exit(0); });
+2 -2
View File
@@ -8,7 +8,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
const PUB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
const SITE = 'https://5xyourteam.com';
const V = { css: 3, js: 3 };
const V = { css: 3, js: 3, chat: 1 }; // chat: the site assistant widget (2026-11-15)
const F = { co: 'TrustClickz', addr: '615 Green Valley Drive, Moody, AL 35004', updated: 'November 15, 2026', usd: 10, picks: 5, rounds: 5, returnDays: 3, maxOpen: 10 };
const FONTS = 'https://fonts.googleapis.com/css2?family=Oswald:wght@500;700&family=Inter:wght@400;600;700&display=swap';
const NOTE = 'A position buys a draft spot and coaching tools, not income. Nothing is promised.';
@@ -41,7 +41,7 @@ ${o.noindex ? '<meta name="robots" content="noindex">' : `<link rel="canonical"
<body${o.data ? ' data-page="' + o.data + '"' : ''}>
`;
}
const tail = scripts => ['common.js'].concat(scripts).map(s => '<script src="/assets/' + s + '?v=' + V.js + '"></script>').join('\n') + '\n</body>\n</html>\n';
const tail = scripts => ['common.js'].concat(scripts).map(s => '<script src="/assets/' + s + '?v=' + V.js + '"></script>').join('\n') + '\n<script src="/assets/chat.js?v=' + V.chat + '" defer></script>' + '\n</body>\n</html>\n';
const page = (file, o, body, scripts) => fs.writeFileSync(path.join(PUB, file), head(o) + body + tail(scripts));
const STATUS = '<p id="status" class="note" hidden></p>';