thumbgate 1.40.12 → 1.40.13

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.
@@ -482,12 +482,41 @@ async function managePrs(prNumber = '', runner = runGh, options = {}) {
482
482
  return { status: 'ok', prs: results };
483
483
  }
484
484
 
485
- const SWEEP_PR_FIELDS = 'number,state,isDraft,title,url,headRefName,baseRefName,updatedAt,createdAt,author,statusCheckRollup';
485
+ // Stale-PR steward. It never closes a PR. Claude Ship's PR Steward fixes PRs
486
+ // instead of closing them; the free version here does the mechanical part
487
+ // (rebase a branch that fell behind main) and labels the rest so the daily
488
+ // steward agent session (docs/ops/ship-pipeline.md) can fix the code.
489
+ // History: the old sweeper closed #5131 after 3 days as a draft.
490
+ const SWEEP_PR_FIELDS = 'number,state,isDraft,title,url,headRefName,headRefOid,baseRefName,updatedAt,createdAt,author,statusCheckRollup,mergeStateStatus,mergeable,labels';
491
+ // main has no "require up to date" rule, so GitHub never reports BEHIND here.
492
+ // The steward asks the compare API instead and updates a branch this far back.
493
+ const SWEEP_BEHIND_THRESHOLD = 10;
486
494
  const SWEEP_LIST_LIMIT = '1000';
487
495
  const SWEEP_REQUIRED_CHECKS_BASE = 'main';
488
496
  const DEFAULT_RED_MAX_AGE_MS = 24 * 60 * 60 * 1000;
489
497
  const DEFAULT_DRAFT_IDLE_MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000;
490
498
  const REQUIRED_CHECK_SET = new Set(MERGE_QUALITY_CHECKS.requiredStatusCheckContexts || []);
499
+ const STEWARD_LABELS = {
500
+ stale: 'stale',
501
+ needsFix: 'needs-fix',
502
+ needsRebase: 'needs-rebase',
503
+ };
504
+ const STEWARD_LABEL_STYLE = {
505
+ stale: ['C5DEF5', 'Steward: draft idle over 3 days'],
506
+ 'needs-fix': ['D93F0B', 'Ship gate: red checks or open review threads'],
507
+ 'needs-rebase': ['FBCA04', 'Steward: conflicts with main'],
508
+ };
509
+
510
+ /** Add a label, creating it first if the repo does not have it yet. */
511
+ function addStewardLabel(number, label, runner) {
512
+ let res = runner(['pr', 'edit', String(number), '--add-label', label]);
513
+ if (res.status !== 0 && /not found/i.test(formatGhError(res))) {
514
+ const [color, description] = STEWARD_LABEL_STYLE[label] || ['EDEDED', 'Steward'];
515
+ runner(['label', 'create', label, '--color', color, '--description', description]);
516
+ res = runner(['pr', 'edit', String(number), '--add-label', label]);
517
+ }
518
+ return res;
519
+ }
491
520
 
492
521
  function isProtectedSweepBranch(pr = {}) {
493
522
  const headRef = String(pr.headRefName || '').trim();
@@ -514,30 +543,60 @@ function isRequiredCheckFailing(check = {}) {
514
543
  return FAILING_CHECK_CONCLUSIONS.has(conclusion) || conclusion === 'ERROR';
515
544
  }
516
545
 
546
+ function prLabels(pr = {}) {
547
+ return new Set((pr.labels || []).map((l) => (typeof l === 'string' ? l : l.name)));
548
+ }
549
+
517
550
  function classifyStalePr(pr = {}, options = {}) {
518
551
  const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
519
552
  const redMaxAgeMs = Number.isFinite(options.redMaxAgeMs) ? options.redMaxAgeMs : DEFAULT_RED_MAX_AGE_MS;
520
553
  const draftIdleMaxAgeMs = Number.isFinite(options.draftIdleMaxAgeMs)
521
554
  ? options.draftIdleMaxAgeMs
522
555
  : DEFAULT_DRAFT_IDLE_MAX_AGE_MS;
556
+ const labels = prLabels(pr);
523
557
 
524
558
  if (isProtectedSweepBranch(pr)) {
525
- return {
526
- action: 'skip',
527
- reason: 'protected_branch',
528
- headRefName: pr.headRefName || '',
529
- };
559
+ return { action: 'skip', reason: 'protected_branch', headRefName: pr.headRefName || '' };
560
+ }
561
+ if (labels.has('do-not-merge')) {
562
+ return { action: 'skip', reason: 'on_hold' };
563
+ }
564
+
565
+ // A branch behind main is rebased whatever else is going on: that alone
566
+ // often turns red checks green, and it keeps drafts mergeable.
567
+ if (String(pr.mergeStateStatus || '').toUpperCase() === 'BEHIND') {
568
+ return { action: 'update_branch', reason: 'behind_main' };
569
+ }
570
+ const behindThreshold = Number.isFinite(options.behindThreshold) ? options.behindThreshold : SWEEP_BEHIND_THRESHOLD;
571
+ if (Number.isFinite(pr.behindBy) && pr.behindBy >= behindThreshold
572
+ && String(pr.mergeStateStatus || '').toUpperCase() !== 'DIRTY') {
573
+ // A merge update, not a rebase: it never rewrites a branch an agent may be working on.
574
+ return { action: 'update_branch', reason: 'behind_main_by_commits', behindBy: pr.behindBy, rebase: false };
575
+ }
576
+ if (String(pr.mergeStateStatus || '').toUpperCase() === 'DIRTY' || String(pr.mergeable || '').toUpperCase() === 'CONFLICTING') {
577
+ return labels.has(STEWARD_LABELS.needsRebase)
578
+ ? { action: 'keep', reason: 'conflict_already_flagged' }
579
+ : {
580
+ action: 'label',
581
+ label: STEWARD_LABELS.needsRebase,
582
+ reason: 'merge_conflict',
583
+ comment: `PR #${pr.number} has a merge conflict with \`main\`. Labelled \`${STEWARD_LABELS.needsRebase}\`; the steward session rebases it and resolves the conflict. Nothing was closed.`,
584
+ };
530
585
  }
531
586
 
532
587
  if (pr.isDraft) {
533
588
  const updatedMs = Date.parse(pr.updatedAt || pr.createdAt || '');
534
589
  if (Number.isFinite(updatedMs) && (nowMs - updatedMs) > draftIdleMaxAgeMs) {
535
590
  const idleDays = Math.floor((nowMs - updatedMs) / (24 * 60 * 60 * 1000));
591
+ if (labels.has(STEWARD_LABELS.stale)) {
592
+ return { action: 'keep', reason: 'draft_idle_already_flagged', idleDays };
593
+ }
536
594
  return {
537
- action: 'close',
595
+ action: 'label',
596
+ label: STEWARD_LABELS.stale,
538
597
  reason: 'draft_idle_over_3d',
539
598
  idleDays,
540
- comment: `Closing draft PR #${pr.number} after ${idleDays}d of inactivity (>3d draft idle threshold). Branch \`${pr.headRefName || 'unknown'}\` is preserved — re-open or open a fresh PR off \`origin/main\` when ready.`,
599
+ comment: `Draft PR #${pr.number} has been idle ${idleDays}d. Labelled \`${STEWARD_LABELS.stale}\` so the steward session finishes it (tests, then ready for review). It stays open.`,
541
600
  };
542
601
  }
543
602
  return { action: 'keep', reason: 'draft_active' };
@@ -546,8 +605,6 @@ function classifyStalePr(pr = {}, options = {}) {
546
605
  const checks = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];
547
606
  const failingRequired = checks.filter((check) => isRequiredCheckFailing(check));
548
607
  if (failingRequired.length > 0 && String(pr.baseRefName || '') !== SWEEP_REQUIRED_CHECKS_BASE) {
549
- // The required-check set is only known for main. For any other base
550
- // (or an unknown one) we cannot tell which red checks matter, so never close.
551
608
  return { action: 'keep', reason: 'required_checks_unknown_for_base', baseRefName: pr.baseRefName || '' };
552
609
  }
553
610
  if (failingRequired.length > 0) {
@@ -555,19 +612,20 @@ function classifyStalePr(pr = {}, options = {}) {
555
612
  .map((check) => Date.parse(check.completedAt || check.startedAt || ''))
556
613
  .filter((ts) => Number.isFinite(ts));
557
614
  const fallbackMs = Date.parse(pr.updatedAt || pr.createdAt || '');
558
- const redSinceMs = checkTimestamps.length > 0
559
- ? Math.max(...checkTimestamps)
560
- : fallbackMs;
561
-
615
+ const redSinceMs = checkTimestamps.length > 0 ? Math.max(...checkTimestamps) : fallbackMs;
562
616
  if (Number.isFinite(redSinceMs) && (nowMs - redSinceMs) > redMaxAgeMs) {
563
617
  const redHours = Math.floor((nowMs - redSinceMs) / (60 * 60 * 1000));
564
618
  const failingNames = [...new Set(failingRequired.map((c) => c.name || c.context))];
619
+ if (labels.has(STEWARD_LABELS.needsFix)) {
620
+ return { action: 'keep', reason: 'red_already_flagged', redHours, failingChecks: failingNames };
621
+ }
565
622
  return {
566
- action: 'close',
623
+ action: 'label',
624
+ label: STEWARD_LABELS.needsFix,
567
625
  reason: 'red_checks_over_24h',
568
626
  redHours,
569
627
  failingChecks: failingNames,
570
- comment: `Closing non-draft PR #${pr.number} because required check(s) (${failingNames.join(', ')}) have been red for ${redHours}h (>24h threshold). Branch \`${pr.headRefName || 'unknown'}\` is preserved — fix locally (` + '`npm test`' + `) and re-open when green.`,
628
+ comment: `Required check(s) ${failingNames.join(', ')} on PR #${pr.number} have been red for ${redHours}h. Labelled \`${STEWARD_LABELS.needsFix}\`; the steward session fixes the failure and pushes. It stays open.`,
571
629
  };
572
630
  }
573
631
  }
@@ -575,22 +633,77 @@ function classifyStalePr(pr = {}, options = {}) {
575
633
  return { action: 'keep', reason: 'active' };
576
634
  }
577
635
 
578
- function stillEligibleForClose(number, options, runner) {
636
+ /**
637
+ * gh pr list often reports mergeable/mergeStateStatus as UNKNOWN (GitHub
638
+ * computes them lazily), and never reports BEHIND without an up-to-date rule.
639
+ * Ask the REST API for the real merge state and how far behind the base the
640
+ * head is. Read-only; skipped when the list gave no head SHA.
641
+ */
642
+ function enrichSweepPr(pr, runner) {
643
+ if (!pr || !pr.headRefOid || !pr.baseRefName || !pr.number) {
644
+ return pr;
645
+ }
646
+ const out = { ...pr };
647
+ const state = runner(['api', `repos/{owner}/{repo}/pulls/${pr.number}`, '--jq', '.mergeable_state']);
648
+ if (state.status === 0) {
649
+ const value = String(state.stdout || '').trim().toUpperCase();
650
+ if (value === 'DIRTY') out.mergeStateStatus = 'DIRTY';
651
+ else if (value === 'BEHIND') out.mergeStateStatus = 'BEHIND';
652
+ }
653
+ const compare = runner(['api', `repos/{owner}/{repo}/compare/${pr.baseRefName}...${pr.headRefOid}`, '--jq', '.behind_by']);
654
+ if (compare.status === 0) {
655
+ const behind = Number(String(compare.stdout || '').trim());
656
+ if (Number.isFinite(behind)) out.behindBy = behind;
657
+ }
658
+ return out;
659
+ }
660
+
661
+ function stillNeedsAction(number, verdict, options, runner) {
579
662
  const viewResult = runner(['pr', 'view', String(number), '--json', SWEEP_PR_FIELDS]);
580
663
  if (viewResult.status !== 0) {
581
664
  return false;
582
665
  }
583
666
  try {
584
- const fresh = JSON.parse(viewResult.stdout || '{}');
585
- return fresh.state === 'OPEN' && classifyStalePr(fresh, options).action === 'close';
667
+ const fresh = enrichSweepPr(JSON.parse(viewResult.stdout || '{}'), runner);
668
+ const again = classifyStalePr(fresh, options);
669
+ return fresh.state === 'OPEN' && again.action === verdict.action && again.reason === verdict.reason;
586
670
  } catch {
587
671
  return false;
588
672
  }
589
673
  }
590
674
 
675
+ function applyStewardAction(pr, verdict, runner) {
676
+ if (verdict.action === 'update_branch') {
677
+ if (verdict.rebase !== false) {
678
+ const rebase = runner(['pr', 'update-branch', String(pr.number), '--rebase']);
679
+ if (rebase.status === 0) {
680
+ return { applied: true, via: 'rebase' };
681
+ }
682
+ }
683
+ // Rebase can fail on a conflict that a merge commit would not hit.
684
+ const merge = runner(['pr', 'update-branch', String(pr.number)]);
685
+ if (merge.status === 0) {
686
+ return { applied: true, via: 'merge' };
687
+ }
688
+ addStewardLabel(pr.number, STEWARD_LABELS.needsRebase, runner);
689
+ return { applied: false, via: 'flagged', error: formatGhError(merge) };
690
+ }
691
+ if (verdict.action === 'label') {
692
+ const labelRes = addStewardLabel(pr.number, verdict.label, runner);
693
+ if (labelRes.status !== 0) {
694
+ throw new Error(`Failed to label PR #${pr.number}: ${formatGhError(labelRes)}`);
695
+ }
696
+ const commentRes = runner(['pr', 'comment', String(pr.number), '--body', verdict.comment]);
697
+ if (commentRes.status !== 0) {
698
+ throw new Error(`Failed to comment on PR #${pr.number}: ${formatGhError(commentRes)}`);
699
+ }
700
+ return { applied: true };
701
+ }
702
+ return { applied: false };
703
+ }
704
+
591
705
  function sweepStalePrs(options = {}, runner = runGh) {
592
706
  const dryRun = Boolean(options.dryRun);
593
- // A high limit makes gh paginate through every open PR, so none are silently skipped.
594
707
  const listResult = runner(['pr', 'list', '--state', 'open', '--limit', SWEEP_LIST_LIMIT, '--json', SWEEP_PR_FIELDS]);
595
708
  if (listResult.status !== 0) {
596
709
  throw new Error(`Failed to list open PRs for sweep: ${formatGhError(listResult)}`);
@@ -598,11 +711,13 @@ function sweepStalePrs(options = {}, runner = runGh) {
598
711
 
599
712
  const prs = JSON.parse(listResult.stdout || '[]');
600
713
  const decisions = [];
601
- let closedCount = 0;
714
+ let actedCount = 0;
602
715
  let skippedCount = 0;
603
716
  let keptCount = 0;
717
+ let errorCount = 0;
604
718
 
605
- for (const pr of prs) {
719
+ for (const listed of prs) {
720
+ const pr = isProtectedSweepBranch(listed) ? listed : enrichSweepPr(listed, runner);
606
721
  const verdict = classifyStalePr(pr, options);
607
722
  const record = {
608
723
  number: pr.number,
@@ -612,45 +727,44 @@ function sweepStalePrs(options = {}, runner = runGh) {
612
727
  ...verdict,
613
728
  applied: false,
614
729
  };
730
+ delete record.comment;
615
731
 
616
732
  if (verdict.action === 'skip') {
617
733
  skippedCount += 1;
618
- } else if (verdict.action === 'close' && !dryRun && !stillEligibleForClose(pr.number, options, runner)) {
619
- // The PR changed after it was listed (new push, checks recovered, undrafted).
734
+ } else if (verdict.action === 'keep') {
735
+ keptCount += 1;
736
+ } else if (!dryRun && !stillNeedsAction(pr.number, verdict, options, runner)) {
620
737
  record.action = 'keep';
621
738
  record.reason = 'eligibility_changed';
622
739
  keptCount += 1;
623
- } else if (verdict.action === 'close') {
624
- closedCount += 1;
740
+ } else {
741
+ actedCount += 1;
625
742
  if (!dryRun) {
626
- const commentRes = runner(['pr', 'comment', String(pr.number), '--body', verdict.comment]);
627
- if (commentRes.status !== 0) {
628
- throw new Error(`Failed to comment on PR #${pr.number}: ${formatGhError(commentRes)}`);
629
- }
630
- // Never pass --delete-branch: branches are preserved by policy.
631
- const closeRes = runner(['pr', 'close', String(pr.number)]);
632
- if (closeRes.status !== 0) {
633
- throw new Error(`Failed to close PR #${pr.number}: ${formatGhError(closeRes)}`);
743
+ // One PR's failure must not stop the sweep for the rest.
744
+ try {
745
+ Object.assign(record, applyStewardAction(pr, verdict, runner));
746
+ } catch (err) {
747
+ record.error = err.message;
748
+ errorCount += 1;
634
749
  }
635
- record.applied = true;
636
750
  }
637
- } else {
638
- keptCount += 1;
639
751
  }
640
-
641
752
  decisions.push(record);
642
753
  }
643
754
 
644
755
  return {
645
756
  status: 'ok',
646
757
  dryRun,
647
- closedCount,
758
+ actedCount,
759
+ closedCount: 0,
648
760
  skippedCount,
649
761
  keptCount,
762
+ errorCount,
650
763
  decisions,
651
764
  };
652
765
  }
653
766
 
767
+
654
768
  if (require.main === module) {
655
769
  const argv = process.argv.slice(2);
656
770
  if (argv.includes('--sweep') || argv.includes('--sweep-stale')) {
@@ -662,10 +776,10 @@ if (require.main === module) {
662
776
  console.log(JSON.stringify(summary, null, 2));
663
777
  } else {
664
778
  console.log(
665
- `[PR Sweeper] dryRun=${summary.dryRun} closed=${summary.closedCount} skipped=${summary.skippedCount} kept=${summary.keptCount}`,
779
+ `[PR Steward] dryRun=${summary.dryRun} acted=${summary.actedCount} skipped=${summary.skippedCount} kept=${summary.keptCount} errors=${summary.errorCount} closed=0`,
666
780
  );
667
781
  }
668
- process.exit(0);
782
+ process.exit(summary.errorCount > 0 ? 1 : 0);
669
783
  } catch (err) {
670
784
  console.error(err.message);
671
785
  process.exit(1);
@@ -685,6 +799,7 @@ module.exports = {
685
799
  assertSafeGhArgs,
686
800
  buildGhEnv,
687
801
  classifyStalePr,
802
+ enrichSweepPr,
688
803
  getPrStatus,
689
804
  getPrChecks,
690
805
  isProtectedSweepBranch,
@@ -110,6 +110,11 @@ function resolveLocalProjectUncached(cwd = process.cwd(), options = {}) {
110
110
  const projectName = homeFolder && root === homeFolder ? 'Home folder (no project)' : safeProjectName(path.basename(root), 'Local project');
111
111
  return { projectKey: `local_${hash(`${machineIdentity(options)}\0${root}`)}`, projectName, identitySource: 'local' };
112
112
  }
113
+ // A folder is a real project only when its git remote identifies it (the same rule as isRealProject in public/project-switcher.js).
114
+ function isProjectFolder(dir, options = {}) {
115
+ if (!dir || typeof dir !== 'string') return false;
116
+ try { return resolveLocalProject(dir, options).identitySource === 'remote'; } catch { return false; }
117
+ }
113
118
  function legacyAlias(record = {}, options = {}) {
114
119
  const registry = options.recordType === 'agent-registry.jsonl' || record.recordType === 'agent-registry.jsonl';
115
120
  const value = record.scope?.projectId || record.metadata?.project || record.metadata?.repo || record.projectId || (registry ? record.registryProject || record.project : null);
@@ -182,4 +187,4 @@ function projectForCapture(input = {}, options = {}) {
182
187
  if ((input.projectKey && input.projectKey !== descriptor.projectKey) || (remote && remote.projectKey !== descriptor.projectKey)) throw invalid('Project key does not match execution directory');
183
188
  return descriptor;
184
189
  }
185
- module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
190
+ module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, isProjectFolder, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ // Unit economics for the owner console: what it costs to deliver ThumbGate, per active install and per paying customer,
4
+ // and what each plan keeps after those costs. Pure arithmetic over numbers the app already has:
5
+ // - hosting: the container's own measured CPU and memory (scripts/cost-meter.js) at Railway's list rates
6
+ // - email: emails the mailer sent, at Resend's per-email rate
7
+ // - payment fees: Stripe's fee on each ThumbGate checkout when Stripe returned it, else the published card rate
8
+ // - revenue: Stripe checkouts and renewal invoices (US dollars only; other currencies are listed, never converted)
9
+ // Every figure carries its basis. A number that cannot be measured is null with a reason, never a guess.
10
+
11
+ const fs = require('node:fs');
12
+ const path = require('node:path');
13
+
14
+ const MONTH_SECONDS = 30 * 86400;
15
+ const cents = (usd) => (Number.isFinite(usd) ? Math.round(usd * 100) : null);
16
+ const round2 = (n) => (Number.isFinite(n) ? Math.round(n * 100) / 100 : null);
17
+ const round4 = (n) => (Number.isFinite(n) ? Math.round(n * 10000) / 10000 : null);
18
+ const usdCents = (byCurrency) => (byCurrency && Number.isSafeInteger(byCurrency.USD) ? byCurrency.USD : 0);
19
+ const sumList = (list) => (Array.isArray(list) ? list : []).filter((item) => item && Number.isFinite(item.usd) && item.usd >= 0).reduce((total, item) => total + item.usd, 0);
20
+
21
+ function loadUnitCosts(file = path.join(__dirname, '..', 'config', 'unit-costs.json')) {
22
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
23
+ }
24
+
25
+ // Hosting for the window: measured compute plus the configured volume and egress, scaled to 30 days when the meter
26
+ // covered only part of the window (for example the first days after this feature shipped).
27
+ function hostingCost(meter, rates) {
28
+ if (!meter || !rates || !(meter.sampledSeconds > 0)) return { usd: null, measuredUsd: null, coverage: meter ? meter.coverage || 0 : 0, basis: 'not_measured_yet', reason: 'The cost meter has no samples yet. It records once a minute after the server starts.' };
29
+ const cpuUsd = (meter.cpuSeconds / MONTH_SECONDS) * rates.vcpuMonthUsd;
30
+ const memoryUsd = (meter.memoryGbSeconds / MONTH_SECONDS) * rates.memoryGbMonthUsd;
31
+ const measuredUsd = cpuUsd + memoryUsd;
32
+ const scale = MONTH_SECONDS / meter.sampledSeconds;
33
+ const computeMonthUsd = measuredUsd * scale;
34
+ const volumeUsd = (Number(rates.volumeGb) || 0) * (Number(rates.volumeGbMonthUsd) || 0);
35
+ const egressUsd = (Number(rates.egressGbPerMonth) || 0) * (Number(rates.egressGbUsd) || 0);
36
+ const full = meter.coverage >= 0.95;
37
+ return {
38
+ usd: round4(computeMonthUsd + volumeUsd + egressUsd),
39
+ measuredUsd: round4(measuredUsd),
40
+ parts: { cpuUsd: round4(cpuUsd * scale), memoryUsd: round4(memoryUsd * scale), volumeUsd: round4(volumeUsd), egressUsd: round4(egressUsd) },
41
+ coverage: round4(meter.coverage),
42
+ sources: meter.sources || [],
43
+ basis: full ? 'measured_30d' : 'projected_from_partial_window',
44
+ reason: full ? null : `The meter covered ${Math.round(meter.coverage * 1000) / 10}% of the 30 days, so compute is projected to 30 days from what it saw.`,
45
+ };
46
+ }
47
+
48
+ // Stripe fees in US dollars: the fees Stripe returned for ThumbGate checkouts, plus the published rate for what it did not
49
+ // return and for renewal invoices. Subscription money also pays the Stripe Billing percentage.
50
+ function paymentFees(money, rates) {
51
+ if (!money || !rates) return { usd: null, basis: 'unavailable', reason: 'Stripe numbers are not available right now.' };
52
+ const fees = money.paymentFees30d || {};
53
+ const reported = usdCents(fees.reportedFees) / 100;
54
+ const unreportedCharges = Number.isSafeInteger(fees.unreportedCharges) ? fees.unreportedCharges : 0;
55
+ const unreportedAmount = usdCents(fees.unreportedAmount) / 100;
56
+ const renewalCount = Number.isSafeInteger(money.recurring30d?.renewalInvoices) ? money.recurring30d.renewalInvoices : 0;
57
+ const renewalUsd = usdCents(money.recurring30d?.renewalRevenue) / 100;
58
+ const card = (count, amount) => count * rates.fixedUsd + amount * rates.percent;
59
+ const estimated = card(unreportedCharges, unreportedAmount) + card(renewalCount, renewalUsd) + renewalUsd * (rates.billingPercent || 0) + (usdCents(fees.subscriptionFirstCharges) / 100) * (rates.billingPercent || 0);
60
+ return { usd: round4(reported + estimated), reportedUsd: round4(reported), estimatedUsd: round4(estimated), basis: estimated > 0 ? (reported > 0 ? 'stripe_reported_plus_published_rate' : 'published_rate') : 'stripe_reported' };
61
+ }
62
+
63
+ function perUnit(totalUsd, count) {
64
+ return Number.isFinite(totalUsd) && Number.isInteger(count) && count > 0 ? round4(totalUsd / count) : null;
65
+ }
66
+
67
+ // Contribution for one plan sale: price, minus the payment fee on that price, minus the delivery cost one customer adds.
68
+ function planContribution({ priceUsd, recurring, costPerCustomerUsd, rates, laborNote = null }) {
69
+ if (!Number.isFinite(priceUsd) || !rates) return null;
70
+ const feeUsd = priceUsd * rates.percent + rates.fixedUsd + (recurring ? priceUsd * (rates.billingPercent || 0) : 0);
71
+ const deliveryUsd = Number.isFinite(costPerCustomerUsd) ? costPerCustomerUsd : 0;
72
+ const contributionUsd = priceUsd - feeUsd - deliveryUsd;
73
+ return { priceUsd: round2(priceUsd), paymentFeeUsd: round2(feeUsd), deliveryCostUsd: round4(deliveryUsd), contributionUsd: round2(contributionUsd), marginPct: round4(contributionUsd / priceUsd), laborNote };
74
+ }
75
+
76
+ // The whole board. `money` is collectMoney's data, `usage` the 30-day CLI usage, `meter` cost-meter's 30-day window.
77
+ function computeUnitEconomics({ money = null, usage = null, meter = null, costs = loadUnitCosts() } = {}) {
78
+ if (!costs) return { status: 'unavailable', reason: 'config/unit-costs.json could not be read.' };
79
+ const hosting = hostingCost(meter, costs.hosting);
80
+ const emails = meter ? meter.emails : null;
81
+ const emailUsd = Number.isInteger(emails) ? round4(emails * costs.email.costPerEmailUsd) : null;
82
+ const fees = paymentFees(money, costs.payments);
83
+ const fixedUsd = round4(sumList(costs.fixedDeliveryMonthly));
84
+ const buildUsd = round4(sumList(costs.buildAndInternalMonthly));
85
+ const parts = [hosting.usd, emailUsd, fees.usd, fixedUsd];
86
+ const deliveryUsd = parts.every(Number.isFinite) ? round4(parts.reduce((a, b) => a + b, 0)) : null;
87
+ // Serving cost (hosting, email, fixed) is shared by every install; payment fees belong to paying customers only.
88
+ const servingUsd = [hosting.usd, emailUsd, fixedUsd].every(Number.isFinite) ? hosting.usd + emailUsd + fixedUsd : null;
89
+
90
+ const activeInstalls = Number.isInteger(usage?.activeInstalls30d) ? usage.activeInstalls30d : null;
91
+ const payingCustomers = Number.isInteger(money?.payingCustomers) ? money.payingCustomers : null;
92
+ const activePro = Number.isInteger(money?.activePro) ? money.activePro : null;
93
+ const servingPerInstall = perUnit(servingUsd, activeInstalls);
94
+
95
+ const oneTimeUsd = money ? usdCents(money.revenueLast30Days) / 100 : null;
96
+ const renewalsUsd = money ? usdCents(money.recurring30d?.renewalRevenue) / 100 : null;
97
+ const revenueUsd = money ? round2(oneTimeUsd + renewalsUsd) : null;
98
+ const otherCurrencies = money ? [...new Set([...Object.keys(money.revenueLast30Days || {}), ...Object.keys(money.recurring30d?.renewalRevenue || {}), ...Object.keys(money.mrr || {})])].filter((code) => code !== 'USD') : [];
99
+ const contribution = Number.isFinite(revenueUsd) && Number.isFinite(deliveryUsd)
100
+ ? { revenueUsd, deliveryUsd, contributionUsd: round2(revenueUsd - deliveryUsd), marginPct: revenueUsd > 0 ? round4((revenueUsd - deliveryUsd) / revenueUsd) : null, afterBuildUsd: round2(revenueUsd - deliveryUsd - buildUsd) }
101
+ : null;
102
+
103
+ // Pro: the list price, or the average active subscription in dollars when Stripe has some.
104
+ const mrrUsd = money ? usdCents(money.mrr) / 100 : 0;
105
+ const proPrice = activePro > 0 && mrrUsd > 0 ? mrrUsd / activePro : costs.plans.pro.listMonthlyUsd;
106
+ const plans = {
107
+ pro: { name: costs.plans.pro.name, priceBasis: activePro > 0 && mrrUsd > 0 ? 'stripe_average_active_subscription' : 'list_price', ...planContribution({ priceUsd: proPrice, recurring: true, costPerCustomerUsd: servingPerInstall, rates: costs.payments }) },
108
+ setupSprint: { name: costs.plans.setupSprint.name, priceBasis: 'list_price', ...planContribution({ priceUsd: costs.plans.setupSprint.listUsd, recurring: false, costPerCustomerUsd: servingPerInstall, rates: costs.payments, laborNote: costs.plans.setupSprint.deliveryHoursNote }) },
109
+ };
110
+
111
+ const reasons = {};
112
+ if (hosting.reason) reasons.hosting = hosting.reason;
113
+ if (fees.reason) reasons.paymentFees = fees.reason;
114
+ if (activeInstalls === null) reasons.activeInstalls = 'CLI usage telemetry is not available right now.';
115
+ else if (activeInstalls === 0) reasons.activeInstalls = 'No active installs in 30 days, so there is no cost per install.';
116
+ if (payingCustomers === 0) reasons.payingCustomers = 'No paying customers, so there is no cost per paying customer.';
117
+ if (!costs.fixedDeliveryMonthly.length) reasons.fixed = 'No fixed delivery costs are recorded in config/unit-costs.json.';
118
+ if (!costs.buildAndInternalMonthly.length) reasons.build = 'No build or internal costs are recorded in config/unit-costs.json, so "after build costs" equals contribution.';
119
+ if (otherCurrencies.length) reasons.currencies = `Revenue in ${otherCurrencies.join(', ')} is left out: only US dollars are added up, and nothing is converted.`;
120
+
121
+ return {
122
+ status: deliveryUsd === null ? 'partial' : 'ok',
123
+ window: '30d',
124
+ ratesCheckedAt: costs.checkedAt,
125
+ delivery: { hostingUsd: hosting.usd, hosting, emails, emailUsd, emailBasis: costs.email.basis, paymentFeesUsd: fees.usd, paymentFees: fees, fixedUsd, totalUsd: deliveryUsd },
126
+ build: { totalUsd: buildUsd, items: costs.buildAndInternalMonthly },
127
+ denominators: { activeInstalls30d: activeInstalls, payingCustomers, activePro },
128
+ perActiveInstallUsd: servingPerInstall,
129
+ perPayingCustomerUsd: perUnit(deliveryUsd, payingCustomers),
130
+ revenue: { oneTimeUsd, renewalsUsd, totalUsd: revenueUsd, mrrUsd: money ? round2(mrrUsd) : null },
131
+ contribution,
132
+ plans,
133
+ reasons,
134
+ sources: { hosting: costs.hosting.source, email: costs.email.source, payments: costs.payments.source },
135
+ };
136
+ }
137
+
138
+ module.exports = { computeUnitEconomics, hostingCost, paymentFees, planContribution, loadUnitCosts, cents };
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.12",
11
+ "version": "1.40.13",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "thumbgate",
17
- "version": "1.40.12",
17
+ "version": "1.40.13",
18
18
  "runtimeHint": "npx",
19
19
  "runtimeArguments": [
20
20
  {
package/src/api/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  const { withDataScope, withoutDataScope, currentDataScope, tenantDataScope, assertScopedDataPath, dataScopeKey } = require('../../scripts/feedback-scope');
3
- const { parseProjectSelection, projectForCapture, projectForRecord, matchesProject, validProjectKey } = require('../../scripts/project-identity');
3
+ const { isProjectFolder, parseProjectSelection, projectForCapture, projectForRecord, matchesProject, validProjectKey } = require('../../scripts/project-identity');
4
4
  const { readProjectRows, buildProjectCatalog } = require('../../scripts/project-catalog');
5
5
  const ownerAdmin = require('../../scripts/owner-admin');
6
6
  const opsLog = require('../../scripts/ops-log');
@@ -5140,6 +5140,7 @@ function renderSitemapXml(runtimeConfig) {
5140
5140
  { path: '/learn/future-agi-self-healing-agent-firewall', changefreq: 'weekly', priority: '0.85' },
5141
5141
  { path: '/learn/five-walls-enterprise-agent-deployment', changefreq: 'weekly', priority: '0.85' },
5142
5142
  { path: '/learn/okta-mcp-governance-per-tool-call-gates', changefreq: 'weekly', priority: '0.85' },
5143
+ { path: '/learn/ai-finops-agent-spend-guardrails', changefreq: 'weekly', priority: '0.85' },
5143
5144
  { path: '/compare/claude-code-hooks', changefreq: 'weekly', priority: '0.85' },
5144
5145
  { path: '/compare/bumblebee', changefreq: 'weekly', priority: '0.85' },
5145
5146
  { path: '/compare/anthropic-containment', changefreq: 'weekly', priority: '0.85' },
@@ -7568,6 +7569,10 @@ function createUnscopedApiServer({ ownerAdminDependencies = {} } = {}) {
7568
7569
  health: () => ({ version: pkg.version, buildSha: BUILD_METADATA.buildSha, uptime: process.uptime() }),
7569
7570
  ...ownerAdminDependencies,
7570
7571
  })));
7572
+ // Cost meter for the owner console's unit economics: hosted deployments only (Railway sets RAILWAY_ENVIRONMENT), never under tests.
7573
+ if (!process.env.NODE_TEST_CONTEXT && (process.env.RAILWAY_ENVIRONMENT || process.env.THUMBGATE_COST_METER === '1')) {
7574
+ try { require('../../scripts/cost-meter').start({ feedbackDir: withoutDataScope(() => getFeedbackPaths().FEEDBACK_DIR) }); } catch { /* best-effort */ }
7575
+ }
7571
7576
  const observedRequests = new WeakSet();
7572
7577
  const eventBus = new EventEmitter();
7573
7578
  eventBus.setMaxListeners(200);
@@ -11820,7 +11825,12 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
11820
11825
  const _token = extractBearerToken(req);
11821
11826
  if (_token && _token !== expectedApiKey) recordUsage(_token);
11822
11827
  Object.assign(projectOptions, { projectKey: requestProjectKey, feedbackDir: requestFeedbackDir }, projectEvidenceForRequest(req, parsed, requestFeedbackDir, requestDataIdentity));
11823
- if (req.method === 'GET' && pathname === '/v1/projects') { sendJson(res, 200, { ...buildProjectCatalog(requestFeedbackDir, projectOptions), projectDir: projectOptions.projectDir || process.env.THUMBGATE_PROJECT_DIR || null }); return; }
11828
+ if (req.method === 'GET' && pathname === '/v1/projects') {
11829
+ // The folder the dashboard was opened for: the page's own projectDir (loopback only), else the server's.
11830
+ const catalogDir = getEffectiveRequestedProjectSelection(req, parsed) || projectOptions.projectDir || process.env.THUMBGATE_PROJECT_DIR || null;
11831
+ sendJson(res, 200, { ...buildProjectCatalog(requestFeedbackDir, projectOptions), projectDir: catalogDir, projectDirIsProject: catalogDir ? isProjectFolder(catalogDir) : null });
11832
+ return;
11833
+ }
11824
11834
  if (requestProjectKey != null && req.method === 'GET' && ['/v1/dashboard', '/v1/feedback/stats'].includes(pathname)) {
11825
11835
  const data = generateDashboard(requestFeedbackDir, {
11826
11836
  projectKey: requestProjectKey, ...projectOptions, humanOnly: true,
@@ -344,8 +344,8 @@ const STRIPE_OFFER_CATALOG = Object.freeze({
344
344
  }),
345
345
  pro_19: Object.freeze({
346
346
  offerId: 'pro_19', productPagePath: '/pro', priceUsd: 19, billingType: 'subscription', proofPath: '/pro',
347
- headline: 'ThumbGate Pro is for one operator who already hit a repeated AI-agent failure and now needs proof: what was blocked, why it was blocked, and what changed before the next risky run.', ctaLabel: 'Start Pro',
348
- rationale: 'Start Pro when you want the local dashboard, DPO export, and a single proof lane for the repeated mistake you need to stop.',
347
+ headline: 'Keep every lesson your agent learned, and ask it what went wrong before.', ctaLabel: 'Start Pro',
348
+ rationale: 'The free CLI already denies catastrophic commands and secret leaks. ThumbGate Pro is about memory: every rule you teach with a thumbs-down stays active, you can record as many thumbs as you like, and you can search and export what was learned.',
349
349
  checkoutPath: '/go/pro-direct?utm_source=website&utm_medium=objection_rescue&utm_campaign=pro_upgrade',
350
350
  }),
351
351
  diagnostic_499: Object.freeze({