thumbgate 1.40.5 → 1.40.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,6 +61,12 @@ const {
61
61
 
62
62
  const AUDIT_TRAIL_TAG = 'audit-trail';
63
63
  const FEEDBACK_EVENT_DEDUPE_WINDOW_MS = 5 * 60 * 1000;
64
+ // Two deliveries of the SAME typed thumbs event (live hook plus Claude history
65
+ // sync) carry event timestamps seconds apart. A typed "thumbs down" that
66
+ // arrives later than this is a new prompt and must count, even when the text
67
+ // and session match. (22 Nov 2026: repeats 2 and 4 minutes after the first were
68
+ // swallowed as duplicates and the status-bar counter stayed at 1.)
69
+ const FEEDBACK_EVENT_REPEAT_GAP_MS = 30 * 1000;
64
70
  const FEEDBACK_EVENT_CLAIM_STALE_MS = 60 * 1000;
65
71
  const FEEDBACK_EVENT_CLAIM_WAIT_MS = 15 * 1000;
66
72
  const FEEDBACK_EVENT_CLAIM_POLL_MS = 25;
@@ -259,6 +265,22 @@ function updateStatuslineWithLesson({ accepted, signal, memoryId, feedbackId, le
259
265
  } catch { /* statusline update is best-effort */ }
260
266
  }
261
267
 
268
+ /**
269
+ * Re-count the status-bar thumbs after a capture that was logged but not
270
+ * promoted (lifecycle block, schema failure). The signal is in the feedback
271
+ * log, so the counter must include it; without this the cache kept its old
272
+ * counts until the next accepted capture.
273
+ */
274
+ function refreshStatuslineCounts() {
275
+ try {
276
+ const cachePath = path.join(getFeedbackPaths().FEEDBACK_DIR, 'statusline_cache.json');
277
+ const { refreshStatuslineCache } = require('./hook-thumbgate-cache-updater');
278
+ refreshStatuslineCache(analyzeFeedback(undefined, { humanOnly: true }), cachePath);
279
+ } catch {
280
+ /* statusline refresh is best-effort */
281
+ }
282
+ }
283
+
262
284
  function getFeedbackPaths(options = {}) {
263
285
  return resolveFeedbackPaths(options);
264
286
  }
@@ -937,7 +959,7 @@ function isDuplicateFeedbackEntry(entry, identity) {
937
959
  if (identity.promptIdHash && sourceEvent.promptIdHash === identity.promptIdHash) return true;
938
960
 
939
961
  const timestamp = parseFeedbackSourceTimestamp(sourceEvent.timestamp || entry.timestamp);
940
- return Math.abs(identity.eventTimestampMs - timestamp) <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS;
962
+ return Math.abs(identity.eventTimestampMs - timestamp) <= FEEDBACK_EVENT_REPEAT_GAP_MS;
941
963
  }
942
964
 
943
965
  function receiptFromFeedbackEntry(entry, paths) {
@@ -976,10 +998,17 @@ function tryCreateFeedbackClaim(claimPath) {
976
998
  function existingClaimResult(state, identity, paths) {
977
999
  const stateTimestamp = Number(state?.completedAtMs || state?.startedAtMs || 0);
978
1000
  const ageMs = stateTimestamp > 0 ? Date.now() - stateTimestamp : 0;
979
- if (state?.status === 'complete'
980
- && (identity.promptIdHash || ageMs <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS)) {
1001
+ if (state?.status === 'complete' && identity.promptIdHash) {
981
1002
  return duplicateCaptureResult(state, paths);
982
1003
  }
1004
+ if (state?.status === 'complete') {
1005
+ // Compare when the prompts were typed, not when the first capture finished.
1006
+ // Claims written before eventTimestampMs existed fall back to capture age.
1007
+ const sameEvent = Number.isFinite(state.eventTimestampMs)
1008
+ ? Math.abs(identity.eventTimestampMs - state.eventTimestampMs) <= FEEDBACK_EVENT_REPEAT_GAP_MS
1009
+ : ageMs <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS;
1010
+ if (sameEvent) return duplicateCaptureResult(state, paths);
1011
+ }
983
1012
  if (state?.status === 'pending' && ageMs <= FEEDBACK_EVENT_CLAIM_STALE_MS) {
984
1013
  return duplicateCaptureResult(state, paths, { pending: true });
985
1014
  }
@@ -1010,10 +1039,11 @@ function acquireFeedbackEventClaim(identity, paths) {
1010
1039
  };
1011
1040
  }
1012
1041
 
1013
- function finalizeFeedbackEventClaim(claim, result) {
1042
+ function finalizeFeedbackEventClaim(claim, result, identity) {
1014
1043
  if (!claim?.owned) return;
1015
1044
  writeClaimState(claim.claimPath, {
1016
1045
  status: 'complete',
1046
+ eventTimestampMs: identity?.eventTimestampMs ?? null,
1017
1047
  startedAtMs: Date.now(),
1018
1048
  completedAtMs: Date.now(),
1019
1049
  accepted: Boolean(result?.accepted),
@@ -1719,6 +1749,7 @@ function captureFeedback(params, options = {}) {
1719
1749
  };
1720
1750
  appendJSONL(FEEDBACK_LOG_PATH, blockedEvent);
1721
1751
  emitAnonymousFeedbackPing(signal);
1752
+ refreshStatuslineCounts();
1722
1753
  return {
1723
1754
  accepted: true,
1724
1755
  captured: true,
@@ -1751,6 +1782,7 @@ function captureFeedback(params, options = {}) {
1751
1782
  validationIssues: prepared.issues,
1752
1783
  });
1753
1784
  emitAnonymousFeedbackPing(signal);
1785
+ refreshStatuslineCounts();
1754
1786
  try { appendRejectionLedger(feedbackEvent, `Schema validation failed: ${prepared.issues.join('; ')}`, options); } catch { /* non-critical */ }
1755
1787
  try {
1756
1788
  appendSequence(historyEntries, feedbackEvent, getFeedbackPaths(options), { accepted: false });
@@ -2184,7 +2216,7 @@ function captureFeedbackIdempotent(params = {}, options = {}) {
2184
2216
 
2185
2217
  try {
2186
2218
  const result = captureFeedback({ ...params, sourceEvent: identity }, options);
2187
- finalizeFeedbackEventClaim(claim, result);
2219
+ finalizeFeedbackEventClaim(claim, result, identity);
2188
2220
  return result;
2189
2221
  } catch (error) {
2190
2222
  releaseFeedbackEventClaim(claim);
@@ -13,7 +13,7 @@ const JSON_LIMIT = 8 * 1024 * 1024;
13
13
  const LOG_LIMIT = 16 * 1024 * 1024;
14
14
  const RESPONSE_LIMIT = 1024 * 1024;
15
15
  const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
16
- const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability']);
16
+ const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary']);
17
17
  const MONEY_CACHE_MS = 60000;
18
18
  let moneyCache = null;
19
19
  const PRIVATE_HEADERS = Object.freeze({ 'Cache-Control': 'private, no-store', Vary: 'Cookie', 'X-Robots-Tag': 'noindex, nofollow', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' });
@@ -264,6 +264,8 @@ async function collectData(route, deps, signal) {
264
264
  const key = joined || 'sso:' + email;
265
265
  if (!accounts.has(key)) accounts.set(key, { customerId: null, email, createdAt: Number.isFinite(session.createdAt) ? new Date(session.createdAt).toISOString() : null, hasActiveKey: false, hasCurrentSession: true, possibleDuplicate: Boolean(matches?.size > 1), freeEmails: new Set() });
266
266
  accounts.get(key).hasCurrentSession = true;
267
+ // A paid key can carry no email of its own; the signed-in session's email is the identity that joined it.
268
+ (accounts.get(key).sessionEmails ||= new Set()).add(email);
267
269
  if (!session.customerId || session.subjectType === 'sso_free') accounts.get(key).freeEmails.add(email);
268
270
  }
269
271
  const ordered = [...accounts.entries()].sort(([a], [b]) => a.localeCompare(b));
@@ -278,7 +280,7 @@ async function collectData(route, deps, signal) {
278
280
  const counts = [];
279
281
  for (const partition of partitions) counts.push(await countPartition(root, partition, signal));
280
282
  if (counts.some((row) => row.state === 'partial')) warnings.push('account_counts_partial');
281
- records.push({ accountId: account.customerId ? text(account.customerId, 128) : [...partitions][0], email: text(account.email, 320), createdAt: account.createdAt, hasActiveKey: account.hasActiveKey, hasCurrentSession: account.hasCurrentSession, possibleDuplicate: account.possibleDuplicate === true, classification: billing.classifyRevenueRecord({ email: account.email }), partitions: counts });
283
+ records.push({ accountId: account.customerId ? text(account.customerId, 128) : [...partitions][0], email: text(account.email, 320), createdAt: account.createdAt, hasActiveKey: account.hasActiveKey, hasCurrentSession: account.hasCurrentSession, possibleDuplicate: account.possibleDuplicate === true, classification: billing.classifyRevenueRecord({ email: account.email, identityEmails: [...(account.sessionEmails || [])] }), partitions: counts });
282
284
  }
283
285
  stopped(signal);
284
286
  const feedback = await countRecords(root, path.join(root, 'feedback-log.jsonl'), signal);
@@ -415,7 +417,7 @@ async function readSummary(deps, signal) {
415
417
  if (deps.getBillingSummaryLive) {
416
418
  const injected = await deps.getBillingSummaryLive({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal });
417
419
  if (!injected || injected.error) throw failure('analytics_unavailable');
418
- return { value: summaryParts(injected), state: 'ok' };
420
+ return { value: summaryParts(injected), state: 'ok', collectedAt: new Date().toISOString() };
419
421
  }
420
422
  const fresh = summarySnapshot.value && Date.now() - summarySnapshot.at < SUMMARY_TTL_MS;
421
423
  if (!fresh) startSummaryWorker();
@@ -424,7 +426,7 @@ async function readSummary(deps, signal) {
424
426
  await Promise.race([summarySnapshot.inflight, new Promise((resolve) => { const timer = setTimeout(resolve, 7000); timer.unref?.(); })]);
425
427
  }
426
428
  const state = summarySnapshot.value ? (fresh ? 'ok' : 'stale') : (summarySnapshot.failed ? 'failed' : 'refreshing');
427
- return { value: summarySnapshot.value, state };
429
+ return { value: summarySnapshot.value, state, collectedAt: summarySnapshot.at ? new Date(summarySnapshot.at).toISOString() : null };
428
430
  }
429
431
 
430
432
  // 30 days of site traffic, streamed from the newest end of the telemetry log. Cached for a minute.
@@ -434,6 +436,7 @@ async function readTraffic(deps, signal) {
434
436
  const hit = trafficCache.get(key);
435
437
  if (ttl > 0 && hit && Date.now() - hit.at < ttl) return hit.value;
436
438
  const value = await ownerTelemetry.readTrafficWindow({ feedbackDir: guardPath(deps.feedbackDir, deps.feedbackDir), days: 30, signal, maxBytes: deps.telemetryMaxBytes });
439
+ value.collectedAt = new Date().toISOString();
437
440
  if (ttl > 0) trafficCache.set(key, { at: Date.now(), value });
438
441
  return value;
439
442
  }
@@ -492,7 +495,7 @@ const attempt = async (work, reasonOf) => {
492
495
  };
493
496
  const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'telemetry read timed out' : 'telemetry read failed');
494
497
 
495
- const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
498
+ const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, pageViewers: read.traffic.pageViewers, checkoutStartsByType: read.traffic.checkoutStartsByType, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
496
499
 
497
500
  // Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
498
501
  // Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
@@ -501,7 +504,10 @@ async function collectMoney(deps, signal) {
501
504
  if (ttl > 0 && moneyCache && Date.now() - moneyCache.at < ttl) return moneyCache.value;
502
505
  const ownerEmails = (deps.getOwnerEmails || require('./bot-detection').getOwnerEmails)();
503
506
  const stripe = () => (deps.getStripeClient || billing.getStripeClient)();
504
- const { countSessions, classifySession } = require('./checkout-session-count');
507
+ const { countSessions, classifySession, BOT_CHECK_BEGAN_AT, BOT_CHECK_BEGAN_LABEL } = require('./checkout-session-count');
508
+ // A test may move the date; production always uses the date the human-click gate went live.
509
+ const botCheckBeganAt = deps.botCheckBeganAt || BOT_CHECK_BEGAN_AT;
510
+ const botCheckBeganLabel = deps.botCheckBeganAt ? deps.botCheckBeganAt : BOT_CHECK_BEGAN_LABEL;
505
511
  const nowSeconds = Math.floor(Date.now() / 1000);
506
512
 
507
513
  // One deadline for all of Stripe's reads, shared by every block below.
@@ -561,7 +567,18 @@ async function collectMoney(deps, signal) {
561
567
  withLastGood('checkouts', async () => {
562
568
  const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options), { created: { gte: nowSeconds - 30 * 86400 } }, thumbgateSession, 40);
563
569
  const since7 = nowSeconds - 7 * 86400;
564
- return { d30: countSessions(result.rows, { ownerEmails }), d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }), complete: result.complete };
570
+ // Sessions made before the bot check carry no user-agent class, so they are reported apart from the ones after it.
571
+ const botCheckSeconds = Date.parse(botCheckBeganAt) / 1000;
572
+ const beforeBotCheck = (row) => Boolean(row.created) && row.created < botCheckSeconds;
573
+ const classified = result.rows.filter((row) => row.metadata?.uaClass && row.created).map((row) => row.created);
574
+ return {
575
+ d30: countSessions(result.rows, { ownerEmails }),
576
+ d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }),
577
+ before: countSessions(result.rows.filter(beforeBotCheck), { ownerEmails }),
578
+ since: countSessions(result.rows.filter((row) => !beforeBotCheck(row)), { ownerEmails }),
579
+ firstClassifiedAt: classified.length ? new Date(Math.min(...classified) * 1000).toISOString() : null,
580
+ complete: result.complete,
581
+ };
565
582
  }),
566
583
  attempt(() => readTraffic(deps, signal), telemetryReason),
567
584
  attempt(() => readSummary(deps, signal), () => 'lead ledgers failed'),
@@ -589,8 +606,47 @@ async function collectMoney(deps, signal) {
589
606
  internal: counts.excluded.internal,
590
607
  } : null);
591
608
  const bothStripe = paid && proRun.value;
609
+ // The checkout panel: sessions with no bot check on record come first, then people, bots and owner only for sessions
610
+ // created after the bot check began, then the gap between the site's own start events and Stripe's sessions.
611
+ const checkoutBotCheck = (counts, traffic) => {
612
+ if (!counts) return null;
613
+ const stripeSessions = counts.d30.started;
614
+ const siteStarts = traffic ? traffic.traffic.checkoutStarts : null;
615
+ const difference = siteStarts === null ? null : siteStarts - stripeSessions;
616
+ return {
617
+ window: '30d',
618
+ botCheckBeganAt,
619
+ botCheckBeganLabel,
620
+ firstClassifiedAt: counts.firstClassifiedAt,
621
+ notClassified: sessionBuckets(counts.d30).notClassified,
622
+ beforeBotCheck: sessionBuckets(counts.before),
623
+ sinceBotCheck: sessionBuckets(counts.since),
624
+ siteVersusStripe: siteStarts === null ? null : {
625
+ siteStarts,
626
+ siteStartsByType: traffic.traffic.checkoutStartsByType || {},
627
+ stripeSessions,
628
+ difference,
629
+ status: difference === 0 ? 'match' : 'unexplained',
630
+ reason: difference === 0 ? 'The two counts match.'
631
+ : 'Unexplained. The site count adds up four kinds of start events (listed here); Stripe counts the sessions it created. They are not matched one to one, so the gap is not itemised.',
632
+ },
633
+ };
634
+ };
635
+ // When each source was last read. A block showing its last good value reports that older time and `stale: true`.
636
+ const blockTime = (key) => ({ collectedAt: new Date(staleBlocks[key] || Date.now()).toISOString(), stale: Object.hasOwn(staleBlocks, key) });
637
+ const freshness = {
638
+ paid: blockTime('paid'),
639
+ subscriptions: blockTime('subscriptions'),
640
+ checkouts: blockTime('checkouts'),
641
+ traffic: { collectedAt: trafficRead?.collectedAt || null, stale: false },
642
+ leads: { collectedAt: summaryRun.value?.collectedAt || null, stale: summaryRun.value?.state === 'stale' },
643
+ displayRefreshedAt: new Date().toISOString(),
644
+ telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000),
645
+ billingSummaryCacheSeconds: SUMMARY_TTL_MS / 1000,
646
+ };
592
647
  const data = {
593
648
  windows: { revenue: '30d', checkouts: '7d', traffic: '30d', leads: '30d' },
649
+ freshness,
594
650
  // Counted straight from Stripe: people with a paid, unrefunded checkout in the past year plus active subscribers, once each.
595
651
  payingCustomers: bothStripe ? new Set([...paid.customers, ...proRun.value.customers]).size : null,
596
652
  payingCustomersSource: 'stripe',
@@ -601,6 +657,7 @@ async function collectMoney(deps, signal) {
601
657
  revenueBasis: 'stripe_paid_checkouts_after_refunds',
602
658
  checkouts7d: sessionBuckets(sessions?.d7),
603
659
  checkouts30d: sessionBuckets(sessions?.d30),
660
+ checkoutBotCheck: checkoutBotCheck(sessions, trafficReason ? null : trafficRead),
604
661
  traffic30d: trafficReason ? null : { ...trafficFields(trafficRead), partial: trafficRead.partial },
605
662
  leadsBySource: parts ? parts.leads : null,
606
663
  reasons: {
@@ -656,6 +713,82 @@ async function collectAnalytics(deps, signal) {
656
713
  return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
657
714
  }
658
715
 
716
+ // One metric of the read-only summary: its value, where it came from, when that source was read, and one of these states:
717
+ // ok a number from a source that answered in full
718
+ // verified_zero a zero from a source that answered in full
719
+ // partial a number from a source that answered only in part (a lower bound)
720
+ // stale the last good value, with lastVerifiedAt; the source failed this time
721
+ // unavailable the source failed and there is no earlier value
722
+ // unresolved the source answered but the metric cannot be settled yet (still calculating)
723
+ function metric(label, value, { source, collectedAt = null, reason = null, partial = false, stale = false, unresolved = false }) {
724
+ const missing = value === null || value === undefined;
725
+ let status = 'ok';
726
+ if (missing) status = unresolved ? 'unresolved' : 'unavailable';
727
+ else if (stale) status = 'stale';
728
+ else if (partial) status = 'partial';
729
+ else if (value === 0) status = 'verified_zero';
730
+ const out = { label, value: missing ? null : value, source, collectedAt, status };
731
+ if (reason && (missing || stale || partial)) out.reason = reason;
732
+ if (stale && !missing) out.lastVerifiedAt = collectedAt;
733
+ return out;
734
+ }
735
+
736
+ // GET /v1/admin/summary: the numbers the Money and Analytics tabs show, as JSON an agent can read instead of scraping HTML.
737
+ async function collectSummary(deps, signal) {
738
+ const [moneyRun, analyticsRun] = await Promise.all([
739
+ attempt(() => collectMoney(deps, signal), () => 'Money collection failed'),
740
+ attempt(() => collectAnalytics(deps, signal), () => 'Analytics collection failed'),
741
+ ]);
742
+ const money = moneyRun.ok ? moneyRun.value.data : null;
743
+ const analytics = analyticsRun.ok ? analyticsRun.value.data : null;
744
+ const why = money?.reasons || {};
745
+ const fresh = money?.freshness || {};
746
+ const refreshed = money?.freshness?.displayRefreshedAt || new Date().toISOString();
747
+ const stripeOpts = (key, reason) => ({ source: 'stripe', collectedAt: fresh[key]?.collectedAt || null, stale: Boolean(fresh[key]?.stale), reason });
748
+ const trafficOpts = { source: 'site_telemetry', collectedAt: fresh.traffic?.collectedAt || null, reason: why.visitors, partial: money?.traffic30d?.partial === true };
749
+ const leadOpts = { source: 'lead_ledgers', collectedAt: fresh.leads?.collectedAt || null, reason: why.leads, stale: Boolean(fresh.leads?.stale), unresolved: /still calculating/i.test(why.leads || '') };
750
+ const fields = {};
751
+ const add = (key, label, value, options) => { fields[key] = metric(label, value, options); };
752
+ const buckets = (prefix, label, block, reason) => {
753
+ for (const [name, words] of [['started', 'started'], ['human', 'browser-classified'], ['bot', 'bot-classified'], ['notClassified', 'with insufficient classification evidence'], ['internal', 'owner and test']]) add(`${prefix}.${name}`, `Checkout sessions ${words} (${label})`, block ? block[name] : null, stripeOpts('checkouts', why.checkouts));
754
+ };
755
+
756
+ if (money) {
757
+ add('money.paying_customers', 'Paying customers', money.payingCustomers, { ...stripeOpts('paid', why.payingCustomers), partial: money.payingCustomersBasis === 'stripe_paid_and_active_partial' });
758
+ add('money.active_pro', 'Active Pro subscriptions', money.activePro, { ...stripeOpts('subscriptions', why.activePro), partial: money.activeProBasis === 'stripe_active_subscriptions_first_100_only' });
759
+ // collectMoney reads completed Checkout Sessions only, so this is first-charge revenue; renewal invoices never appear in it.
760
+ add('money.revenue_30d', 'One-time checkout revenue, past 30 days, by currency (completed Checkout Sessions after refunds)', money.revenueLast30Days, stripeOpts('paid', why.revenue));
761
+ add('money.subscription_invoices_30d', 'Subscription invoices, past 30 days', null, { source: 'stripe', unresolved: true, reason: 'Not collected yet: renewal invoices are not read, so recurring revenue is not in any revenue number here' });
762
+ buckets('money.checkouts_7d', '7 days', money.checkouts7d);
763
+ buckets('money.checkouts_30d', '30 days', money.checkouts30d);
764
+ const panel = money.checkoutBotCheck;
765
+ add('money.checkout_bot_check', 'Checkout sessions split at the bot check (30 days)', panel, stripeOpts('checkouts', why.checkouts));
766
+ add('money.signups_by_source', 'Signups by source', money.leadsBySource?.signups ?? null, leadOpts);
767
+ add('money.workflow_sprint_leads', 'Setup Sprint leads', money.leadsBySource?.workflowSprint ?? null, leadOpts);
768
+ add('money.newsletter', 'Newsletter signups', money.leadsBySource?.newsletter ?? null, leadOpts);
769
+ }
770
+ const traffic = analytics?.trafficMetrics || money?.traffic30d || null;
771
+ const trafficField = (key, label, name) => add(key, label, traffic ? traffic[name] ?? null : null, trafficOpts);
772
+ trafficField('traffic.visitor_identifiers_all_30d', 'All observed visitor identifiers (30 days)', 'visitors');
773
+ if (money?.traffic30d) add('traffic.visitor_identifiers_excluding_flagged_30d', 'Observed visitor identifiers, excluding bot, internal and test (30 days)', money.traffic30d.realVisitors, trafficOpts);
774
+ trafficField('traffic.landing_page_views_30d', 'Landing page views (30 days)', 'pageViews');
775
+ trafficField('traffic.cta_clicks_30d', 'Call to action clicks (30 days)', 'ctaClicks');
776
+ trafficField('traffic.checkout_starts_30d', 'Checkout starts seen on the site (30 days)', 'checkoutStarts');
777
+ trafficField('traffic.paid_confirmations_30d', 'Paid confirmations (30 days)', 'checkoutPaidConfirmations');
778
+ add('traffic.daily_30d', 'Daily traffic, past 30 days', analytics ? analytics.daily : null, trafficOpts);
779
+ const billingOpts = { source: 'billing_summary', collectedAt: fresh.leads?.collectedAt || null, reason: analyticsRun.ok ? null : analyticsRun.reason, unresolved: !analytics?.signups };
780
+ add('analytics.email_signups', 'Email signups', analytics?.signups?.emailSignups ?? null, billingOpts);
781
+ add('analytics.external_paid_orders', 'External paid orders', analytics?.revenue?.external?.paidOrders ?? null, billingOpts);
782
+ add('analytics.external_booked_revenue_30d', 'External booked revenue, past 30 days, by currency', analytics?.revenue?.external?.bookedRevenueByCurrency ?? null, billingOpts);
783
+
784
+ // A permanent, stated gap is listed apart so the overall state reflects sources that failed, not a feature not built yet.
785
+ const knownGaps = ['money.subscription_invoices_30d'];
786
+ const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key)).map(([, entry]) => entry.status);
787
+ const bad = states.filter((state) => state === 'unavailable').length;
788
+ const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
789
+ return envelope('owner_console_summary', { generatedAt: refreshed, readOnly: true, windows: { checkouts: '7d and 30d', traffic: '30d', revenue: '30d' }, freshness: { displayRefreshedAt: refreshed, stripeCollectedAt: fresh.checkouts?.collectedAt || null, telemetryCollectedAt: fresh.traffic?.collectedAt || null, leadsCollectedAt: fresh.leads?.collectedAt || null, telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000), billingSummaryCacheSeconds: Math.round(SUMMARY_TTL_MS / 1000) }, fields, knownGaps, unavailableFields: bad }, [], overall);
790
+ }
791
+
659
792
  async function collectAdminSection(route, deps, externalSignal) {
660
793
  if (activeCollections >= 2) throw failure('collection_busy');
661
794
  activeCollections += 1;
@@ -669,6 +802,7 @@ async function collectAdminSection(route, deps, externalSignal) {
669
802
  stopped(controller.signal);
670
803
  if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
671
804
  if (route.section === 'money') return collectMoney(deps, controller.signal);
805
+ if (route.section === 'summary') return collectSummary(deps, controller.signal);
672
806
  if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
673
807
  if (route.section === 'data') return collectData(route, deps, controller.signal);
674
808
  if (route.section === 'observability') return collectObservability(deps, controller.signal);
@@ -682,4 +816,4 @@ async function collectAdminSection(route, deps, externalSignal) {
682
816
  }
683
817
  }
684
818
 
685
- module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
819
+ module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
@@ -103,16 +103,22 @@ const isWeb = (entry) => (entry.clientType || entry.client) === 'web';
103
103
  const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal === true || entry.isTest === true;
104
104
 
105
105
  // Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
106
+ //
107
+ // `visitors` is the number of distinct visitor identifiers seen on ANY web event (a click, a checkout step, a page view),
108
+ // so it can exceed `pageViews`, which counts landing_page_view events only. `realVisitors` leaves out identifiers that
109
+ // carried a bot, internal or test flag on any event. `pageViewers` is the identifiers with at least one landing page view.
106
110
  async function readTrafficWindow(options) {
107
111
  const days = new Map();
108
112
  const visitors = new Set();
109
113
  const flagged = new Set();
114
+ const pageViewers = new Set();
110
115
  const sessions = new Set();
116
+ const startsByType = {};
111
117
  const totals = { pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0, webEvents: 0 };
112
118
  const dayOf = (time) => {
113
119
  const key = new Date(time).toISOString().slice(0, 10);
114
120
  let day = days.get(key);
115
- if (!day) { day = { date: key, visitors: new Set(), sessions: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
121
+ if (!day) { day = { date: key, visitors: new Set(), pageViewers: new Set(), sessions: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
116
122
  return day;
117
123
  };
118
124
  const meta = await scanTelemetry({
@@ -125,16 +131,19 @@ async function readTrafficWindow(options) {
125
131
  if (who) { visitors.add(who); day.visitors.add(who); if (isFlagged(entry)) flagged.add(who); }
126
132
  if (entry.sessionId) { sessions.add(entry.sessionId); day.sessions.add(entry.sessionId); }
127
133
  const type = kind(entry);
128
- if (type === 'landing_page_view') { totals.pageViews += 1; day.pageViews += 1; }
134
+ if (type === 'landing_page_view') {
135
+ totals.pageViews += 1; day.pageViews += 1;
136
+ if (who) { pageViewers.add(who); day.pageViewers.add(who); }
137
+ }
129
138
  if (telemetry.isMarketingClickEvent(type) && !telemetry.isDirectStripeBeacon(entry)) { totals.ctaClicks += 1; day.ctaClicks += 1; }
130
- if (telemetry.isCheckoutStartEvent(type)) { totals.checkoutStarts += 1; day.checkoutStarts += 1; }
139
+ if (telemetry.isCheckoutStartEvent(type)) { totals.checkoutStarts += 1; day.checkoutStarts += 1; startsByType[type] = (startsByType[type] || 0) + 1; }
131
140
  if (type === 'checkout_paid_confirmed') { totals.checkoutPaidConfirmations += 1; day.checkoutPaidConfirmations += 1; }
132
141
  },
133
142
  });
134
- const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, sessions: day.sessions.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
143
+ const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
135
144
  return {
136
145
  ...meta,
137
- traffic: { visitors: visitors.size, realVisitors: visitors.size - flagged.size, botOrInternalVisitors: flagged.size, sessions: sessions.size, pageViews: totals.pageViews, ctaClicks: totals.ctaClicks, checkoutStarts: totals.checkoutStarts, checkoutPaidConfirmations: totals.checkoutPaidConfirmations },
146
+ traffic: { visitors: visitors.size, realVisitors: visitors.size - flagged.size, botOrInternalVisitors: flagged.size, pageViewers: pageViewers.size, checkoutStartsByType: startsByType, sessions: sessions.size, pageViews: totals.pageViews, ctaClicks: totals.ctaClicks, checkoutStarts: totals.checkoutStarts, checkoutPaidConfirmations: totals.checkoutPaidConfirmations },
138
147
  daily,
139
148
  };
140
149
  }
package/server.json CHANGED
@@ -8,13 +8,13 @@
8
8
  "source": "github",
9
9
  "url": "https://github.com/IgorGanapolsky/ThumbGate"
10
10
  },
11
- "version": "1.40.5",
11
+ "version": "1.40.6",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "thumbgate",
17
- "version": "1.40.5",
17
+ "version": "1.40.6",
18
18
  "runtimeHint": "npx",
19
19
  "runtimeArguments": [
20
20
  {
@@ -46,14 +46,17 @@ tell application "Comet"
46
46
  end tell'
47
47
 
48
48
  # Open or focus a specific URL in Comet
49
+ # The URL is passed as an argument (item 1 of argv), never spliced into the script text.
49
50
  open_comet_url() {
50
- local target_url="$1"
51
- osascript -e "
52
- tell application \"Comet\"
51
+ osascript - "$1" <<'APPLESCRIPT'
52
+ on run argv
53
+ tell application "Comet"
53
54
  activate
54
55
  tell front window
55
- make new tab with properties {URL:\"${target_url}\"}
56
+ make new tab with properties {URL:(item 1 of argv)}
56
57
  end tell
57
- end tell"
58
+ end tell
59
+ end run
60
+ APPLESCRIPT
58
61
  }
59
62
  ```
package/src/api/server.js CHANGED
@@ -3140,8 +3140,29 @@ function resolveCheckoutIntentPlanView(parsed, includeAttribution = false) {
3140
3140
  };
3141
3141
  }
3142
3142
 
3143
+ // A refused click used to land the buyer on an identical page with no word on
3144
+ // why (headless run: third click in a minute from one IP, 302 back, empty
3145
+ // note). The refusal reason is mapped to one of three fixed notices; only the
3146
+ // code travels in the URL, never free text. Bots and non-browser agents get no
3147
+ // notice because they are not the audience.
3148
+ const CHECKOUT_GATE_NOTICES = Object.freeze({
3149
+ retry: "We couldn't confirm that click. Press the button again.",
3150
+ network: 'Your connection changed while we confirmed the click. Press the button again.',
3151
+ busy: 'Many checkouts are starting from your network right now. Wait a minute, then press the button again.',
3152
+ });
3153
+
3154
+ function checkoutGateNoticeCode(reason) {
3155
+ const text = String(reason || '');
3156
+ if (/^token_(ip|ua)_mismatch$/.test(text)) return 'network';
3157
+ if (/^token_(missing|malformed|bad_signature|expired|replayed)$/.test(text)) return 'retry';
3158
+ if (text === 'burst_limit' || text === 'global_ceiling') return 'busy';
3159
+ return null;
3160
+ }
3161
+
3143
3162
  function renderCheckoutIntentPage(prefilledEmail = '', parsed = null, options = {}) {
3144
3163
  const plausibleDomain = escapeHtmlAttribute(resolvePlausibleDataDomain({ host: 'thumbgate.ai' }));
3164
+ const noticeCode = String(options.gateNotice || parsed?.searchParams?.get('gate_notice') || '');
3165
+ const gateNoticeText = Object.hasOwn(CHECKOUT_GATE_NOTICES, noticeCode) ? CHECKOUT_GATE_NOTICES[noticeCode] : '';
3145
3166
  const includeHiddenAttribution = options.includeHiddenAttribution === true;
3146
3167
  const hiddenInputs = includeHiddenAttribution
3147
3168
  ? buildCheckoutHiddenAttributionInputs(parsed)
@@ -3189,9 +3210,9 @@ ${Object.entries(planView.directFields).map(([k, v]) => `<input type="hidden" na
3189
3210
  <input type="hidden" name="click_token" value="">
3190
3211
  <button type="submit" class="primary" rel="nofollow">${planView.ctaLabel}</button>
3191
3212
  </form>
3192
- <p class="gate-note" id="gate-note" role="status" style="display:none"></p>
3213
+ <p class="gate-note" id="gate-note" role="status"${gateNoticeText ? '' : ' style="display:none"'}>${gateNoticeText}</p>
3193
3214
  <noscript><p class="gate-note">Checkout needs JavaScript so we can tell a person from a crawler.</p></noscript>
3194
- <p class="choice-note">Stripe asks for your email and card on the next page. Cancel anytime. 7-day refund, no questions.</p>
3215
+ <p class="choice-note">Stripe asks for your email and card on the next page. Cancel anytime. Refund within 7 days of the first charge if a documented platform defect makes ThumbGate unusable and we cannot fix it; see <a href="/terms">Terms</a>.</p>
3195
3216
  <details class="more-options" data-i="pro_checkout_more_options">
3196
3217
  <summary>Other ways to buy</summary>
3197
3218
  <form action="/checkout/pro" method="POST" data-i="pro_checkout_confirmed">
@@ -3335,6 +3356,23 @@ ${hiddenInputs}
3335
3356
  try { window.plausible && window.plausible('Checkout Pro Email Submitted', { props: { page:'/checkout/pro', source:'interstitial' } }); } catch(_) {}
3336
3357
  return { ctaId: 'pro_checkout_confirmed', ctaPlacement: 'checkout_interstitial', customerEmail: field ? field.value : null };
3337
3358
  });
3359
+ // The server logs checkout_interstitial_view for every GET, including link scanners and
3360
+ // crawlers that never run this script. This beacon fires only when a browser executed it,
3361
+ // so views that ran the page are countable apart from views that did not.
3362
+ function reportShown() {
3363
+ try {
3364
+ var b = directForm && directForm.querySelector('button[type=submit]');
3365
+ var r = b ? b.getBoundingClientRect() : null;
3366
+ var inView = !!(r && r.top >= 0 && r.bottom <= window.innerHeight);
3367
+ sendTelemetry('checkout_interstitial_shown', {
3368
+ ctaId: 'pro_checkout_direct_stripe',
3369
+ sectionId: inView ? 'cta_above_fold' : 'cta_below_fold',
3370
+ sectionLabel: window.innerWidth + 'x' + window.innerHeight
3371
+ });
3372
+ } catch (_) {}
3373
+ }
3374
+ if (document.readyState === 'complete') reportShown();
3375
+ else window.addEventListener('load', reportShown);
3338
3376
  document.querySelectorAll('[data-reason]').forEach(function(button) {
3339
3377
  button.addEventListener('click', function(){
3340
3378
  var reason = button.getAttribute('data-reason');
@@ -3799,6 +3837,8 @@ async function serveTrackedLinkRedirect({ req, res, parsed, hostedConfig, isHead
3799
3837
  } else {
3800
3838
  const confirmUrl = new URL('/checkout/pro', hostedConfig.appOrigin);
3801
3839
  appendTrackedLinkQueryParams(confirmUrl, parsed, { ...target, allowCustomerEmail: false });
3840
+ const refusedNotice = req.method === 'POST' ? checkoutGateNoticeCode(admission.reason) : null;
3841
+ if (refusedNotice) confirmUrl.searchParams.set('gate_notice', refusedNotice);
3802
3842
  if (!isHeadRequest && req.method === 'POST') {
3803
3843
  appendBestEffortTelemetry(
3804
3844
  FEEDBACK_DIR,
@@ -5096,6 +5136,7 @@ function renderSitemapXml(runtimeConfig) {
5096
5136
  { path: '/learn/netflix-oci-actor-critic-process-audits', changefreq: 'weekly', priority: '0.85' },
5097
5137
  { path: '/learn/future-agi-self-healing-agent-firewall', changefreq: 'weekly', priority: '0.85' },
5098
5138
  { path: '/learn/five-walls-enterprise-agent-deployment', changefreq: 'weekly', priority: '0.85' },
5139
+ { path: '/learn/okta-mcp-governance-per-tool-call-gates', changefreq: 'weekly', priority: '0.85' },
5099
5140
  { path: '/compare/claude-code-hooks', changefreq: 'weekly', priority: '0.85' },
5100
5141
  { path: '/compare/bumblebee', changefreq: 'weekly', priority: '0.85' },
5101
5142
  { path: '/compare/anthropic-containment', changefreq: 'weekly', priority: '0.85' },
@@ -9577,6 +9618,7 @@ async function addContext(){
9577
9618
  }, req.headers, 'checkout_human_gate_refused');
9578
9619
  const refusedHtml = renderCheckoutIntentPage(normalizedCheckoutEmail || '', parsed, {
9579
9620
  includeHiddenAttribution: true,
9621
+ gateNotice: checkoutGateNoticeCode(checkoutAdmission.reason),
9580
9622
  });
9581
9623
  sendHtml(res, checkoutAdmission.status, refusedHtml, {
9582
9624
  ...responseHeaders,