thumbgate 1.40.9 → 1.40.12

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.
Files changed (46) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/README.md +46 -40
  4. package/adapters/claude/.mcp.json +3 -3
  5. package/adapters/forge/forge.yaml +3 -3
  6. package/adapters/future-agi/.mcp.json +1 -1
  7. package/adapters/future-agi/config.toml +1 -1
  8. package/adapters/future-agi/opencode.json +1 -1
  9. package/adapters/herdr/herdr-plugin.toml +2 -2
  10. package/adapters/mcp/server-stdio.js +1 -1
  11. package/adapters/opencode/opencode.json +1 -1
  12. package/bin/cli.js +9 -8
  13. package/bin/postinstall.js +2 -2
  14. package/package.json +9 -5
  15. package/public/admin.html +229 -29
  16. package/public/agent-manager.html +2 -2
  17. package/public/agents-cost-savings.html +1 -1
  18. package/public/codex-enterprise.html +2 -2
  19. package/public/compare.html +3 -3
  20. package/public/dashboard.html +28 -9
  21. package/public/diagnostic.html +1 -1
  22. package/public/founders.html +1 -1
  23. package/public/guide.html +4 -4
  24. package/public/index.html +80 -116
  25. package/public/install.html +19 -19
  26. package/public/js/connect-panel.js +21 -7
  27. package/public/lessons.html +1 -1
  28. package/public/numbers.html +2 -2
  29. package/public/pricing.html +12 -9
  30. package/public/pro.html +96 -137
  31. package/public/project-switcher.js +42 -18
  32. package/scripts/auto-wire-hooks.js +36 -2
  33. package/scripts/billing.js +3 -1
  34. package/scripts/cli-schema.js +2 -3
  35. package/scripts/commercial-offer.js +1 -1
  36. package/scripts/gates-engine.js +26 -8
  37. package/scripts/hook-runtime.js +18 -1
  38. package/scripts/owner-admin.js +212 -13
  39. package/scripts/owner-alerts.js +79 -0
  40. package/scripts/owner-telemetry.js +93 -3
  41. package/scripts/project-catalog.js +3 -1
  42. package/scripts/project-identity.js +4 -1
  43. package/scripts/seo-gsd.js +1 -1
  44. package/scripts/telemetry-analytics.js +14 -4
  45. package/server.json +2 -2
  46. package/src/api/server.js +51 -3
@@ -8,12 +8,13 @@ const billing = require('./billing');
8
8
  const ownerTelemetry = require('./owner-telemetry');
9
9
  const opsLog = require('./ops-log');
10
10
  const opsReport = require('./ops-report');
11
+ const ownerAlerts = require('./owner-alerts');
11
12
 
12
13
  const JSON_LIMIT = 8 * 1024 * 1024;
13
14
  const LOG_LIMIT = 16 * 1024 * 1024;
14
15
  const RESPONSE_LIMIT = 1024 * 1024;
15
16
  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', 'summary']);
17
+ const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts']);
17
18
  const MONEY_CACHE_MS = 60000;
18
19
  let moneyCache = null;
19
20
  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' });
@@ -49,7 +50,10 @@ function parseAdminRoute(pathname, params) {
49
50
  if (limitRaw !== null && (!/^[1-9][0-9]*$/.test(limitRaw) || Number(limitRaw) > max)) throw failure('invalid_query');
50
51
  const limit = limitRaw === null ? 25 : Number(limitRaw);
51
52
  const cursor = params.get(section === 'data' ? 'cursor' : 'starting_after') || '';
52
- if (section === 'stripe' && cursor && !new RegExp(`^${RESOURCES[resource]}_[A-Za-z0-9]{1,120}$`).test(cursor)) throw failure('invalid_query');
53
+ // Stripe charge lists can return ch_ or py_ identifiers. Accept both only
54
+ // for payments, so the nextCursor we return is valid for the next request.
55
+ const cursorPrefix = resource === 'payments' ? '(?:ch|py)' : RESOURCES[resource];
56
+ if (section === 'stripe' && cursor && !new RegExp(`^${cursorPrefix}_[A-Za-z0-9]{1,120}$`).test(cursor)) throw failure('invalid_query');
53
57
  let offset = 0;
54
58
  if (section === 'data' && cursor) {
55
59
  if (!/^[A-Za-z0-9_-]{1,32}$/.test(cursor)) throw failure('invalid_query');
@@ -296,6 +300,7 @@ function projectAnalytics(summary) {
296
300
  return {
297
301
  funnel: { ...numericFields(summary.funnel, ['totalEvents', 'uniqueAcquisitionLeads', 'uniquePaidCustomers', 'excludedSyntheticCheckoutSessions']), stageCounts: numericFields(summary.funnel?.stageCounts, ['acquisition', 'activation', 'paid']), conversionRates: numericFields(summary.funnel?.conversionRates, ['acquisitionToActivation', 'activationToPaid', 'acquisitionToPaid']) },
298
302
  signups: numericFields(summary.signups, ['total', 'uniqueLeads', 'emailSignups', 'emailRecords', 'checkoutSessionsCreated']),
303
+ checkoutSessionDepth: { ...numericFields(summary.checkoutSessionDepth, ['sessionsCreated', 'raw', 'identified', 'paymentAttempt', 'paid', 'unresolved', 'qualifiedCheckoutStarts']), basis: summary.checkoutSessionDepth?.basis === 'stripe_session_lookup' ? 'stripe_session_lookup' : 'telemetry_heuristic', lookupStatus: ['ok', 'partial', 'unconfigured', 'unavailable', 'not_requested'].includes(summary.checkoutSessionDepth?.lookupStatus) ? summary.checkoutSessionDepth.lookupStatus : 'unavailable' },
299
304
  revenue: { external: { ...numericFields(external, ['paidOrders', 'amountUnknownOrders', 'duplicates']), bookedRevenueByCurrency: currencies(external?.bookedRevenueByCurrency), refundedByCurrency: currencies(external?.refundedByCurrency), excluded: numericFields(external?.excluded, ['internal', 'test', 'unknown']) }, broadAccounting: { ...numericFields(summary.revenue, ['paidOrders', 'paidCustomers', 'amountKnownOrders', 'amountUnknownOrders']), bookedRevenueByCurrency: currencies(summary.revenue?.bookedRevenueByCurrency) } },
300
305
  trafficMetrics: numericFields(summary.trafficMetrics, ['visitors', 'sessions', 'pageViews', 'ctaClicks', 'checkoutStarts', 'checkoutPaidConfirmations']),
301
306
  attribution: { coverageRate: number(summary.dataQuality?.attributionCoverage) },
@@ -441,6 +446,17 @@ async function readTraffic(deps, signal) {
441
446
  return value;
442
447
  }
443
448
 
449
+ const cohortCache = new Map();
450
+ async function readCohorts(deps, signal) {
451
+ const ttl = deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS;
452
+ const key = String(deps.feedbackDir);
453
+ const hit = cohortCache.get(key);
454
+ if (ttl > 0 && hit && Date.now() - hit.at < ttl) return hit.value;
455
+ const value = await ownerTelemetry.readInstallCohorts({ feedbackDir: guardPath(deps.feedbackDir, deps.feedbackDir), weeks: 8, signal, maxBytes: deps.telemetryMaxBytes });
456
+ if (ttl > 0) cohortCache.set(key, { at: Date.now(), value });
457
+ return value;
458
+ }
459
+
444
460
  // Why the Money board used to say "Stripe is busy": every list held one of the account's two read slots for its whole run
445
461
  // (a 30-day checkout list is about six pages), a read that found both taken failed at once, and a read that timed out kept
446
462
  // running and kept its slot. Now each page waits for a slot until one shared deadline, a stopped list stops between pages,
@@ -480,6 +496,35 @@ async function listAll({ list, params, keep = () => true, maxPages = 40, signal,
480
496
  }
481
497
  }
482
498
 
499
+ // Monthly recurring revenue by currency from active subscriptions: each item's price times quantity, scaled to one month.
500
+ // Discounts and coupons are not applied, so this is list-price MRR. `cancelling` counts subscriptions set to end at period end.
501
+ const MONTHS_PER = { day: 12 / 365, week: 12 / 52, month: 1, year: 12 };
502
+ function monthlyRecurring(subscriptions) {
503
+ const mrr = {};
504
+ let cancelling = 0;
505
+ let unpriced = 0;
506
+ for (const row of subscriptions) {
507
+ if (row.cancel_at_period_end === true) cancelling += 1;
508
+ for (const item of row.items?.data || []) {
509
+ const price = item.price || {};
510
+ const every = MONTHS_PER[price.recurring?.interval];
511
+ const count = Number.isInteger(price.recurring?.interval_count) && price.recurring.interval_count > 0 ? price.recurring.interval_count : 1;
512
+ if (!every || !Number.isSafeInteger(price.unit_amount) || !/^[a-z]{3}$/i.test(price.currency || '')) { unpriced += 1; continue; }
513
+ const code = price.currency.toUpperCase();
514
+ const quantity = Number.isInteger(item.quantity) && item.quantity > 0 ? item.quantity : 1;
515
+ mrr[code] = (mrr[code] || 0) + (price.unit_amount * quantity) / (every * count);
516
+ }
517
+ }
518
+ for (const code of Object.keys(mrr)) mrr[code] = Math.round(mrr[code]);
519
+ return { mrr, cancelling, unpriced };
520
+ }
521
+
522
+ // The acquisition channel a checkout carried in its metadata (utm source, else source), in one plain lower-case word.
523
+ function channelOf(row) {
524
+ const raw = String(row?.metadata?.utmSource || row?.metadata?.source || '').trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '_').slice(0, 40);
525
+ return raw && raw !== 'unknown' ? raw : 'direct';
526
+ }
527
+
483
528
  const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''));
484
529
 
485
530
  // Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
@@ -541,13 +586,23 @@ async function collectMoney(deps, signal) {
541
586
  const paid = result.rows.filter((row) => row.payment_status === 'paid' && classifySession(row, { ownerEmails }) !== 'internal' && charge(row)?.refunded !== true);
542
587
  const customers = new Set(paid.map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
543
588
  const revenue = {};
589
+ const channels = {};
590
+ const counted = new Set();
591
+ const channel = (name) => (channels[name] ||= { paidCustomers: 0, revenue30d: {} });
592
+ // Oldest first, so a customer is credited to the channel of their first paid checkout.
593
+ for (const row of [...paid].sort((a, b) => (a.created || 0) - (b.created || 0))) {
594
+ const who = id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase();
595
+ if (!counted.has(who)) { counted.add(who); channel(channelOf(row)).paidCustomers += 1; }
596
+ }
544
597
  for (const row of paid) {
545
598
  if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
546
599
  const code = row.currency.toUpperCase();
547
600
  const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
548
601
  revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
602
+ const byChannel = channel(channelOf(row)).revenue30d;
603
+ byChannel[code] = (byChannel[code] || 0) + row.amount_total - refunded;
549
604
  }
550
- return { customers, revenue, complete: result.complete };
605
+ return { customers, revenue, channels, complete: result.complete };
551
606
  });
552
607
  const proResult = await withLastGood('subscriptions', async () => {
553
608
  const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
@@ -556,13 +611,30 @@ async function collectMoney(deps, signal) {
556
611
  return !(email && ownerEmails.some((owner) => email === String(owner).toLowerCase()));
557
612
  });
558
613
  const customers = new Set(external.map((row) => id(row.customer) || String(row.customer?.email || row.id).toLowerCase()));
559
- return { count: external.length, customers, complete: result.complete };
614
+ return { count: external.length, customers, complete: result.complete, ...monthlyRecurring(external) };
560
615
  });
561
616
  return [paidResult, proResult];
562
617
  })();
563
- let paidAndPro; let sessionRun; let trafficRun; let summaryRun;
618
+ const isOwnerEmail = (email) => Boolean(email) && ownerEmails.some((owner) => String(email).toLowerCase() === String(owner).toLowerCase());
619
+ // Third lane: what subscriptions actually brought in and lost in 30 days. Renewal invoices are the recurring cash the
620
+ // checkout list never sees; cancelled subscriptions are churn.
621
+ const recurringLane = withLastGood('recurring', async () => {
622
+ const since30 = nowSeconds - 30 * 86400;
623
+ const invoices = await listIt((params, options) => stripe().invoices.list(params, options), { status: 'paid', created: { gte: since30 } },
624
+ (row) => row.billing_reason === 'subscription_cycle' && !isOwnerEmail(row.customer_email), 10);
625
+ const renewals = {};
626
+ for (const row of invoices.rows) {
627
+ if (!Number.isSafeInteger(row.amount_paid) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
628
+ const code = row.currency.toUpperCase();
629
+ renewals[code] = (renewals[code] || 0) + row.amount_paid;
630
+ }
631
+ const cancelled = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'canceled', expand: ['data.customer'] },
632
+ (row) => Number(row.canceled_at || row.ended_at) >= since30 && !isOwnerEmail(row.customer?.email), 5);
633
+ return { renewals, renewalCount: invoices.rows.length, churned: cancelled.rows.length, churnedMrr: monthlyRecurring(cancelled.rows).mrr, complete: invoices.complete && cancelled.complete };
634
+ });
635
+ let paidAndPro; let sessionRun; let trafficRun; let summaryRun; let recurringRun;
564
636
  try {
565
- [paidAndPro, sessionRun, trafficRun, summaryRun] = await Promise.all([
637
+ [paidAndPro, sessionRun, trafficRun, summaryRun, recurringRun] = await Promise.all([
566
638
  paidAndProLane,
567
639
  withLastGood('checkouts', async () => {
568
640
  const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options), { created: { gte: nowSeconds - 30 * 86400 } }, thumbgateSession, 40);
@@ -571,7 +643,13 @@ async function collectMoney(deps, signal) {
571
643
  const botCheckSeconds = Date.parse(botCheckBeganAt) / 1000;
572
644
  const beforeBotCheck = (row) => Boolean(row.created) && row.created < botCheckSeconds;
573
645
  const classified = result.rows.filter((row) => row.metadata?.uaClass && row.created).map((row) => row.created);
646
+ const startsByChannel = {};
647
+ for (const row of result.rows) {
648
+ if (['bot', 'internal'].includes(classifySession(row, { ownerEmails }))) continue;
649
+ startsByChannel[channelOf(row)] = (startsByChannel[channelOf(row)] || 0) + 1;
650
+ }
574
651
  return {
652
+ startsByChannel,
575
653
  d30: countSessions(result.rows, { ownerEmails }),
576
654
  d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }),
577
655
  before: countSessions(result.rows.filter(beforeBotCheck), { ownerEmails }),
@@ -582,6 +660,7 @@ async function collectMoney(deps, signal) {
582
660
  }),
583
661
  attempt(() => readTraffic(deps, signal), telemetryReason),
584
662
  attempt(() => readSummary(deps, signal), () => 'lead ledgers failed'),
663
+ recurringLane,
585
664
  ]);
586
665
  } finally {
587
666
  clearTimeout(sharedTimer);
@@ -638,6 +717,7 @@ async function collectMoney(deps, signal) {
638
717
  paid: blockTime('paid'),
639
718
  subscriptions: blockTime('subscriptions'),
640
719
  checkouts: blockTime('checkouts'),
720
+ recurring: blockTime('recurring'),
641
721
  traffic: { collectedAt: trafficRead?.collectedAt || null, stale: false },
642
722
  leads: { collectedAt: summaryRun.value?.collectedAt || null, stale: summaryRun.value?.state === 'stale' },
643
723
  displayRefreshedAt: new Date().toISOString(),
@@ -652,6 +732,26 @@ async function collectMoney(deps, signal) {
652
732
  payingCustomersSource: 'stripe',
653
733
  payingCustomersBasis: bothStripe ? (paid.complete && proRun.value.complete ? 'stripe_paid_and_active' : 'stripe_paid_and_active_partial') : 'unavailable',
654
734
  activePro: proRun.value ? proRun.value.count : null,
735
+ mrr: proRun.value ? proRun.value.mrr : null,
736
+ mrrBasis: proRun.value ? (proRun.value.complete && !proRun.value.unpriced ? 'stripe_active_subscription_list_prices' : 'stripe_active_subscription_list_prices_partial') : 'unavailable',
737
+ cancellingAtPeriodEnd: proRun.value ? proRun.value.cancelling : null,
738
+ // Churn: subscriptions cancelled in 30 days against those plus the ones still active.
739
+ recurring30d: recurringRun.ok ? {
740
+ renewalRevenue: recurringRun.value.renewals,
741
+ renewalInvoices: recurringRun.value.renewalCount,
742
+ churnedSubscriptions: recurringRun.value.churned,
743
+ churnedMrr: recurringRun.value.churnedMrr,
744
+ churnRate: proRun.value && proRun.value.count + recurringRun.value.churned > 0 ? Math.round((recurringRun.value.churned / (proRun.value.count + recurringRun.value.churned)) * 1000) / 1000 : null,
745
+ complete: recurringRun.value.complete,
746
+ } : null,
747
+ // One row per channel: checkout sessions started in 30 days (bots and owner left out), paying customers credited to
748
+ // the channel of their first paid checkout in the past year, and 30-day checkout revenue.
749
+ channels: paid || sessions ? Object.entries([...new Set([...Object.keys(paid?.channels || {}), ...Object.keys(sessions?.startsByChannel || {})])].reduce((out, name) => {
750
+ out[name] = { checkoutStarts30d: sessions ? sessions.startsByChannel[name] || 0 : null, paidCustomers: paid ? paid.channels[name]?.paidCustomers || 0 : null, revenue30d: paid ? paid.channels[name]?.revenue30d || {} : null };
751
+ return out;
752
+ }, {})).map(([channel, row]) => ({ channel, ...row })).sort((a, b) => (b.paidCustomers || 0) - (a.paidCustomers || 0) || (b.checkoutStarts30d || 0) - (a.checkoutStarts30d || 0)).slice(0, 25) : null,
753
+ usage30d: trafficReason ? null : (trafficRead.usage || null),
754
+ weekOverWeek: trafficReason ? null : (trafficRead.weeks || null),
655
755
  activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
656
756
  revenueLast30Days: paid ? paid.revenue : null,
657
757
  revenueBasis: 'stripe_paid_checkouts_after_refunds',
@@ -663,6 +763,8 @@ async function collectMoney(deps, signal) {
663
763
  reasons: {
664
764
  payingCustomers: bothStripe ? null : (paidRun.reason || proRun.reason),
665
765
  activePro: proRun.value ? null : proRun.reason,
766
+ mrr: proRun.value ? null : proRun.reason,
767
+ recurring: recurringRun.ok ? null : recurringRun.reason,
666
768
  revenue: paid ? null : paidRun.reason,
667
769
  checkouts: sessions ? null : sessionRun.reason,
668
770
  visitors: trafficReason,
@@ -670,7 +772,7 @@ async function collectMoney(deps, signal) {
670
772
  },
671
773
  notes: ['Every started checkout is counted once: real people, bots, not classified, or owner and test.', 'Sessions created before the bot check carry no browser class, so they are counted as not classified.'],
672
774
  };
673
- const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts' };
775
+ const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts', recurring: 'renewals and churn' };
674
776
  for (const [key, at] of Object.entries(staleBlocks)) {
675
777
  const minutes = Math.max(1, Math.round((Date.now() - at) / 60000));
676
778
  data.notes.push(`Showing the last good ${staleLabel[key]} from ${minutes} minute${minutes === 1 ? '' : 's'} ago, because Stripe did not answer this time.`);
@@ -682,6 +784,7 @@ async function collectMoney(deps, signal) {
682
784
  if (!paidRun.ok) warnings.push('paid_checkout_list_unavailable');
683
785
  if (!sessionRun.ok) warnings.push('checkout_list_unavailable');
684
786
  if (!proRun.ok) warnings.push('subscription_list_unavailable');
787
+ if (!recurringRun.ok) warnings.push('renewal_and_churn_unavailable');
685
788
  if (trafficReason) warnings.push('telemetry_unavailable');
686
789
  if (leadsReason) warnings.push('leads_unavailable');
687
790
  const failed = [paidRun, sessionRun, proRun].filter((run) => !run.ok).length;
@@ -693,9 +796,10 @@ async function collectMoney(deps, signal) {
693
796
  // Analytics: 30 days of traffic streamed from the telemetry tail (never refused for size), a daily series, and the
694
797
  // billing totals from the cached child-process summary when it is ready.
695
798
  async function collectAnalytics(deps, signal) {
696
- const [trafficRun, summaryRun] = await Promise.all([
799
+ const [trafficRun, summaryRun, cohortRun] = await Promise.all([
697
800
  attempt(() => readTraffic(deps, signal), telemetryReason),
698
801
  attempt(() => readSummary(deps, signal), () => 'billing totals failed'),
802
+ attempt(() => readCohorts(deps, signal), telemetryReason),
699
803
  ]);
700
804
  const parts = summaryRun.value?.value || null;
701
805
  const trafficRead = trafficRun.value;
@@ -704,6 +808,9 @@ async function collectAnalytics(deps, signal) {
704
808
  const hasTraffic = trafficRun.ok && !trafficRead.empty;
705
809
  data.trafficMetrics = hasTraffic ? trafficFields(trafficRead) : (data.trafficMetrics || null);
706
810
  data.daily = hasTraffic ? trafficRead.daily : [];
811
+ data.usage = hasTraffic ? (trafficRead.usage || null) : null;
812
+ data.weekOverWeek = hasTraffic ? (trafficRead.weeks || null) : null;
813
+ data.cohorts = cohortRun.ok ? cohortRun.value : null;
707
814
  data.dataQuality = { ...(data.dataQuality || {}), telemetryWindowComplete: hasTraffic ? !trafficRead.partial : false, telemetryBytesRead: trafficRead ? trafficRead.bytesRead : 0, telemetrySizeBytes: trafficRead ? trafficRead.size : 0 };
708
815
  const warnings = [];
709
816
  if (data.reconciliation && (data.reconciliation.status !== 'ok' || !data.reconciliation.complete)) warnings.push('stripe_reconciliation_' + data.reconciliation.status);
@@ -757,8 +864,15 @@ async function collectSummary(deps, signal) {
757
864
  add('money.paying_customers', 'Paying customers', money.payingCustomers, { ...stripeOpts('paid', why.payingCustomers), partial: money.payingCustomersBasis === 'stripe_paid_and_active_partial' });
758
865
  add('money.active_pro', 'Active Pro subscriptions', money.activePro, { ...stripeOpts('subscriptions', why.activePro), partial: money.activeProBasis === 'stripe_active_subscriptions_first_100_only' });
759
866
  // collectMoney reads completed Checkout Sessions only, so this is first-charge revenue; renewal invoices never appear in it.
867
+ add('money.mrr', 'Monthly recurring revenue at list price, by currency (active Stripe subscriptions)', money.mrr, { ...stripeOpts('subscriptions', why.mrr), partial: money.mrrBasis === 'stripe_active_subscription_list_prices_partial' });
868
+ add('money.cancelling_at_period_end', 'Active subscriptions set to cancel at period end', money.cancellingAtPeriodEnd, stripeOpts('subscriptions', why.mrr));
760
869
  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' });
870
+ const recurring = money.recurring30d;
871
+ const recurringOpts = { ...stripeOpts('recurring', why.recurring), partial: recurring ? recurring.complete === false : false };
872
+ add('money.subscription_invoices_30d', 'Subscription renewal revenue, past 30 days, by currency (paid renewal invoices)', recurring ? recurring.renewalRevenue : null, recurringOpts);
873
+ add('money.churned_subscriptions_30d', 'Subscriptions cancelled in the past 30 days', recurring ? recurring.churnedSubscriptions : null, recurringOpts);
874
+ const noSubscriptions = recurring && recurring.churnRate === null;
875
+ add('money.churn_rate_30d', 'Subscription churn, past 30 days (cancelled ÷ cancelled plus active)', recurring ? recurring.churnRate : null, noSubscriptions ? { ...recurringOpts, unresolved: true, reason: 'No active or cancelled subscriptions, so there is no rate' } : recurringOpts);
762
876
  buckets('money.checkouts_7d', '7 days', money.checkouts7d);
763
877
  buckets('money.checkouts_30d', '30 days', money.checkouts30d);
764
878
  const panel = money.checkoutBotCheck;
@@ -775,20 +889,104 @@ async function collectSummary(deps, signal) {
775
889
  trafficField('traffic.cta_clicks_30d', 'Call to action clicks (30 days)', 'ctaClicks');
776
890
  trafficField('traffic.checkout_starts_30d', 'Checkout starts seen on the site (30 days)', 'checkoutStarts');
777
891
  trafficField('traffic.paid_confirmations_30d', 'Paid confirmations (30 days)', 'checkoutPaidConfirmations');
892
+ const usage = analytics?.usage || money?.usage30d || null;
893
+ const usageField = (key, label, name) => add(key, label, usage ? usage[name] ?? null : null, trafficOpts);
894
+ usageField('usage.active_installs_7d', 'CLI installs active in the past 7 days (owner and CI excluded)', 'activeInstalls7d');
895
+ usageField('usage.active_installs_30d', 'CLI installs active in the past 30 days (owner and CI excluded)', 'activeInstalls30d');
896
+ usageField('usage.activated_installs_30d', 'Active installs that captured feedback (30 days)', 'activatedInstalls');
897
+ usageField('usage.returning_installs_30d', 'Active installs seen on 2 or more days (30 days)', 'returningInstalls');
898
+ add('usage.install_cohorts_8w', 'Weekly CLI install cohorts and how many came back each later week (8 weeks)', analytics?.cohorts?.cohorts ?? null, { ...trafficOpts, partial: analytics?.cohorts?.partial === true });
899
+ if (money) add('money.channels', 'Checkout starts (30 days), paying customers (first paid checkout, 1 year) and revenue (30 days) by channel', money.channels, stripeOpts('paid', why.revenue));
900
+ add('traffic.week_over_week', 'Past 7 days against the 7 days before', analytics?.weekOverWeek || money?.weekOverWeek || null, trafficOpts);
778
901
  add('traffic.daily_30d', 'Daily traffic, past 30 days', analytics ? analytics.daily : null, trafficOpts);
779
902
  const billingOpts = { source: 'billing_summary', collectedAt: fresh.leads?.collectedAt || null, reason: analyticsRun.ok ? null : analyticsRun.reason, unresolved: !analytics?.signups };
780
903
  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);
904
+ // Ledger totals remain useful evidence when the provider reconciliation is
905
+ // incomplete, but a zero must not be promoted to a verified provider zero.
906
+ const reconciliationComplete = analytics?.reconciliation?.status === 'ok' && analytics.reconciliation.complete === true;
907
+ const revenueOpts = { ...billingOpts, partial: Boolean(analytics) && !reconciliationComplete,
908
+ reason: reconciliationComplete || !analytics ? billingOpts.reason : 'Provider reconciliation is incomplete (' + (analytics?.reconciliation?.status || 'not reported') + '); these are partial ledger totals, not a verified payment outcome' };
909
+ add('analytics.external_paid_orders', 'External paid orders', analytics?.revenue?.external?.paidOrders ?? null, revenueOpts);
910
+ add('analytics.external_booked_revenue_30d', 'External booked revenue, past 30 days, by currency', analytics?.revenue?.external?.bookedRevenueByCurrency ?? null, revenueOpts);
783
911
 
784
912
  // 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'];
913
+ const knownGaps = [];
786
914
  const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key)).map(([, entry]) => entry.status);
787
915
  const bad = states.filter((state) => state === 'unavailable').length;
788
916
  const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
789
917
  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
918
  }
791
919
 
920
+ // GET /v1/admin/alerts: what needs the owner now, from the Money board and the Health report.
921
+ async function collectAlerts(deps, signal) {
922
+ const [moneyRun, healthRun] = await Promise.all([
923
+ attempt(() => collectMoney(deps, signal), () => 'money unavailable'),
924
+ attempt(() => collectObservability(deps, signal), () => 'health unavailable'),
925
+ ]);
926
+ const money = moneyRun.ok ? moneyRun.value.data : null;
927
+ const report = healthRun.ok ? healthRun.value.data?.report || null : null;
928
+ const alerts = ownerAlerts.evaluateAlerts({ money, report });
929
+ if (!money) alerts.push({ id: 'money_unchecked', level: 'amber', text: 'The money checks could not run this time.', action: 'Refresh in a minute.', tab: 'money' });
930
+ if (!report) alerts.push({ id: 'health_unchecked', level: 'amber', text: 'The health checks could not run this time.', action: 'Refresh in a minute.', tab: 'observability' });
931
+ const delivery = alertChannels().length ? alertChannels().join('_and_') + '_on_new_alert' : 'off';
932
+ return envelope('owner_alerts', { alerts, checked: { money: Boolean(money), health: Boolean(report) }, delivery }, [], money && report ? 'ok' : 'partial');
933
+ }
934
+
935
+ // Where new alerts go: the owner's own incoming webhook (Slack, Discord or Teams) and/or an email to the owner addresses
936
+ // through the app's existing mail provider. Both are off unless their variable is set.
937
+ function alertChannels() {
938
+ const out = [];
939
+ if (/^https:\/\//.test(String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim())) out.push('webhook');
940
+ if (String(process.env.THUMBGATE_OWNER_ALERT_EMAIL || '').trim().toLowerCase() === 'on') out.push('email');
941
+ return out;
942
+ }
943
+
944
+ // One-shot webhook post for owner alerts. Kept local because scripts/webhook-delivery.js is a dev-only file the npm package must not ship.
945
+ function postOwnerWebhook(platform, webhookUrl, title, message) {
946
+ const payload = platform === 'teams' ? { '@type': 'MessageCard', '@context': 'http://schema.org/extensions', summary: title, themeColor: '0076D7', title, text: message }
947
+ : platform === 'discord' ? { embeds: [{ title, description: String(message).substring(0, 4096), color: 0x0076D7 }] }
948
+ : { text: `*${title}*\n${message}` };
949
+ const target = new URL(webhookUrl);
950
+ const body = JSON.stringify(payload);
951
+ return new Promise((resolve, reject) => {
952
+ const req = (target.protocol === 'https:' ? require('https') : require('http')).request(target, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, (res) => {
953
+ res.resume();
954
+ res.on('end', () => (res.statusCode >= 200 && res.statusCode < 300 ? resolve(res.statusCode) : reject(new Error(`Webhook HTTP ${res.statusCode}`))));
955
+ });
956
+ req.on('error', reject);
957
+ req.on('timeout', () => req.destroy(new Error('Webhook timeout')));
958
+ req.end(body);
959
+ });
960
+ }
961
+
962
+ // Checks the alerts every 15 minutes and sends the new ones to the channels above. Does nothing when none is set.
963
+ function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, send } = {}) {
964
+ const channels = alertChannels();
965
+ if (!channels.length && !send) return null;
966
+ const url = String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim();
967
+ const platform = /discord/i.test(url) ? 'discord' : /office|teams|logic\.azure/i.test(url) ? 'teams' : 'slack';
968
+ const deliver = send || (async ({ title, message }) => {
969
+ if (channels.includes('webhook')) await postOwnerWebhook(platform, url, title, message).catch(() => null);
970
+ if (channels.includes('email')) {
971
+ const to = require('./bot-detection').getOwnerEmails();
972
+ if (to.length) await require('./mailer/resend-mailer').sendEmail({ to: String(to[0]), subject: title, text: message }).catch(() => null);
973
+ }
974
+ });
975
+ const tracker = ownerAlerts.createAlertTracker();
976
+ const run = async () => {
977
+ try {
978
+ const result = await collectAlerts(makeDeps(), AbortSignal.timeout(30000));
979
+ const added = tracker.fresh(result.data.alerts.filter((alert) => alert.level !== 'info'));
980
+ if (!added.length) return;
981
+ await deliver(ownerAlerts.formatAlertMessage(added));
982
+ } catch { /* an alert check never takes the server down */ }
983
+ };
984
+ const timer = setInterval(run, intervalMs);
985
+ timer.unref?.();
986
+ setTimeout(run, 60000).unref?.();
987
+ return timer;
988
+ }
989
+
792
990
  async function collectAdminSection(route, deps, externalSignal) {
793
991
  if (activeCollections >= 2) throw failure('collection_busy');
794
992
  activeCollections += 1;
@@ -803,6 +1001,7 @@ async function collectAdminSection(route, deps, externalSignal) {
803
1001
  if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
804
1002
  if (route.section === 'money') return collectMoney(deps, controller.signal);
805
1003
  if (route.section === 'summary') return collectSummary(deps, controller.signal);
1004
+ if (route.section === 'alerts') return collectAlerts(deps, controller.signal);
806
1005
  if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
807
1006
  if (route.section === 'data') return collectData(route, deps, controller.signal);
808
1007
  if (route.section === 'observability') return collectObservability(deps, controller.signal);
@@ -816,4 +1015,4 @@ async function collectAdminSection(route, deps, externalSignal) {
816
1015
  }
817
1016
  }
818
1017
 
819
- module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
1018
+ module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Owner console alerts. Pure rules over the Money board and the Observability report: each alert says what happened,
5
+ * with its numbers, and what to do next. No alert fires on a source that could not be read; that is its own alert.
6
+ *
7
+ * Delivery is off unless THUMBGATE_OWNER_ALERT_WEBHOOK is set (a Slack, Discord or Teams incoming webhook, all free).
8
+ * A message goes out only when an alert appears that was not firing at the last check, so a standing problem is sent once.
9
+ */
10
+
11
+ const LEVELS = { red: 0, amber: 1, info: 2 };
12
+ const dropped = (week, key, floor) => {
13
+ const before = week?.prior7?.[key];
14
+ const now = week?.last7?.[key];
15
+ return Number.isFinite(before) && Number.isFinite(now) && before >= floor && now <= before / 2 ? { before, now } : null;
16
+ };
17
+ const percent = (part, whole) => Math.round((part / whole) * 100);
18
+
19
+ function evaluateAlerts({ money = null, report = null } = {}) {
20
+ const alerts = [];
21
+ const add = (id, level, text, action, tab) => alerts.push({ id, level, text, action, tab });
22
+
23
+ if (report) {
24
+ const errors = report.errors || {};
25
+ if (Number.isFinite(errors.lastHour) && errors.lastHour >= 5) add('server_errors', 'red', errors.lastHour + ' server errors in the last hour.', 'Open Health to see which requests fail.', 'observability');
26
+ const uptime = report.uptime || {};
27
+ if (Number.isFinite(uptime.percent) && uptime.percent < 99.5) add('uptime', 'amber', 'Uptime is ' + uptime.percent + '% over about ' + uptime.observedDays + ' days.', 'Check the last outage on Health and the Railway deploy log.', 'observability');
28
+ const hooks = report.webhooks || {};
29
+ if (Number.isFinite(hooks.failures24h) && hooks.failures24h > 0) add('stripe_webhooks', 'red', hooks.failures24h + ' Stripe notifications failed in 24 hours, so a payment may not have unlocked Pro.', 'Check Stripe, Developers, Webhooks, and resend the failed events.', 'observability');
30
+ const disk = report.disk || {};
31
+ if (Number.isFinite(disk.percent) && disk.percent >= 85) add('disk', disk.percent >= 95 ? 'red' : 'amber', 'The data disk is ' + disk.percent + '% full.', 'Grow the Railway volume or rotate the telemetry log.', 'observability');
32
+ const signIn = report.signIn || {};
33
+ if (Number.isFinite(signIn.failed24h) && signIn.failed24h >= 10) add('sign_in', 'amber', signIn.failed24h + ' failed sign-ins in 24 hours.', 'Open Health to see the most common reason.', 'observability');
34
+ }
35
+
36
+ if (money) {
37
+ const why = money.reasons || {};
38
+ const stripeDown = ['payingCustomers', 'revenue', 'checkouts', 'mrr'].map((key) => why[key]).filter(Boolean);
39
+ if (stripeDown.length) add('stripe_unreadable', 'amber', 'Stripe could not be read: ' + stripeDown[0] + '.', 'Refresh in a minute. If it stays, check the Stripe key on Railway.', 'money');
40
+ if (why.visitors && why.visitors !== 'telemetry store empty') add('telemetry_unreadable', 'amber', 'Site and CLI telemetry could not be read: ' + why.visitors + '.', 'Refresh in a minute, then check the Railway volume.', 'analytics');
41
+
42
+ const week = money.weekOverWeek;
43
+ const visitors = dropped(week, 'realVisitors', 20);
44
+ if (visitors) add('visitors_drop', 'amber', 'People on the site fell from ' + visitors.before + ' to ' + visitors.now + ' this week.', 'Check that the last deploy did not break a page, then check your launch posts and links.', 'analytics');
45
+ const starts = dropped(week, 'checkoutStarts', 4);
46
+ if (starts) add('checkout_drop', 'amber', 'Checkout starts fell from ' + starts.before + ' to ' + starts.now + ' this week.', 'Click through the pricing page to the Stripe checkout yourself.', 'money');
47
+ const installs = dropped(week, 'activeInstalls', 4);
48
+ if (installs) add('installs_drop', 'amber', 'Active CLI installs fell from ' + installs.before + ' to ' + installs.now + ' this week.', 'Run npx thumbgate init on a clean machine to check install still works.', 'analytics');
49
+
50
+ const usage = money.usage30d;
51
+ if (usage && usage.activeInstalls30d >= 10 && usage.activatedInstalls / usage.activeInstalls30d < 0.2) add('activation_low', 'amber', 'Only ' + usage.activatedInstalls + ' of ' + usage.activeInstalls30d + ' active installs (' + percent(usage.activatedInstalls, usage.activeInstalls30d) + '%) captured any feedback.', 'Make the first thumbs-down easier to reach in init.', 'analytics');
52
+
53
+ if (Number.isFinite(money.cancellingAtPeriodEnd) && money.cancellingAtPeriodEnd > 0) add('cancelling', 'amber', money.cancellingAtPeriodEnd + ' subscriber' + (money.cancellingAtPeriodEnd === 1 ? ' is' : 's are') + ' set to cancel at the end of the period.', 'Look them up under Stripe records, Subscriptions, and ask why before the period ends.', 'stripe');
54
+ const churned = money.recurring30d?.churnedSubscriptions;
55
+ if (Number.isFinite(churned) && churned > 0) add('churned', 'amber', churned + ' subscription' + (churned === 1 ? '' : 's') + ' cancelled in the past 30 days.', 'Read the cancellation reasons in Stripe.', 'stripe');
56
+ }
57
+
58
+ return alerts.sort((a, b) => LEVELS[a.level] - LEVELS[b.level]);
59
+ }
60
+
61
+ function formatAlertMessage(alerts) {
62
+ const lines = alerts.map((alert) => (alert.level === 'red' ? '[urgent] ' : '') + alert.text + ' ' + alert.action);
63
+ return { title: 'ThumbGate: ' + alerts.length + ' thing' + (alerts.length === 1 ? '' : 's') + ' need you', message: lines.join('\n') + '\nhttps://thumbgate.ai/admin' };
64
+ }
65
+
66
+ // Returns the alerts that are new since the last call, and remembers the current set.
67
+ function createAlertTracker() {
68
+ let firing = new Set();
69
+ return {
70
+ fresh(alerts) {
71
+ const now = new Set(alerts.map((alert) => alert.id));
72
+ const added = alerts.filter((alert) => !firing.has(alert.id));
73
+ firing = now;
74
+ return added;
75
+ },
76
+ };
77
+ }
78
+
79
+ module.exports = { evaluateAlerts, formatAlertMessage, createAlertTracker };
@@ -101,6 +101,13 @@ async function scanTelemetry({ feedbackDir, days = 30, now = Date.now(), maxByte
101
101
  const kind = (entry) => String(entry.eventType || entry.event || '').toLowerCase();
102
102
  const isWeb = (entry) => (entry.clientType || entry.client) === 'web';
103
103
  const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal === true || entry.isTest === true;
104
+ const isCli = (entry) => (entry.clientType || entry.client) === 'cli';
105
+ // The CLI labels its own runs: `owner` for the owner's machines and `ci` for build servers. Older stored rows carry only
106
+ // that label, not the ingest flags, so both are checked.
107
+ const isOwnOrCiInstall = (entry) => isFlagged(entry) || ['owner', 'ci'].includes(String(entry.visitorType || '').toLowerCase());
108
+ // An install counts as activated once it has captured a piece of feedback: that is the first moment ThumbGate does its job.
109
+ const ACTIVATION_EVENT = 'cli_capture';
110
+ const topCounts = (counts, limit = 10) => Object.fromEntries(Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, limit));
104
111
 
105
112
  // Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
106
113
  //
@@ -108,6 +115,13 @@ const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal ===
108
115
  // so it can exceed `pageViews`, which counts landing_page_view events only. `realVisitors` leaves out identifiers that
109
116
  // carried a bot, internal or test flag on any event. `pageViewers` is the identifiers with at least one landing page view.
110
117
  async function readTrafficWindow(options) {
118
+ const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
119
+ const weekOf = (time) => (time >= nowMs - 7 * DAY_MS ? 'last7' : time >= nowMs - 14 * DAY_MS ? 'prior7' : null);
120
+ const emptyWeek = () => ({ visitors: new Set(), flagged: new Set(), pageViews: 0, checkoutStarts: 0, activeInstalls: new Set() });
121
+ const weeks = { last7: emptyWeek(), prior7: emptyWeek() };
122
+ const installs = new Map();
123
+ const excludedInstalls = new Set();
124
+ const cliEvents = {};
111
125
  const days = new Map();
112
126
  const visitors = new Set();
113
127
  const flagged = new Set();
@@ -118,17 +132,40 @@ async function readTrafficWindow(options) {
118
132
  const dayOf = (time) => {
119
133
  const key = new Date(time).toISOString().slice(0, 10);
120
134
  let day = days.get(key);
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); }
135
+ if (!day) { day = { date: key, visitors: new Set(), pageViewers: new Set(), sessions: new Set(), activeInstalls: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
122
136
  return day;
123
137
  };
124
138
  const meta = await scanTelemetry({
125
139
  ...options,
126
140
  onEntry(entry, time) {
141
+ const week = weekOf(time);
142
+ if (isCli(entry)) {
143
+ const install = entry.installId;
144
+ if (!install) return;
145
+ if (isOwnOrCiInstall(entry)) { excludedInstalls.add(install); return; }
146
+ const type = kind(entry) || 'unknown';
147
+ cliEvents[type] = (cliEvents[type] || 0) + 1;
148
+ const day = dayOf(time);
149
+ day.activeInstalls.add(install);
150
+ if (week) weeks[week].activeInstalls.add(install);
151
+ const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, version: null, platform: null };
152
+ seen.days.add(day.date);
153
+ seen.inited ||= type === 'cli_init';
154
+ seen.activated ||= type === ACTIVATION_EVENT;
155
+ if (time >= seen.lastMs) { seen.lastMs = time; seen.version = entry.version || entry.pkgVersion || seen.version; seen.platform = entry.platform || seen.platform; }
156
+ installs.set(install, seen);
157
+ return;
158
+ }
127
159
  if (!isWeb(entry)) return;
128
160
  totals.webEvents += 1;
129
161
  const day = dayOf(time);
130
162
  const who = entry.visitorId || entry.installId || entry.sessionId || null;
131
163
  if (who) { visitors.add(who); day.visitors.add(who); if (isFlagged(entry)) flagged.add(who); }
164
+ if (week) {
165
+ if (who) { weeks[week].visitors.add(who); if (isFlagged(entry)) weeks[week].flagged.add(who); }
166
+ if (kind(entry) === 'landing_page_view') weeks[week].pageViews += 1;
167
+ if (telemetry.isCheckoutStartEvent(kind(entry))) weeks[week].checkoutStarts += 1;
168
+ }
132
169
  if (entry.sessionId) { sessions.add(entry.sessionId); day.sessions.add(entry.sessionId); }
133
170
  const type = kind(entry);
134
171
  if (type === 'landing_page_view') {
@@ -140,12 +177,65 @@ async function readTrafficWindow(options) {
140
177
  if (type === 'checkout_paid_confirmed') { totals.checkoutPaidConfirmations += 1; day.checkoutPaidConfirmations += 1; }
141
178
  },
142
179
  });
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 }));
180
+ 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, activeInstalls: day.activeInstalls.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
181
+ const byVersion = {};
182
+ const byPlatform = {};
183
+ let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0;
184
+ for (const seen of installs.values()) {
185
+ byVersion[seen.version || 'unknown'] = (byVersion[seen.version || 'unknown'] || 0) + 1;
186
+ byPlatform[seen.platform || 'unknown'] = (byPlatform[seen.platform || 'unknown'] || 0) + 1;
187
+ if (seen.inited) newInstalls += 1;
188
+ if (seen.activated) activated += 1;
189
+ if (seen.days.size >= 2) returning += 1;
190
+ if (seen.lastMs >= nowMs - 7 * DAY_MS) active7 += 1;
191
+ }
192
+ const weekNumbers = (week) => ({ realVisitors: week.visitors.size - week.flagged.size, pageViews: week.pageViews, checkoutStarts: week.checkoutStarts, activeInstalls: week.activeInstalls.size });
144
193
  return {
145
194
  ...meta,
195
+ // CLI installs, from the anonymous install id the CLI sends. The owner's machines, CI and flagged pings are left out.
196
+ usage: {
197
+ activeInstalls30d: installs.size,
198
+ activeInstalls7d: active7,
199
+ initsInWindow: newInstalls,
200
+ activatedInstalls: activated,
201
+ returningInstalls: returning,
202
+ excludedInstalls: excludedInstalls.size,
203
+ eventsByType: topCounts(cliEvents, 20),
204
+ byVersion: topCounts(byVersion),
205
+ byPlatform: topCounts(byPlatform),
206
+ },
207
+ // The newest 7 days against the 7 days before them, so a change shows without remembering last week.
208
+ weeks: { last7: weekNumbers(weeks.last7), prior7: weekNumbers(weeks.prior7) },
146
209
  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 },
147
210
  daily,
148
211
  };
149
212
  }
150
213
 
151
- module.exports = { scanFile, scanTelemetry, readTrafficWindow, DEFAULT_MAX_BYTES };
214
+ // Weekly retention for CLI installs. Week 0 is the newest 7 days. An install joins the cohort of the oldest week it was
215
+ // seen in, and `retained[k]` counts the cohort's installs seen again k weeks later. The oldest cohort also holds installs
216
+ // that began before the read window, so it is marked `includesOlder`.
217
+ async function readInstallCohorts({ weeks = 8, now = Date.now(), ...options }) {
218
+ const seen = new Map();
219
+ const meta = await scanTelemetry({
220
+ ...options,
221
+ days: weeks * 7,
222
+ now,
223
+ onEntry(entry, time) {
224
+ if (!isCli(entry) || !entry.installId || isOwnOrCiInstall(entry)) return;
225
+ const week = Math.min(weeks - 1, Math.max(0, Math.floor((now - time) / (7 * DAY_MS))));
226
+ const set = seen.get(entry.installId) || new Set();
227
+ set.add(week);
228
+ seen.set(entry.installId, set);
229
+ },
230
+ });
231
+ const cohorts = [];
232
+ for (let first = weeks - 1; first >= 0; first -= 1) {
233
+ const members = [...seen.values()].filter((set) => Math.max(...set) === first);
234
+ const retained = [];
235
+ for (let k = 0; k <= first; k += 1) retained.push(members.filter((set) => set.has(first - k)).length);
236
+ cohorts.push({ weekStart: new Date(now - (first + 1) * 7 * DAY_MS).toISOString().slice(0, 10), weeksAgo: first, size: members.length, retained, includesOlder: first === weeks - 1 });
237
+ }
238
+ return { weeks, partial: meta.partial, cohorts };
239
+ }
240
+
241
+ module.exports = { scanFile, scanTelemetry, readTrafficWindow, readInstallCohorts, DEFAULT_MAX_BYTES };
@@ -238,6 +238,8 @@ function buildProjectCatalog(root, options = {}) {
238
238
  if (stamp && Number.isFinite(Date.parse(stamp)) && (!project.lastActivity || Date.parse(stamp) > Date.parse(project.lastActivity))) project.lastActivity = stamp;
239
239
  }
240
240
  }
241
- return { projects: [...projects.values()].sort((a, b) => a.projectName.localeCompare(b.projectName)), globalGateCount: gates.filter((gate) => gate.scope === 'global' && gate.active !== false && gate.enabled !== false).length };
241
+ // A project with nothing recorded (no feedback, lessons, gates, blocks, tool calls or agents) is a leftover identity, not something to pick.
242
+ const withActivity = (project) => ({ ...project, empty: Object.values(project.counts).every((count) => !count) });
243
+ return { projects: [...projects.values()].map(withActivity).sort((a, b) => a.projectName.localeCompare(b.projectName)), globalGateCount: gates.filter((gate) => gate.scope === 'global' && gate.active !== false && gate.enabled !== false).length };
242
244
  }
243
245
  module.exports = { attributionForFile, uniqueSourceIndex, iterateRows, SIGNAL_FILES, accountDirectories, signalPaths, readRows, accountAttribution, readProjectRows, readProjectGates, buildProjectCatalog };