From 42cbe9697921aac047cb0e98a700ca9a8ecc8e67 Mon Sep 17 00:00:00 2001 From: martbost Date: Sat, 14 Nov 2026 08:45:43 -0600 Subject: [PATCH] Hub switch-on (Marty 2026-11-14). Rule 2: a hub arrival gets person.locks.linkspin's sponsor when the LinkSpin contract holds them, never the plain network sponsor; sponsor.changed stays ignored. Quiet: a wallet filled from a hub event never switches payouts on (isQuiet: no gas, no lock, no 'payouts are switched on' mail). Rule 3: the holding tank (waiting, release, expiry, rescue, readyTick, autoAssign) leaves out anyone the hub reports locked on any contract or sponsored, and hub waiting copies that never signed in here; /v1/locked detail cached 10 min, last answer kept 1 h, after that held (unknown). Alignment to the hub sponsor only with HUB_TANK_ALIGN=on. Needs network-hub b44dba6. hubsync 15 checks, sponsorfollow 30/30, tank-cap 15/15, networksso ALL PASSED, tank-hold, carry-hold ok Co-Authored-By: Claude Opus 5.5 --- hubsync.js | 99 +++++++++++++++++++++++++++++++++++++++------ qa/hubsync.test.cjs | 85 +++++++++++++++++++++++++++++++++++++- server.js | 7 +++- tank.js | 40 ++++++++++++++++-- 4 files changed, 212 insertions(+), 19 deletions(-) diff --git a/hubsync.js b/hubsync.js index 2efc890..11241f3 100644 --- a/hubsync.js +++ b/hubsync.js @@ -7,7 +7,9 @@ // registry sync makes (/api/partner/registry in server.js): accounts.ensure(email, '', 'carried', 'network'), then only // EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed // first (up to 25 levels up) so the line exists. A sponsor already set here is never moved: a disagreement is logged. -// wallet.connected: fills an empty wallet here, same as the registry sync. Every other event is acknowledged and ignored. +// wallet.connected: fills an empty wallet here, same as the registry sync. Every other event is acknowledged and ignored +// (sponsor.changed included, on purpose). 2026-11-14: the sponsor written is person.locks.linkspin's sponsor when that lock +// exists (rule 2), and a wallet filled from the hub never switches payouts on (isQuiet): no gas, no lock, no mail. // OUT accounts.onChange -> touch(email): a persisted outbox (DATA_DIR/hubsync.json) reports LinkSpin's own joins // (/v1/join, sponsor named by email) and wallet links (/v1/wallet). Never blocks sign-up; failures retry with backoff. // Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), still one way: a DELIBERATE sponsor change @@ -37,17 +39,17 @@ function load() { try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = null; } if (!state || typeof state !== 'object') state = {}; state.lastSeq = Number(state.lastSeq) || 0; state.outbox = state.outbox || {}; state.sent = state.sent || {}; - state.disagree = state.disagree || {}; state.stats = state.stats || { events: 0, shells: 0, filled: 0, joins: 0, wallets: 0, dropped: 0, errors: 0 }; + state.disagree = state.disagree || {}; state.made = state.made || {}; /* made: waiting copies created here from hub events, email -> door */ state.stats = state.stats || { events: 0, shells: 0, filled: 0, joins: 0, wallets: 0, dropped: 0, errors: 0 }; return state; } function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} } function init(deps) { R = deps; state = null; load(); } // { dataDir, accounts, registry, carry, follow (sponsorfollow store) } const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex'); -async function call(route, body) { +async function call(route, body, timeout) { const raw = JSON.stringify(body); const ts = String(Date.now()); let r; - try { r = await fetch(URL_() + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(15000) }); } + try { r = await fetch(URL_() + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) }); } catch (e) { throw new Error('hub ' + route + ' unreachable'); } let out = null; try { out = await r.json(); } catch (e) {} if (r.status >= 500 || r.status === 401) throw new Error('hub ' + route + ' ' + r.status); // down, redeploying (503) or misconfigured: try again later @@ -65,12 +67,24 @@ function noteDisagree(e, hubSponsor, here, how) { } // ---- inbound ------------------------------------------------------------------------------------------------------------- -// a hub person gets a LinkSpin account the way an InstantAdPay person does: a waiting shell, empty fields filled, nothing moved +// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the LinkSpin CONTRACT holds for them when it holds them +// (person.locks.linkspin, null = the top of that tree), never the plain network sponsor, which may come from another +// contract where they spent money. Each contract pays whoever it holds. +const CONTRACT = 'linkspin'; +const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; return l ? (l.sponsor || null) : ((p && p.sponsor) || null); }; +// QUIET wallet fills (Marty 2026-11-14): accounts.onWalletLinked would have the engine switch payouts on for a wallet that lands +// here (carry.ensureOnChain: gas, a lock on the LinkSpin contract, the 'Your LinkSpin payouts are switched on' email and the +// chain-event mail and posts). A wallet filled from a hub event does none of that: server.js's wallet hook skips an email +// while isQuiet(email). The switch-on happens later the usual ways (the member's own Switch on payouts, or a purchase below). +const quiet = new Set(); const isQuiet = email => quiet.has(norm(email)); +// a hub person gets a LinkSpin account the way an InstantAdPay person does: a waiting shell, empty fields filled, nothing moved. +// QUIET (Marty 2026-11-14, "join one = join all"): nothing here sends mail, a notice or a post; qa/hubsync.test.cjs checks it. async function place(p, depth, seen) { const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e); - let sp = p.sponsor && p.sponsor.email ? await R.accounts.byEmail(p.sponsor.email) : null; - if (!sp && p.sponsor && p.sponsor.id && depth < MAX_UP) { // the sponsor is new here too: their line first - const up = await resolveId(p.sponsor.id); + const ps = sponsorFor(p); + let sp = ps && ps.email ? await R.accounts.byEmail(ps.email) : null; + if (!sp && ps && ps.id && depth < MAX_UP) { // the sponsor is new here too: their line first + const up = await resolveId(ps.id); if (up && up.email) { await place(up, depth + 1, seen); sp = await R.accounts.byEmail(up.email); } } R.carry.hold([e]); @@ -79,7 +93,7 @@ async function place(p, depth, seen) { try { await R.registry.upsert({ email: e, username: p.username || null, wallet: p.wallet || null, sponsorEmail: sp ? sp.email : null, joinedAt: p.firstDoor && p.firstDoor.at, firstProperty: (p.firstDoor && p.firstDoor.site) || 'network' }); } catch (err) {} } let a = await R.accounts.byEmail(e); - if (!a) { const x = await R.accounts.ensure(e, '', 'carried', 'network'); if (x.created) load().stats.shells++; a = await R.accounts.byEmail(e); } + if (!a) { const x = await R.accounts.ensure(e, '', 'carried', 'network'); if (x.created) { const st = load(); st.stats.shells++; st.made[e] = (p.firstDoor && p.firstDoor.site) || 'network'; } a = await R.accounts.byEmail(e); } if (!a) return null; if (p.username && !a.username) { try { const r = await R.accounts.setUsername(e, p.username); if (r && !r.error) load().stats.filled++; } catch (err) {} } if (sp && norm(sp.email) !== e) { @@ -92,7 +106,7 @@ async function place(p, depth, seen) { if (here !== norm(sp.email)) noteDisagree(e, sp.email, here, 'inbound'); // LinkSpin's line stands; TODO(Marty): who settles these } } - if (p.wallet && !a.address) { try { const r = await R.accounts.linkWallet(e, p.wallet); if (r && !r.error) load().stats.filled++; } catch (err) {} } + if (p.wallet && !a.address) { quiet.add(e); try { const r = await R.accounts.linkWallet(e, p.wallet); if (r && !r.error) load().stats.filled++; } catch (err) {} finally { quiet.delete(e); } } return a; } finally { R.carry.unhold([e]); } } @@ -105,9 +119,11 @@ async function apply(ev) { } else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync const p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return; const a = await R.accounts.byEmail(p.email); - if (a && !a.address) { R.carry.hold([a.email]); try { await R.accounts.linkWallet(a.email, p.wallet); } finally { R.carry.unhold([a.email]); } } + if (a && !a.address) { const k = norm(a.email); R.carry.hold([k]); quiet.add(k); try { await R.accounts.linkWallet(a.email, p.wallet); } finally { quiet.delete(k); R.carry.unhold([k]); } } } - // TODO(hub): sponsor.changed needs the sponsorfollow.js decision (chain binding, window, provenance); until it is wired, ignored. + // sponsor.changed is IGNORED on purpose (checked 2026-11-14 for the switch-on): it would need the sponsorfollow.js decision + // (chain binding, window, provenance), and a member locked on the LinkSpin contract must never move anyway (the contract pays + // whoever it holds). qa/hubsync.test.cjs proves a locked member stays put. // TODO(hub): member.blocked / unblocked, entitlement.changed, wallet.changed and the wallet-change events: ignored for now. } function verify(headers, raw) { @@ -250,9 +266,66 @@ async function flush() { return { done, failed }; } const tick = () => flush(); + +// ---- rule 3: the holding tank asks the hub (Marty 2026-11-14) ------------------------------------------------------------- +// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for, nor a waiting +// copy made here from a hub event for someone who never signed in here (their own door's tank has them; announcing them in +// the shared topic or adopting them here would not be quiet). tank.js asks through its hooks (networkHeld, networkLocked, +// network); server.js wires them only with HUB_ENABLED, so with the flag off the tank works exactly as before. One +// /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10 minutes. CONSERVATIVE when the hub cannot +// be reached: the last answer stands for up to 1 hour, after that the person is held ('unknown': not offered, not moved to +// the tank, not auto-assigned) until the hub answers again. After a failed call the hub is left alone for 2 minutes. +const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000; +const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve(); +async function refreshHeld(emails, timeout) { + const run = heldBusy.then(async () => { + const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; }); + if (!miss.length || now < heldDownUntil) return; + try { + for (let i = 0; i < miss.length; i += HELD_CHUNK) { + const part = miss.slice(i, i + HELD_CHUNK); + const r = await call('/v1/locked', { emails: part, detail: true }, timeout || 5000); + if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status); + if (held.size > 60000) held.clear(); + const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null }); + } + } catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); } + }); + heldBusy = run.catch(() => {}); return run; +} +const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null); +// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' | 'hub-shell' for the ones the tank must not offer +async function heldAmong(accts, opts) { + const out = new Map(); if (!R || !on()) return out; + const list = (accts || []).filter(a => a && a.email); const emails = [...new Set(list.map(a => norm(a.email)))]; if (!emails.length) return out; + await refreshHeld(emails, opts && opts.timeout); + const now = Date.now(); const made = load().made; + for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); } + for (const a of list) { const e = norm(a.email); if (!out.has(e) && made[e] && !a.lastSeen && !(Number(a.memberId) > 0)) out.set(e, 'hub-shell'); } + return out; +} +// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null +async function lockedAnywhere(email) { + if (!R || !on()) return null; const e = norm(email); if (!e) return null; + await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now()); + return w === 'locked' || w === 'unknown' ? w : null; +} +// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor +// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which +// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the +// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3). +const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim()); +async function hubSponsor(email) { + if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null; + await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null; + const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined; + const sp = norm(l !== undefined ? l : c.row.sponsorEmail); + return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, LinkSpin contract' : 'network hub' } : null; +} function adminView() { const st = load(); return { on: on(), url: URL_(), site: SITE(), lastSeq: st.lastSeq, outbox: Object.keys(st.outbox).length, stats: st.stats, lastError: st.lastError || null, + made: Object.keys(st.made || {}).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null, disagree: Object.entries(st.disagree).slice(-50).map(([e, d]) => ({ member: mask(e), hub: mask(d.hub), here: mask(d.here), how: d.how, at: d.at })), disagreeTotal: Object.keys(st.disagree).length }; } -module.exports = { init, on, receive, touch, onChain, flush, tick, adminView }; +module.exports = { init, on, receive, touch, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } }; diff --git a/qa/hubsync.test.cjs b/qa/hubsync.test.cjs index d41cf15..3711ce7 100644 --- a/qa/hubsync.test.cjs +++ b/qa/hubsync.test.cjs @@ -13,6 +13,11 @@ const HUB_DIR = process.env.HUB_DIR || [path.join(__dirname, '..', '..', 'networ const LS_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-hub-')); const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-data-')); const LS_SECRET = 'l'.repeat(40), CTB_SECRET = 'c'.repeat(40); delete process.env.DATABASE_URL; delete process.env.HUB_ENABLED; +// mail audit (2026-11-14): every outbound request this process makes is recorded; only the local hub and site may be called. +// mailer.js sends over https, Telegram and Sendy too, so both doors are watched. +const outside = []; +{ const realFetch = global.fetch; global.fetch = (u, o) => { const s = String(u && u.url ? u.url : u); if (!/^http:[/][/]127[.]0[.]0[.]1:/.test(s)) outside.push(s); return realFetch(u, o); }; + const https = require('https'); const realReq = https.request; https.request = function (...a) { outside.push('https ' + JSON.stringify((a[0] && a[0].hostname) || a[0])); return realReq.apply(this, a); }; } const accounts = require(path.join(__dirname, '..', 'accounts.js')); const registry = require(path.join(__dirname, '..', 'registry.js')); const carry = require(path.join(__dirname, '..', 'carry.js')); @@ -20,6 +25,9 @@ const hubsync = require(path.join(__dirname, '..', 'hubsync.js')); accounts.init({ dataDir: LS_DIR }); registry.init({ dataDir: LS_DIR }); hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null }); accounts.onChange(e => hubsync.touch(e)); +// the wallet hook as server.js wires it: the engine would switch payouts on (gas, a lock, the "payouts are switched on" mail) +const activations = []; +accounts.onWalletLinked(async email => { if (hubsync.isQuiet(email)) return; activations.push(email); }); const E = n => n + '@example.test'; const W = n => '0x' + String(n).padStart(40, '0'); @@ -143,7 +151,82 @@ const W = n => '0x' + String(n).padStart(40, '0'); assert.strictEqual(tur.bindings.linkspin.spentCents, 1000, 'one purchase counted once'); assert.strictEqual(tur.sponsorId, per(E('ptw')).id, 'the earlier spend (InstantAdPay) still decides'); assert.strictEqual(hubsync.adminView().stats.spends, 1); - console.log('hubsync: ok (11 checks)'); + // 12. rule 2 on arrival (2026-11-14): someone the LinkSpin contract holds arrives under THAT lock's sponsor, not the network + // sponsor (another contract where money was spent); a later sponsor.changed never moves them + const HP = require(path.join(HUB_DIR, 'lib', 'people.js')); + await ctb('/v1/join', { email: E('lx'), username: 'lockx' }); await ctb('/v1/join', { email: E('ly'), username: 'locky' }); + await ctb('/v1/join', { email: E('lk'), username: 'lockkid', ref: 'locky' }); + HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: E('lk'), wallet: W(81), sponsorRef: 'lockx', at: 1000 }); + HP.bindContract({ site: 'iap', contract: 'iap', email: E('lk'), wallet: W(81), sponsorRef: 'locky', at: 2000, spentCents: 2500 }); + await hstore.flush(); + assert.strictEqual(per(E('lk')).sponsorId, per(E('ly')).id, 'network sponsor = InstantAdPay (money spent there)'); + await hooks.tick(); + assert.strictEqual((await accounts.sponsorOf(E('lk'))).email, E('lx'), 'the LinkSpin lock sponsor is written here'); + const lkSeq = lastSeq() + 1000; + const evRaw = JSON.stringify({ events: [{ seq: lkSeq, type: 'sponsor.changed', personId: per(E('lk')).id, data: { by: 'contract', contract: 'iap' } }] }); const evTs = String(Date.now()); + assert.strictEqual((await hubsync.receive({ 'x-hub-ts': evTs, 'x-hub-sig': crypto.createHmac('sha256', LS_SECRET).update(evTs + '\n' + evRaw).digest('hex') }, evRaw)).status, 200); + assert.strictEqual((await accounts.sponsorOf(E('lk'))).email, E('lx'), 'sponsor.changed is ignored'); + hstore.setCursor('linkspin', lastSeq()); await hstore.flush(); // the test event above moved lastSeq past the hub's numbering + const st0 = JSON.parse(fs.readFileSync(path.join(LS_DIR, 'hubsync.json'), 'utf8')); st0.lastSeq = lastSeq(); fs.writeFileSync(path.join(LS_DIR, 'hubsync.json'), JSON.stringify(st0)); + hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null }); + + // 13. rule 3: the tank never offers anyone locked on any network contract, sponsored in the hub, or a hub waiting copy that + // never signed in here; release refuses a locked member. Tank as server.js wires it, mailer and messages only record. + const tank = require(path.join(__dirname, '..', 'tank.js')); + const sent = []; + const mailer = { hasKey: () => true, send: async (...a) => { sent.push(['mail', a[0], a[1]]); } }; + const messages = { sendChat: async (...a) => { sent.push(['chat', a[2]]); }, deliver: async (...a) => { sent.push(['notice', a[2]]); }, lastFrom: async () => Date.now() }; + tank.init({ dataDir: LS_DIR, accounts, chain: { recentEvents: () => [], memberIdByAccount: async () => 0 }, messages, mailer, + hooks: { network: async e => hubsync.hubSponsor(e), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } }); + await ctb('/v1/join', { email: E('hs') }); await hooks.tick(); // a CTB join with no sponsor anywhere: a waiting copy here + assert.ok(await accounts.byEmail(E('hs')), 'waiting copy made'); + await ctb('/v1/join', { email: E('tk1'), username: 'tk1ctb', ref: 'ann' }); // the hub knows a sponsor + for (const n of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(E(n), '', '', null)).created); // signed up here, no sponsor + await hubsync.flush(); + HP.bindContract({ site: 'iap', contract: 'iap', email: E('tk2'), wallet: W(82), sponsorRef: '' }); await hstore.flush(); // locked, top of that tree + hubsync._heldReset(); + const held = await hubsync.heldAmong(await Promise.all(['tk1', 'tk2', 'tk3', 'hs'].map(n => accounts.byEmail(E(n))))); + assert.deepStrictEqual([...held.entries()].sort(), [[E('hs'), 'hub-shell'], [E('tk1'), 'sponsored'], [E('tk2'), 'locked']]); + let w = (await tank.waiting()).map(x => x.email); + assert.ok(w.includes(E('tk3')), 'a free member is offered'); + for (const n of ['tk1', 'tk2', 'hs']) assert.ok(!w.includes(E(n)), n + ' is not offered: ' + w.join(',')); + await accounts.setSponsorRef(E('tk2'), 'zed'); + const rel = await tank.release(E('zed'), E('tk2')); + assert.ok(rel.error && /locked/.test(rel.error), JSON.stringify(rel)); assert.strictEqual((await accounts.sponsorOf(E('tk2'))).email, E('zed')); + await tank.readyTick(); assert.strictEqual((await accounts.byEmail(E('tk1'))).sponsorRef || '', '', 'alignment from the hub is off by default'); + process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN; // aligns tk1 to the sponsor the hub knows, and leaves the waiting copy alone + assert.strictEqual((await accounts.sponsorOf(E('tk1'))).email, E('ann'), 'aligned to the hub sponsor'); + assert.strictEqual((await accounts.byEmail(E('hs'))).sponsorRef || '', '', 'the waiting copy is not touched'); + + // 14. fail-safe: hub unreachable past the 1-hour cache = held; within the hour the last answer stands; back = offered again + process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000); + assert.ok((await tank.waiting()).map(x => x.email).includes(E('tk3')), 'within the hour'); + hubsync._heldReset(); + assert.ok(!(await tank.waiting()).map(x => x.email).includes(E('tk3')), 'unknown = held'); + assert.strictEqual(await hubsync.lockedAnywhere(E('tk3')), 'unknown'); + process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; hubsync._heldReset(); + assert.ok((await tank.waiting()).map(x => x.email).includes(E('tk3'))); + + // 15. mail audit: hub arrivals with wallets (new, sponsor climbed first, an empty wallet filled later) switch nothing on and + // send no mail, chat, notice or outside call; neither do the tank ticks afterwards + sent.length = 0; outside.length = 0; activations.length = 0; + await ctb('/v1/join', { email: E('ma'), username: 'mailtop' }); await ctb('/v1/wallet', { email: E('ma'), wallet: W(83) }); + await ctb('/v1/join', { email: E('mb'), username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: E('mb'), wallet: W(84) }); + await ctb('/v1/join', { email: E('mc'), username: 'mailfill' }); + const mbEv = hstore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === per(E('mb')).id); + hstore.setCursor('linkspin', mbEv.seq - 1); await hstore.flush(); // the kid's join first: the sponsor is placed from the hub + await hooks.tick(); + await ctb('/v1/wallet', { email: E('mc'), wallet: W(85) }); await hooks.tick(); // wallet.connected on a waiting copy + assert.strictEqual((await accounts.byEmail(E('mb'))).address, W(84)); assert.strictEqual((await accounts.byEmail(E('mc'))).address, W(85)); + assert.strictEqual((await accounts.sponsorOf(E('mb'))).email, E('ma')); + await hubsync.flush(); await tank.readyTick(); await tank.sweep(); + assert.deepStrictEqual(activations, [], 'no payouts switch-on for wallets filled from the hub'); + assert.deepStrictEqual(sent, [], 'nothing sent'); + assert.deepStrictEqual(outside, [], 'no outside call'); + const loaded = Object.keys(require.cache).map(f => path.basename(f)); + for (const m of ['mailer.js', 'sendy.js', 'messages.js', 'drip.js']) assert.ok(!loaded.includes(m), m + ' is loaded'); + await accounts.linkWallet(E('tk3'), W(86)); assert.deepStrictEqual(activations, [E('tk3')], 'a wallet linked here still switches payouts on'); + console.log('hubsync: ok (15 checks)'); } finally { hub.close(); ls.close(); } process.exit(0); })().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); }); diff --git a/server.js b/server.js index aa2f584..eb319b7 100644 --- a/server.js +++ b/server.js @@ -733,7 +733,7 @@ async function boot() { setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first. // Not while a deliberate sponsor change from InstantAdPay is still waiting to be applied (afterResolve above does it then). - accounts.onWalletLinked(async email => { if (followStore.pendingFor(email)) { console.log('activation deferred: sponsor follow pending for', email); return; } const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); }); + accounts.onWalletLinked(async email => { if (hubsync.isQuiet(email)) { console.log('activation skipped: wallet filled from a network hub event (quiet)'); return; } if (followStore.pendingFor(email)) { console.log('activation deferred: sponsor follow pending for', email); return; } const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); }); // member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000); // reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest @@ -767,7 +767,10 @@ async function boot() { tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore, // network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never // bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held) - hooks: { network: (email, address) => networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }), + // network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports + // locked on a network contract or sponsored is offered, moved to the tank or auto-assigned (hubsync.js: cache + fail-safe) + hooks: { network: async (email, address) => (hubsync.on() ? await hubsync.hubSponsor(email).catch(() => null) : null) || networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }), + networkHeld: accts => (hubsync.on() ? hubsync.heldAmong(accts) : new Map()), networkLocked: email => (hubsync.on() ? hubsync.lockedAnywhere(email) : null), iapOwns: (email, o) => iapOwnsTank(email, o), bound: async a => { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) await accounts.setMemberId(a.email, id).catch(() => {}); return id; }, payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1, notify: (email, subject, text) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, '

' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s)]+)/g, '$1') + '

'), diff --git a/tank.js b/tank.js index f850cf1..a218514 100644 --- a/tank.js +++ b/tank.js @@ -86,11 +86,28 @@ const countAll = async email => (await impl().countFor(email)) + remoteCount(ema const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email)); const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or fell back), still free +// Rule 3 (Marty 2026-11-14): never offer anyone locked on ANY network contract or whom the network hub already knows a sponsor +// for, nor a waiting copy the hub made here for someone who never signed in here (their own door's tank has them). +// hooks.networkHeld = hubsync.heldAmong, wired only with HUB_ENABLED. A hook that throws holds everyone it was asked about: +// the conservative side. No hook (flag off, tests) = nothing held, the tank as before. +const lc = v => String(v || '').trim().toLowerCase(); +async function heldSet(accts) { + if (!hooks.networkHeld || !accts.length) return new Map(); + try { return (await hooks.networkHeld(accts)) || new Map(); } catch (e) { console.error('tank networkHeld', e.message); return new Map(accts.map(a => [lc(a.email), 'unknown'])); } +} +const HELD_WHY = { locked: 'they are locked on a network contract', sponsored: 'it already knows a sponsor for them', unknown: 'nothing (it is not answering)', 'hub-shell': 'they are a waiting copy from another door and never signed in here' }; +// release / rescue / expiry: 'locked' | 'unknown' | null (hooks.networkLocked = hubsync.lockedAnywhere) +async function lockedWhy(email) { + if (!hooks.networkLocked) return null; + try { return (await hooks.networkLocked(email)) || null; } catch (e) { return 'unknown'; } +} // waiting list: newest sign-in first so a live one is easy to spot async function waiting() { const all = await accounts.listAll(1e6); // was 2000: newest-first, so once the site passed 2000 accounts (BTC4Hits import 2026-11-11) older tank members fell off the list - return all.filter(a => inTank(a) && !remoteOpen(a.email)).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: !!a.address, + const cand = all.filter(a => inTank(a) && !remoteOpen(a.email)); + const held = await heldSet(cand); // rule 3: locked or sponsored elsewhere + return cand.filter(a => !held.has(lc(a.email))).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: !!a.address, // wallet linked = ready to switch on payouts, the plain activation held for an adopter (24-hour clock, autoAssign after that) opensAt: inGrace(a) ? graceEnd(a) : 0, // new sign-up: nobody can adopt them by hand before this (0 = open now) ...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() })) @@ -183,6 +200,8 @@ async function release(ownerEmail, directEmail) { const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String); if (!toks.includes(String(direct.sponsorRef || ''))) return { error: 'That member is not in your line.' }; if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' }; + const lk = await lockedWhy(d); // rule 3: someone a network contract holds never goes to the tank + if (lk) return { error: lk === 'locked' ? nameOf(direct) + ' is locked to a sponsor on a network contract, so they cannot go to the holding tank.' : 'The network record for ' + nameOf(direct) + ' cannot be checked right now. Try again in a few minutes.' }; // picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13) const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d); let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS); @@ -213,6 +232,9 @@ async function sweep() { if (!a) { await impl().setStatus(ad.id, 'expired'); continue; } if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; } if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; } + const lk = await lockedWhy(ad.adoptee); // rule 3: a person a network contract holds stays with the adopter, never back in the tank + if (lk === 'unknown') continue; // the hub is not answering: try again next hour + if (lk === 'locked') { await impl().setStatus(ad.id, 'expired'); kept++; continue; } await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended'); await impl().setStatus(ad.id, 'expired'); back++; } @@ -281,11 +303,14 @@ async function rescueSweep() { if (String(process.env.TANK_RESCUE || '').trim() !== 'on') return { warned: 0, rescued: 0, dead: 0, off: true }; const now = Date.now(); let warned = 0, rescued = 0, dead = 0; - for (const a of await accounts.listAll(5000)) { + const all = await accounts.listAll(5000); + await heldSet(all.filter(a => !a.memberId && !a.address && a.sponsorRef)); // one batched hub call warms the cache for lockedWhy below + for (const a of all) { if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules const pv = store && store.get(a.email); if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on InstantAdPay: the tank's window rules there + if (await lockedWhy(a.email)) continue; // rule 3: locked on a network contract (or the hub is not answering): no warning, no move const sp = await sponsorOf(a); if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day if (now - (a.created || 0) < 86400000) continue; @@ -412,7 +437,7 @@ async function alignToNetwork(a, opts) { const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null; const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null; const st = RS.load(); const via = n.via || 'same email'; - const why = 'aligned to network sponsor ' + nameOf(sp) + ' from InstantAdPay (' + via + ')'; + const why = 'aligned to network sponsor ' + nameOf(sp) + (/hub/.test(via) ? ' (' + via + ')' : ' from InstantAdPay (' + via + ')'); st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via, at: clock(), why }); if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300); if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; } @@ -482,8 +507,14 @@ async function autoAssignRun() { due.push([e, rec, a]); } due.sort((x, y) => x[1].readyAt - y[1].readyAt); + const netHeld = await heldSet(due.map(x => x[2])); let pool = null; for (const [e, rec, a] of due) { + if (netHeld.has(e)) { // rule 3: never auto-assigned; the admin hears once (their network sponsor has no usable account here yet, or the hub is not answering) + out.held++; + if (!rec.networkHeldAlerted) { rec.networkHeldAlerted = clock(); RS.save(); if (hooks.adminAlert && await claimOnce('tanknetheld:' + e + ':' + rec.readyAt)) { try { await hooks.adminAlert('LinkSpin holding tank: ' + nameOf(a) + ' (' + e + ') is held and NOT auto-assigned: the network hub says ' + (HELD_WHY[netHeld.get(e)] || netHeld.get(e)) + ', and no sponsor for them could be used here. Set their sponsor in Admin if it should be someone here.'); } catch (err) {} } } + continue; + } // the double-assign guard: InstantAdPay holds this person in its own tank, so its safety net assigns them (asked fresh) if (hooks.iapOwns && await Promise.resolve(hooks.iapOwns(e, { fresh: true })).catch(() => false)) { out.deferred++; if (!rec.deferred) { rec.deferred = clock(); RS.save(); } continue; } if (!(await claimOnce('tankauto:' + e + ':' + Math.floor(clock() / 600000)))) continue; // the other app copy (deploy overlap) has this one @@ -522,9 +553,12 @@ async function readyTick() { const st = RS.load(); const fresh = []; let aligned = 0; const tankers = (await accounts.listAll(5000)).filter(inTank); if (hooks.prefetch) { try { await hooks.prefetch(tankers.map(a => a.email)); } catch (e) {} } // one signed batch call to InstantAdPay, not one per member + const netHeld = await heldSet(tankers); // one batched hub call; alignToNetwork below reads the same cache for (const a of tankers) { + if (netHeld.get(lc(a.email)) === 'hub-shell') continue; // a waiting copy from another door: no alignment, no payouts switch-on here (quiet) if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; } if (remoteOpen(a.email)) continue; + if (netHeld.has(lc(a.email))) continue; // rule 3: not announced, no 24-hour clock while the network holds them const rec = markReady(a); // Sign-up grace (2026-11-07): no "adopt them" post for someone who cannot be adopted yet; announced when the grace ends, // and not at all when the safety net takes them in this same tick (nothing left for anyone to do)