Site assistant (Marty 2026-11-15): chat widget in the Stack POL look on every page, CANNED + FACTS from this repo (the on-page FAQ, programs.js, the 5-minute indexer, opt-in member pages, holds nothing, no income promise), retrieval over the shared network knowledge base on the hub (netkb.js as hub site stackpol; another site named = its answer, with its tracked LinkSpin link), reasoning off, account problems hand off to network support. Static server now serves .js/.css; Dockerfile copies the chat modules. chatbot.test 125 pass
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js ./
|
||||
COPY package.json package-lock.json server.js layout.js blog.js programs.js netsites.js chatbot.js chatcore.js kb.js netkb.js ./
|
||||
RUN npm ci --omit=dev --no-audit --no-fund
|
||||
COPY content/ ./content/
|
||||
COPY public/ ./public/
|
||||
|
||||
@@ -8,3 +8,4 @@ stackpol.com: every POL payout across the network, stacked. Live app since 2026-
|
||||
- programs.js: program registry (keys match the indexer); game blurbs are InstantAdPay's own.
|
||||
- mockup/: the Oct design mockup (artifact https://claude.ai/artifact/1mN4dCYUcbw7EHicCdejM3).
|
||||
- Standing rule (Marty 2026-11-15): every rebuilt network site is added here when it goes live: a programs.js entry, its /earn/<slug> page (automatic from the entry, plus public/img/<key>.jpg 800x420) and an indexer source for its member payouts (house/company wallets excluded). ViralAdBlitz, 5xYourTeam and DownlineHydra added 2026-11-15.
|
||||
- Site assistant (2026-11-15): chat widget on every page (`public/assets/chat.js` + `chat.css`, loaded from layout.js). `chatbot.js` holds what it knows (CANNED + FACTS from this repo); `chatcore.js`, `kb.js` (memory only here: no database, no volume) and `netkb.js` (the shared network knowledge on the hub, signed as `HUB_SITE=stackpol` with `HUB_SECRET`) are the same files as the rebuilt sites. OpenRouter key: Coolify env `OPENROUTER_API_KEY`. No admin KB editing on Stack POL. Test: `node qa/chatbot.test.mjs`.
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// Stack POL'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.
|
||||
// Stack POL has no database and no data volume: its own entries live in memory (seeded from this file at boot), and the
|
||||
// OpenRouter key comes from the OPENROUTER_API_KEY env (a Coolify secret). No admin knowledge-base editing here.
|
||||
//
|
||||
// Every fact below was checked against this repo on KNOWLEDGE_DATE: server.js (the on-page FAQ, the pages, /api/totals, member
|
||||
// stacks only when switched on), programs.js (the programs and their kinds), README.md (the indexer refreshes every 5 minutes;
|
||||
// members are named only when opted in). Stack POL sells nothing and holds nothing.
|
||||
// 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, never quote totals as what someone will earn, never RM Circle.
|
||||
'use strict';
|
||||
const core = require('./chatcore');
|
||||
const { PROGRAMS } = require('./programs');
|
||||
|
||||
const KNOWLEDGE_DATE = '2026-11-15';
|
||||
const URL_ = String(process.env.SITE_URL || 'https://stackpol.com').replace(/\/+$/, '');
|
||||
const SUPPORT = 'https://instantadpay.com/support';
|
||||
const NAMES = PROGRAMS.map(p => p.n).join(', ');
|
||||
const NOT_INCOME = 'No promise of income is made: the totals are what the whole network has paid so far, and many members earn little or nothing.';
|
||||
|
||||
const CANNED = [
|
||||
{ id: 'support', title: 'Talk to a person, or a problem with my account', q: ['How do I contact support?', 'My payout is not on the ledger', 'I need a real person'], tags: ['support', 'help', 'ticket', 'problem'],
|
||||
re: core.SUPPORT_RE, handoff: true,
|
||||
a: 'Network support handles every network site: open ' + SUPPORT + ', say which program it is about, and include your username, your wallet address and the transaction link if you have one. Marty answers there and by email. Tap "Open network support" below and your question goes with you.' },
|
||||
{ id: 'about', title: 'What is Stack POL?', q: ['What is Stack POL?', 'How does Stack POL work?', 'What is this site?'], tags: ['stack pol', 'overview', 'ledger', 'payouts'],
|
||||
re: /(what('s| is) (stack ?pol|this (site|place))|how does (stack ?pol|this site|it) work)/i,
|
||||
a: 'Stack POL adds up every POL payout from the programs in the network: InstantAdPay, LinkSpin, the other network sites and the games that pay POL. The front page shows everyone combined, every row links to its Polygon transaction, and a member who switches it on gets their own page with their own stack. Stack POL only shows payouts; it sells nothing and holds nothing. ' + NOT_INCOME },
|
||||
{ id: 'numbers', title: 'Where the numbers come from', q: ['Where do the numbers come from?', 'How often does it update?', 'Can I check a payment?'], tags: ['numbers', 'ledger', 'polygonscan', 'update'],
|
||||
re: /(where do the numbers|numbers come from|how often|update[sd]?\b|refresh|check (a |the )?payment|polygonscan|verify)/i,
|
||||
a: 'From each program\'s own payout records and from the network contracts on Polygon, refreshed every 5 minutes. Every row in the ledger (' + URL_ + '/ledger) links to its Polygon transaction, so anyone can check it on Polygonscan.' },
|
||||
{ id: 'income', title: 'Is this income? Will I earn this much?', q: ['Will I earn this much?', 'Is this income?', 'How much can I make?'], tags: ['income', 'earnings', 'promise'],
|
||||
re: /(will i (earn|make|get)|how much (can|will|do) (i|you|people) (earn|make)|is (this|it) income|earn this much|guarantee)/i,
|
||||
a: NOT_INCOME + ' What one member stacks depends on what they do in each program.' },
|
||||
{ id: 'my-page', title: 'Your own Stack POL page', q: ['How do I get my own Stack POL page?', 'Why is my name not on Stack POL?', 'How do I hide my page?'], tags: ['my page', 'opt in', 'username', 'promo tools'],
|
||||
re: /(my (own )?(stack|page)|own (stack )?page|switch on|opt.?in|my name (is )?not|hide my|show my stack)/i,
|
||||
a: 'Join InstantAdPay free, link a wallet, and switch on "Show my Stack POL page" in Promo tools. Your page lives at ' + URL_ + '/your-username and updates every 5 minutes. Members are named on Stack POL only when they switch it on.' },
|
||||
{ id: 'programs', title: 'Which programs are on Stack POL', q: ['Which programs are on Stack POL?', 'Where does the POL come from?', 'Are the games included?'], tags: ['programs', 'games', 'sites', 'earn pages'],
|
||||
re: /(which programs|what programs|programs (are|on)|where does the pol come from|games? (included|on)|\/earn)/i,
|
||||
a: 'The programs on Stack POL: ' + NAMES + '. Each has its own page (for example ' + URL_ + '/earn/viraladblitz) and its own ledger filter, and each pays straight to members\' own wallets on Polygon. See them all at ' + URL_ + '/programs' },
|
||||
{ id: 'start', title: 'How to start', q: ['How do I start?', 'How do I join?', 'Is it free?'], tags: ['join', 'start', 'free', 'instantadpay'],
|
||||
re: /(how (do|can) i (start|join|sign ?up)|\bjoin\b|sign ?up|get started|is (it|this) free|free to join)/i,
|
||||
a: 'Start free on InstantAdPay (https://instantadpay.com/join): one network account works across every network site. What you stack depends on what you do in each program. ' + NOT_INCOME },
|
||||
{ id: 'custody', title: 'Does Stack POL hold my money?', q: ['Does Stack POL hold my money?', 'How do I withdraw from Stack POL?'], tags: ['custody', 'withdraw', 'wallet', 'safe'],
|
||||
re: /(hold (my|the) (money|funds|pol)|withdraw|cash ?out|balance|safe|scam|legit)/i,
|
||||
a: 'No. Stack POL only shows payouts. Every payment goes straight from the program to your own wallet on Polygon, so there is nothing here to withdraw.' },
|
||||
{ id: 'pol', title: 'What is POL?', q: ['What is POL?', 'Is POL the same as MATIC?', 'Which wallet do I need?'], tags: ['pol', 'polygon', 'matic', 'wallet'],
|
||||
re: /(what is pol|\bpol\b|matic|polygon|wallet|safepal|metamask)/i,
|
||||
a: 'POL is the native token of the Polygon network, formerly MATIC. Fees are a fraction of a cent and transfers confirm in seconds, which is why small payouts work on it. To receive payouts, use SafePal or any other crypto wallet on Polygon, and never share your recovery phrase.' },
|
||||
{ id: 'blog', title: 'The blog', q: ['Is there a blog?', 'Where are the guides?'], tags: ['blog', 'guides', 'articles'],
|
||||
re: /\bblog\b|articles?|guides?|rss/i,
|
||||
a: 'The blog at ' + URL_ + '/blog has guides on building in POL across the network, with an RSS feed at ' + URL_ + '/blog/feed.xml.' }
|
||||
];
|
||||
|
||||
const FAQ = [
|
||||
{ id: 'f-network', title: 'Stack POL and the network', source: 'faq', tags: ['network', 'one account'],
|
||||
questions: ['Is Stack POL part of InstantAdPay?', 'Which network sites are there?'],
|
||||
answer: 'Stack POL is the network\'s payout tracker. One network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, DownlineHydra, 5xYourTeam, Stack POL and Earners Corner, and each site\'s member payouts show here.' }
|
||||
];
|
||||
|
||||
const FACTS = () => [
|
||||
'- WHAT IT IS: Stack POL (' + URL_ + ') adds up every POL payout across the network: ' + NAMES + '. Front page = everyone combined (network totals, last 7 days, latest payouts), /programs, /earn/<program> pages, /ledger (filter ?p=), opt-in member pages ' + URL_ + '/<username>, /blog. It sells nothing and holds nothing: every payment goes from the program straight to the member\'s wallet on Polygon.',
|
||||
'- DATA: each program\'s payout records and the network contracts on Polygon, refreshed every 5 minutes; every ledger row links to its Polygon transaction. Members are named only when they switch on "Show my Stack POL page" in InstantAdPay Promo tools (join InstantAdPay free and link a wallet first).',
|
||||
'- NEVER quote a total as what someone will earn; never state a maximum. ' + NOT_INCOME,
|
||||
'- For how a program pays (prices, splits, rules), use that program\'s own knowledge-base entries and send people to that site. SUPPORT: network support at ' + SUPPORT + '.'
|
||||
].join('\n');
|
||||
|
||||
const SITE = {
|
||||
id: 'stackpol', hubSite: 'stackpol', netId: 'stackpol', name: 'Stack POL', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE,
|
||||
dataDir: null, canned: CANNED, faq: FAQ, facts: FACTS,
|
||||
intro: 'You are the assistant on Stack POL (' + URL_ + '), the network\'s payout tracker: it adds up every POL payout across the network\'s sites and games, each one checkable on Polygon. Most questions about how to earn belong to a specific program: answer from that program\'s entries and link to it.',
|
||||
quickTopics: ['What is Stack POL?', 'How do I get my own page?', 'What is ViralAdBlitz?', 'How does Downline Banners pay?']
|
||||
};
|
||||
|
||||
function init() { return core.init(SITE); }
|
||||
module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE };
|
||||
+219
@@ -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 };
|
||||
@@ -0,0 +1,289 @@
|
||||
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
|
||||
// The chatbot answers from maintained entries, and good support replies become entries.
|
||||
//
|
||||
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
|
||||
// updated, created, edited, deleted, seedHash }
|
||||
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
|
||||
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
|
||||
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
|
||||
// path serves the new text.
|
||||
// source canned | faq | ticket | admin
|
||||
//
|
||||
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||
//
|
||||
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
|
||||
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
|
||||
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
|
||||
//
|
||||
// Store: DATA_DIR/kb.json (written to a temp file and renamed), which docstore.js keeps in MySQL when DOCSTORE_URL is set
|
||||
// (Marty's database rule). Ported from LinkSpin's kb.js (2026-11-15); keep the scoring and seed rules in step.
|
||||
//
|
||||
// NETWORK (2026-11-15, netkb.js): the other network sites' entries, read from the hub, sit in the same index. This site's
|
||||
// own entries are boosted first (HOME_BOOST); a question that names another site boosts that site's entries instead
|
||||
// (NAMED_BOOST). Other sites' entries never take the instant-answer fast path: they only ride along as context, labelled
|
||||
// with the site and the link to send people to. This site's own entries are published to the hub (netkb.publish).
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
let netkb = null; try { netkb = require('./netkb'); } catch (e) {}
|
||||
|
||||
let DATA_DIR = null, SEEDS = [], ready = null, SITE_URL = '', HELP_TEXT = '', MEMORY = false;
|
||||
let cache = null, cacheAt = 0, index = null, netVer = '';
|
||||
const TTL = 30000; // two app copies share the volume for about 30 s during a deploy: re-read now and then
|
||||
|
||||
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
|
||||
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
|
||||
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
|
||||
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
|
||||
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
|
||||
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
|
||||
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
|
||||
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
|
||||
function stem(w) {
|
||||
if (SYN[w]) return SYN[w];
|
||||
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
|
||||
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
|
||||
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
|
||||
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
|
||||
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
|
||||
return w;
|
||||
}
|
||||
function words(text) {
|
||||
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
|
||||
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
|
||||
}
|
||||
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
|
||||
function terms(text) {
|
||||
const w = words(text), out = w.slice();
|
||||
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
|
||||
return out;
|
||||
}
|
||||
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
|
||||
const K1 = 1.2, B = 0.75;
|
||||
function fieldText(e, f) {
|
||||
if (f === 'questions') return (e.questions || []).join(' . ');
|
||||
if (f === 'tags') return (e.tags || []).join(' . ');
|
||||
return e[f] || '';
|
||||
}
|
||||
function buildIndex(entries) {
|
||||
const docs = entries.map(e => {
|
||||
const d = { e, f: {} };
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const t = terms(fieldText(e, f)), tf = new Map();
|
||||
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
|
||||
d.f[f] = { tf, len: t.length };
|
||||
}
|
||||
return d;
|
||||
});
|
||||
const df = new Map(), avg = {};
|
||||
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
|
||||
for (const d of docs) {
|
||||
const seen = new Set();
|
||||
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
|
||||
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
|
||||
}
|
||||
return { docs, df, avg, n: docs.length };
|
||||
}
|
||||
const HOME_BOOST = 2, NAMED_BOOST = 3;
|
||||
// which network sites a question names, by the site name or a short alias ("dlb", "vbb", "iap", ...)
|
||||
const ALIASES = { iap: ['iap', 'instant ad pay'], linkspin: ['link spin'], bannerline: ['dlb', 'downline banner', 'downline banners'], vbb: ['vbb', 'viral banner'],
|
||||
viraladblitz: ['vab', 'viral ad blitz'], downlinehydra: ['hydra', 'dh'], fivex: ['5x', '5x your team', 'five x', 'the draft'], stackpol: ['stack pol', 'stackpol'] };
|
||||
const norm = s => ' ' + String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim() + ' ';
|
||||
function namedSites(query, idx) {
|
||||
const q = norm(query); const out = new Set();
|
||||
for (const s of (idx && idx.sites) || []) {
|
||||
const names = [s.name, s.site].concat(ALIASES[s.site] || []).map(norm);
|
||||
if (names.some(n => n.trim() && q.includes(n))) out.add(s.site);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// does the question name a network site other than this one (hub site id `self`)? Then the home fast path stands aside and the
|
||||
// answer comes from retrieval over the whole network (a "how much" about another site must not get this site's price).
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz',
|
||||
downlinehydra: 'DownlineHydra', fivex: '5xYourTeam', stackpol: 'Stack POL', earnerscorner: 'Earners Corner' };
|
||||
function namesOther(query, self) {
|
||||
const q = norm(query); const out = [];
|
||||
const ids = new Set(Object.keys(NAMES).concat(((index && index.sites) || []).map(s => s.site)));
|
||||
for (const id of ids) {
|
||||
if (id === self) continue;
|
||||
const s = ((index && index.sites) || []).find(x => x.site === id) || {};
|
||||
const names = [s.name, NAMES[id], id.length > 3 ? id : ''].concat(ALIASES[id] || []).filter(Boolean).map(norm);
|
||||
if (names.some(n => n.trim() && q.includes(n))) out.push(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function rank(idx, query, k) {
|
||||
if (!idx || !idx.n) return [];
|
||||
const qt = [...new Set(terms(query))];
|
||||
if (!qt.length) return [];
|
||||
const named = namedSites(query, idx);
|
||||
const out = [];
|
||||
for (const d of idx.docs) {
|
||||
let s = 0;
|
||||
for (const t of qt) {
|
||||
const n = idx.df.get(t); if (!n) continue;
|
||||
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const tf = d.f[f].tf.get(t); if (!tf) continue;
|
||||
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||
}
|
||||
}
|
||||
if (s > 0 && d.e.site) s *= named.has(d.e.site) ? NAMED_BOOST : 1;
|
||||
else if (s > 0) s *= named.size ? 1 : HOME_BOOST;
|
||||
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||
}
|
||||
out.sort((a, b) => b.score - a.score);
|
||||
return out.slice(0, k || 5);
|
||||
}
|
||||
// keep hits that are close to the best one, and only when the best is a real match
|
||||
const MIN_SCORE = 3;
|
||||
function relevant(hits) {
|
||||
if (!hits.length || hits[0].score < MIN_SCORE) return [];
|
||||
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
|
||||
return hits.filter(h => h.score >= floor);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- store
|
||||
const mem = { entries: [] }; // a site with no data volume (Stack POL): seeds in memory only
|
||||
const J = {
|
||||
file: () => path.join(DATA_DIR, 'kb.json'),
|
||||
async ensure() {},
|
||||
async all() { if (MEMORY) return mem.entries.slice(); try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
|
||||
async put(e) {
|
||||
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
|
||||
if (i >= 0) all[i] = e; else all.push(e);
|
||||
if (MEMORY) { mem.entries = all; return; }
|
||||
const tmp = J.file() + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
|
||||
fs.renameSync(tmp, J.file());
|
||||
}
|
||||
};
|
||||
const store = () => J;
|
||||
|
||||
// ---------------------------------------------------------------- seeds
|
||||
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
|
||||
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
|
||||
function seedEntry(s) {
|
||||
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
|
||||
order: s.order == null ? null : s.order, source: s.source || 'faq' };
|
||||
}
|
||||
async function syncSeeds() {
|
||||
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
|
||||
const seedIds = new Set(SEEDS.map(s => s.id));
|
||||
let added = 0, refreshed = 0, retired = 0;
|
||||
for (const s of SEEDS) {
|
||||
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
|
||||
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
|
||||
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
|
||||
}
|
||||
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
|
||||
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
|
||||
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
|
||||
}
|
||||
|
||||
// opts: { dataDir (null = memory only), seeds, siteUrl, helpText (where a member gets a person) }
|
||||
function init(opts) {
|
||||
DATA_DIR = opts.dataDir || null; MEMORY = !DATA_DIR; SEEDS = opts.seeds || []; cache = null; index = null; mem.entries = [];
|
||||
SITE_URL = String(opts.siteUrl || '').replace(/\/+$/, ''); HELP_TEXT = opts.helpText || 'network support at https://instantadpay.com/support';
|
||||
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
|
||||
return ready;
|
||||
}
|
||||
// this site's own entries, for netkb.publish
|
||||
async function own() { await load(); return cache.slice(); }
|
||||
async function load(force) {
|
||||
if (ready) await ready;
|
||||
if (!force && cache && Date.now() - cacheAt < TTL && (!netkb || netkb.version() === netVer)) return cache; // a new network set rebuilds at once
|
||||
const all = await store().all();
|
||||
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); rx.clear(); netVer = netkb ? netkb.version() : '';
|
||||
index = buildIndex(cache.concat(netkb ? netkb.remote() : [])); index.sites = netkb ? netkb.sites() : [];
|
||||
return cache;
|
||||
}
|
||||
const rx = new Map();
|
||||
function compiled(src) {
|
||||
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
|
||||
return rx.get(src);
|
||||
}
|
||||
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
|
||||
|
||||
// ---------------------------------------------------------------- the chatbot side
|
||||
async function fastPath(msg) {
|
||||
const list = (await load()).filter(e => e.pattern).sort(byOrder);
|
||||
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
|
||||
return null;
|
||||
}
|
||||
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||
async function context(query, k) { return relevant(await search(query, k || 6)); }
|
||||
const label = e => e.site ? ' (about ' + e.siteName + ', another network site; send people to ' + e.go + ')' : '';
|
||||
function promptBlock(hits) {
|
||||
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP_TEXT + '.';
|
||||
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + label(h.entry) + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the admin side
|
||||
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
|
||||
function validate(o, cur) {
|
||||
o = o || {};
|
||||
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
|
||||
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
|
||||
const answer = clean(o.answer).slice(0, 4000);
|
||||
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
|
||||
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
|
||||
if (!title) return { error: 'Give the entry a title or at least one question.' };
|
||||
if (!answer) return { error: 'The answer is empty.' };
|
||||
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
|
||||
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
|
||||
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
|
||||
}
|
||||
async function list(q) {
|
||||
const all = (await load(true)).slice();
|
||||
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||
const ranked = rank(index, q, 50).filter(h => !h.entry.site).map(h => Object.assign({ score: h.score }, h.entry));
|
||||
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||
return ranked.concat(plain);
|
||||
}
|
||||
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
|
||||
async function create(o) {
|
||||
const v = validate(o); if (v.error) return v;
|
||||
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function update(id, o) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
const v = validate(o, cur); if (v.error) return v;
|
||||
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||
await store().put(e); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function remove(id) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true); if (netkb) netkb.publishSoon();
|
||||
return { ok: true };
|
||||
}
|
||||
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
|
||||
// KNOWLEDGE_DATE already speaks for the code.
|
||||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
async function stamp() {
|
||||
const all = await load();
|
||||
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
|
||||
return { updated: max ? ctDay(max) : '', count: all.length };
|
||||
}
|
||||
async function test(question) {
|
||||
const fast = await fastPath(String(question || ''));
|
||||
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, site: h.entry.site || '', title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||
}
|
||||
|
||||
module.exports = { init, load, own, namesOther, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, namedSites, MIN_SCORE, HOME_BOOST, NAMED_BOOST } };
|
||||
@@ -177,6 +177,6 @@ function tail(extra) {
|
||||
+ '<p class="disc">© ' + year + ' Stack POL by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Part of the Crypto Team Build Network. Stack POL shows payouts; it does not hold, invest or pay out anyone\'s money.</p>'
|
||||
// PolHunter mission (Marty 2026-11-10): silent unless a hunter arrives with their own #ph token; the code lands on one of the
|
||||
// program cards (3 slots, which one rotates per hunter per day)
|
||||
+ '</div>' + (extra || '') + SPOT_JS + '<script src="https://polhunter.com/embed.js" data-slots="3" data-selector=".card" async></script></body></html>';
|
||||
+ '</div>' + (extra || '') + SPOT_JS + '<script src="https://polhunter.com/embed.js" data-slots="3" data-selector=".card" async></script><script src="/assets/chat.js?v=1" defer></script></body></html>';
|
||||
}
|
||||
module.exports = { SITE, esc, head, tail, OG, V, ZONES, spot, personalize, memberLinks, proCta, MEMBER_HOST };
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Shared network knowledge, site side (Marty 2026-11-15: every network site's chatbot answers about the whole network, with its
|
||||
// own site first). This site publishes its own knowledge-base entries to the network hub and reads the merged set back:
|
||||
// PUT HUB_URL/v1/kb {name, url, entries} replaces this site's set (the hub skips a set it already holds)
|
||||
// GET HUB_URL/v1/kb signed over an empty body, If-None-Match: the last version -> 304 when nothing changed
|
||||
// Signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + "\n" + raw body)), like hubreport.js.
|
||||
// The merged set is kept in memory and in DATA_DIR/netkb-cache.json (a MySQL document through docstore where the site has
|
||||
// DOCSTORE_URL; written only when the version changes), so a hub outage at boot still answers about the other sites.
|
||||
// Off when HUB_URL or a 32+ character HUB_SECRET is missing, or NETKB=0: the chatbot then answers about this site only.
|
||||
// The SAME file ships in every network site (InstantAdPay, LinkSpin, ViralAdBlitz, DownlineHydra, 5xYourTeam, VBB, Downline
|
||||
// Banners, Stack POL). Keep them identical.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const REFRESH_MS = 10 * 60 * 1000;
|
||||
let O = null; // { dataDir, site, name, url, netId, entries: async () => [...], linkFor: (url) => link }
|
||||
let merged = { version: '', sites: {}, entries: [] }, loadedAt = 0, publishedHash = '', pubTimer = null, timer = null;
|
||||
const stats = { published: 0, publishErrors: 0, reads: 0, notModified: 0, readErrors: 0, lastError: null, lastPublishAt: 0, lastReadAt: 0 };
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const secret = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const siteName = () => String(process.env.HUB_SITE || (O && O.site) || '').trim();
|
||||
const enabled = () => process.env.NETKB !== '0' && !!hubUrl() && secret().length >= 32 && !!siteName();
|
||||
const cacheFile = () => (O && O.dataDir ? path.join(O.dataDir, 'netkb-cache.json') : null);
|
||||
|
||||
async function call(method, route, body, headers) {
|
||||
const raw = body === undefined ? '' : JSON.stringify(body); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(hubUrl() + route, { method, body: method === 'GET' ? undefined : raw, signal: AbortSignal.timeout(15000),
|
||||
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Hub-Site': siteName(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, headers || {}) });
|
||||
let j = null; if (r.status !== 304) { try { j = await r.json(); } catch (e) {} }
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
|
||||
// the entries this site shares: what the chatbot's knowledge base holds, minus the instant-answer patterns (those stay home)
|
||||
const shape = e => ({ id: String(e.id), title: e.title, questions: (e.questions || []).slice(0, 15), answer: e.answer, tags: (e.tags || []).slice(0, 15), link: e.link || (O && O.url) || undefined });
|
||||
async function publish() {
|
||||
if (!enabled() || !O || typeof O.entries !== 'function') return { skipped: true };
|
||||
const entries = (await O.entries()).filter(e => e && e.id && e.answer && !e.deleted).map(shape);
|
||||
const body = { name: O.name, url: O.url, entries };
|
||||
const h = crypto.createHash('sha1').update(JSON.stringify(body)).digest('hex');
|
||||
if (h === publishedHash) return { same: true };
|
||||
try {
|
||||
const r = await call('PUT', '/v1/kb', body);
|
||||
if (r.status !== 200) { stats.publishErrors++; stats.lastError = 'publish ' + r.status + ' ' + ((r.body && r.body.error) || ''); return { error: stats.lastError }; }
|
||||
publishedHash = h; stats.published++; stats.lastPublishAt = Date.now();
|
||||
return r.body;
|
||||
} catch (e) { stats.publishErrors++; stats.lastError = 'publish ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
// an admin edit: publish a few seconds later (several quick edits go as one)
|
||||
function publishSoon() { if (pubTimer) return; pubTimer = setTimeout(() => { pubTimer = null; publish().catch(() => {}); }, 5000); if (pubTimer.unref) pubTimer.unref(); }
|
||||
|
||||
function readCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (d && Array.isArray(d.entries)) { merged = d; loadedAt = 0; } } catch (e) {}
|
||||
}
|
||||
function writeCache() {
|
||||
const f = cacheFile(); if (!f) return;
|
||||
try { fs.writeFileSync(f + '.tmp', JSON.stringify(merged)); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('netkb cache', e.message); }
|
||||
}
|
||||
async function refresh() {
|
||||
if (!enabled()) return { skipped: true };
|
||||
try {
|
||||
const r = await call('GET', '/v1/kb', undefined, merged.version ? { 'If-None-Match': '"' + merged.version + '"' } : {});
|
||||
stats.lastReadAt = Date.now();
|
||||
if (r.status === 304) { stats.notModified++; loadedAt = Date.now(); return { same: true }; }
|
||||
if (r.status !== 200 || !r.body || !Array.isArray(r.body.entries)) { stats.readErrors++; stats.lastError = 'read ' + r.status; return { error: stats.lastError }; }
|
||||
merged = { version: String(r.body.version || ''), sites: r.body.sites || {}, entries: r.body.entries }; loadedAt = Date.now(); stats.reads++;
|
||||
writeCache();
|
||||
return { version: merged.version, count: merged.entries.length };
|
||||
} catch (e) { stats.readErrors++; stats.lastError = 'read ' + e.message; return { error: e.message }; }
|
||||
}
|
||||
|
||||
// other sites' entries, ready for the chatbot's index: id "<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
|
||||
|
||||
const version = () => merged.version || '';
|
||||
module.exports = { init, publish, publishSoon, refresh, remote, sites, view, enabled, version, _set };
|
||||
@@ -0,0 +1,35 @@
|
||||
/* Site assistant widget, Stack POL look (layout.js): deep violet night, gold for the stack, Sora headings, Manrope body.
|
||||
Fallbacks match the layout's tokens. */
|
||||
#scChat{--sc-bg:var(--panel,#130c24);--sc-bg2:var(--panel-2,#1b1232);--sc-ink:var(--ink,#f3efff);--sc-sub:var(--muted,#a8a0c6);--sc-line:var(--line,rgba(183,148,255,.18));
|
||||
--sc-violet:var(--violet,#8247e5);--sc-violet-hi:var(--violet-hi,#b794ff);--sc-gold:var(--gold,#ffc24b);--sc-gold-d:var(--gold-d,#b9781a);
|
||||
--sc-disp:var(--display,"Sora","Segoe UI",system-ui,sans-serif);--sc-font:var(--body,"Manrope",system-ui,sans-serif);
|
||||
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
|
||||
#scBtn{width:58px;height:58px;border-radius:18px;border:0;cursor:pointer;background:var(--sc-gold);color:#160b02;display:flex;align-items:center;justify-content:center;box-shadow:0 5px 0 var(--sc-gold-d),0 14px 30px rgba(255,194,75,.2)}
|
||||
#scBtn:focus-visible{outline:2px solid var(--sc-violet-hi);outline-offset:4px}
|
||||
#scChat.open #scBtn{background:var(--sc-violet);color:#fff;box-shadow:0 5px 0 #4b2394}
|
||||
#scPanel{position:absolute;right:0;bottom:76px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column;
|
||||
background:var(--sc-bg);color:var(--sc-ink);border:1px solid var(--sc-line);border-radius:18px;box-shadow:0 24px 60px rgba(0,0,0,.55);overflow:hidden}
|
||||
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:linear-gradient(135deg,rgba(130,71,229,.35),rgba(19,12,36,0) 75%),var(--sc-bg2);border-bottom:1px solid var(--sc-line)}
|
||||
.sc-head>div{flex:1;min-width:0}
|
||||
.sc-title{display:block;font:800 19px var(--sc-disp);letter-spacing:-.01em}
|
||||
.sc-sub{display:block;font-size:12.5px;color:var(--sc-sub)}
|
||||
#scClose{background:transparent;border:0;color:var(--sc-sub);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.5;border-radius:14px;overflow-wrap:anywhere}
|
||||
.sc-m.bot{align-self:flex-start;background:var(--sc-bg2);border:1px solid var(--sc-line);border-bottom-left-radius:4px}
|
||||
.sc-m.me{align-self:flex-end;background:var(--sc-violet);color:#fff;border-bottom-right-radius:4px}
|
||||
.sc-m a{color:var(--sc-gold);text-decoration:underline}
|
||||
.sc-m.me a{color:#fff}
|
||||
.sc-m.wait{opacity:.6}
|
||||
.sc-cta{display:inline-block;background:var(--sc-gold);color:#160b02!important;text-decoration:none!important;font:800 14px var(--sc-disp);padding:8px 14px;border-radius:12px;box-shadow:0 4px 0 var(--sc-gold-d)}
|
||||
.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-violet-hi);border:1px solid var(--sc-line);border-radius:999px;font:600 12.5px var(--sc-font);padding:5px 11px;cursor:pointer}
|
||||
.sc-topics button:hover{border-color:var(--sc-violet-hi)}
|
||||
.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line)}
|
||||
.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);border-radius:12px;padding:10px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:var(--ground,#0a0715)}
|
||||
.sc-input input::placeholder{color:var(--sc-sub)}
|
||||
.sc-input input:focus{outline:2px solid var(--sc-violet-hi);outline-offset:-1px}
|
||||
.sc-input button{background:var(--sc-gold);color:#160b02;border:0;border-radius:12px;font:800 14px var(--sc-disp);padding:0 16px;cursor:pointer}
|
||||
.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:0 0 10px}
|
||||
@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:68px;height:calc(100vh - 100px)}}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Site assistant widget (2026-11-15): a round button bottom right, a panel that asks /api/chat. The look is this site's own,
|
||||
// in /assets/chat.css (colors and fonts from the site's stylesheet). When an answer cannot help, or the visitor asks for a
|
||||
// person, it offers "Open network support": InstantAdPay's support desk, which already knows the question and the site.
|
||||
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
|
||||
(function () {
|
||||
if (window.__siteChat || /^\/admin/.test(location.pathname)) return;
|
||||
window.__siteChat = 1;
|
||||
var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/assets/chat.css?v=20261115d'; document.head.appendChild(css);
|
||||
var NAME = 'this site', TOPICS = [];
|
||||
var root = document.createElement('div'); root.id = 'scChat';
|
||||
root.innerHTML = '<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>'
|
||||
+ '<div id="scPanel" role="dialog" aria-label="Questions" hidden>'
|
||||
+ '<div 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">×</button></div>'
|
||||
+ '<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>'
|
||||
+ '</div>';
|
||||
document.body.appendChild(root);
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var msgs = $('scMsgs'), input = $('scIn'), panel = $('scPanel'), btn = $('scBtn');
|
||||
var history = [], greeted = false, support = 'https://instantadpay.com/support';
|
||||
fetch('/api/chat/config').then(function (r) { return r.json(); }).then(function (c) {
|
||||
if (c.name) { NAME = c.name; $('scTitle').textContent = 'Ask ' + c.name; }
|
||||
if (c.support) { support = c.support; $('scHuman').href = c.support; }
|
||||
TOPICS = c.topics || [];
|
||||
}).catch(function () {});
|
||||
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function add(text, who) {
|
||||
var d = document.createElement('div'); d.className = 'sc-m ' + who;
|
||||
d.innerHTML = esc(text).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)])/g, '<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(); });
|
||||
})();
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"site": "stackpol",
|
||||
"home": [
|
||||
{ "q": "What is Stack POL?", "kb": "about", "must": ["every POL payout", "holds nothing"] },
|
||||
{ "q": "Where do the numbers come from?", "kb": "numbers", "must": ["5 minutes", "Polygonscan"] },
|
||||
{ "q": "How often does it update?", "kb": "numbers", "must": ["5 minutes"] },
|
||||
{ "q": "Will I earn this much?", "kb": "income", "must": ["No promise of income"] },
|
||||
{ "q": "How do I get my own Stack POL page?", "kb": "my-page", "must": ["Promo tools", "link a wallet"] },
|
||||
{ "q": "Which programs are on Stack POL?", "kb": "programs", "must": ["InstantAdPay", "ViralAdBlitz", "DownlineHydra"] },
|
||||
{ "q": "How do I join?", "kb": "start", "must": ["instantadpay.com/join"] },
|
||||
{ "q": "Does Stack POL hold my money?", "kb": "custody", "must": ["straight from the program"] },
|
||||
{ "q": "What is POL?", "kb": "pol", "must": ["Polygon", "SafePal or any other crypto wallet"] },
|
||||
{ "q": "Is there a blog?", "kb": "blog", "must": ["feed.xml"] }
|
||||
],
|
||||
"cross": [
|
||||
{ "q": "How does Downline Banners pay?", "site": "bannerline" },
|
||||
{ "q": "What is a ViralAdBlitz Boost?", "site": "viraladblitz" },
|
||||
{ "q": "How much is a 5xYourTeam position?", "site": "fivex" },
|
||||
{ "q": "What does DownlineHydra Pro give me?", "site": "downlinehydra" },
|
||||
{ "q": "How does Viral Banner Blitz work?", "site": "vbb" }
|
||||
]
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
try { const cfg = require(path.join(ROOT, 'config.js')); if (cfg.reset) cfg.reset(); } catch (e) {} // Stack POL has no config.js
|
||||
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 >= 10, 'at least 10 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'); }
|
||||
if (dataDir) fs.writeFileSync(path.join(dataDir, 'openrouter.key'), 'test-key'); else process.env.OPENROUTER_API_KEY = 'test-key'; // no volume (Stack POL): the env 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);
|
||||
@@ -157,7 +157,7 @@ function sitemap() {
|
||||
}
|
||||
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
|
||||
|
||||
const TYPES = { '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
|
||||
const TYPES = { '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
|
||||
function send(req, res, code, type, body, cache) {
|
||||
const h = { 'Content-Type': type, 'Cache-Control': cache || 'public, max-age=60', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' };
|
||||
if (/gzip/.test(req.headers['accept-encoding'] || '') && /text|xml|json|javascript/.test(type) && body.length > 1024) { h['Content-Encoding'] = 'gzip'; h.Vary = 'Accept-Encoding'; body = zlib.gzipSync(body); }
|
||||
@@ -178,6 +178,10 @@ function staticFile(req, res, p) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js); no admin editing on Stack POL
|
||||
const chatbot = require('./chatbot');
|
||||
const chatJson = (res, code, obj, extra) => { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }, extra || {})); res.end(JSON.stringify(obj)); };
|
||||
const chatBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 32768) ch.push(c); }); req.on('end', () => { try { resolve(n && n <= 32768 ? JSON.parse(Buffer.concat(ch).toString('utf8')) : {}); } catch (e) { resolve({}); } }); req.on('error', () => resolve({})); });
|
||||
const server = http.createServer((req, res) => {
|
||||
let u; try { u = new URL(req.url, SITE); } catch (e) { res.writeHead(400); return res.end(); }
|
||||
const p = decodeURIComponent(u.pathname);
|
||||
@@ -190,6 +194,8 @@ const server = http.createServer((req, res) => {
|
||||
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; fs.writeFile(SNAP, JSON.stringify(j), () => {}); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
|
||||
return;
|
||||
}
|
||||
if (p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) { chatbot.handle(req, res, p, u, { json: chatJson, readBody: chatBody, isAdmin: () => false })
|
||||
.then(done => { if (!done) chatJson(res, 404, { error: 'Not found' }); }).catch(e => { console.error('[stackpol] chat', e.message); if (!res.headersSent) chatJson(res, 500, { error: 'Server error' }); }); return; }
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
|
||||
if (p === '/api/totals') return send(req, res, 200, 'application/json', JSON.stringify({ at: IDX ? IDX.at : null, network: net(), programs: (IDX && IDX.programs) || {} }), 'public, max-age=120');
|
||||
if (p === '/health') return send(req, res, 200, 'text/plain', 'ok', 'no-store');
|
||||
@@ -221,4 +227,5 @@ const server = http.createServer((req, res) => {
|
||||
return html(req, res, 404, notFound());
|
||||
} catch (e) { console.error('[stackpol]', p, e); html(req, res, 500, notFound('Something went wrong on our side. Try again in a minute.'), 'no-store'); }
|
||||
});
|
||||
chatbot.init();
|
||||
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX ? new Date(IDX.at).toISOString() : 'none yet') + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
|
||||
|
||||
Reference in New Issue
Block a user