thumbgate 1.39.1 → 1.40.2
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.
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +5 -4
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +82 -7
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +128 -15
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +1 -0
- package/config/post-deploy-marketing-pages.json +3 -3
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +98 -31
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +1 -2
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +773 -481
- package/public/diagnostic.html +8 -3
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +181 -205
- package/public/install.html +12 -11
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +103 -46
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +61 -327
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-report.js +363 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/check-update.js +236 -0
- package/scripts/cli-schema.js +1 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +576 -169
- package/scripts/decision-journal.js +7 -4
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/gate-stats.js +8 -2
- package/scripts/gates-engine.js +694 -230
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hybrid-feedback-context.js +5 -2
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/intervention-policy.js +2 -1
- package/scripts/latency-budget.js +164 -0
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-integrity.js +436 -3
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/session-report.js +120 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/task-outcomes.js +29 -2
- package/scripts/telemetry-analytics.js +238 -13
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/src/api/server.js +2371 -451
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* conversion-rate-stats.js — honest conversion-rate estimation for low-N data.
|
|
4
|
+
*
|
|
5
|
+
* THE PROBLEM THIS SOLVES
|
|
6
|
+
*
|
|
7
|
+
* ThumbGate has shipped 7 public revenue surfaces (/, /pricing, /case-studies,
|
|
8
|
+
* /compare/heidi, /learn/spec-driven-development, /pro, /go/teams). Each will
|
|
9
|
+
* accumulate Plausible visitor counts and (eventually) Stripe charges. The
|
|
10
|
+
* naïve approach is to compute conversion = charges / visitors per surface
|
|
11
|
+
* and rank surfaces by that ratio.
|
|
12
|
+
*
|
|
13
|
+
* That approach lies at low N. /case-studies with 1 visitor and 0 charges
|
|
14
|
+
* gets a "0%" rate, but the truth is "we don't know — could be 0%, could be
|
|
15
|
+
* 80%, sample is too small." Likewise a /pricing surface with 1 visitor and
|
|
16
|
+
* 1 charge gets ranked as 100% conversion, which would steer all traffic to
|
|
17
|
+
* a surface that converted exactly one buyer.
|
|
18
|
+
*
|
|
19
|
+
* The right ML for this regime is a Bayesian beta-binomial model:
|
|
20
|
+
*
|
|
21
|
+
* conversion_rate ~ Beta(α + successes, β + failures)
|
|
22
|
+
*
|
|
23
|
+
* With a weakly informative prior (Beta(α₀, β₀) reflecting a "most
|
|
24
|
+
* dev-tool surfaces convert at 1-3%" expectation), the posterior gives a
|
|
25
|
+
* credible interval that GETS NARROWER as N grows. At N=0 the interval is
|
|
26
|
+
* wide and honest; at N=10,000 the interval tightens to the empirical rate.
|
|
27
|
+
* Same code path, no need to switch models when "we finally have data."
|
|
28
|
+
*
|
|
29
|
+
* This module exports pure stats functions (no IO, no fetch) so they're
|
|
30
|
+
* trivial to test and easy to wire into the unified revenue rollup once
|
|
31
|
+
* #2090 lands.
|
|
32
|
+
*
|
|
33
|
+
* WHY NOT JUST USE THE FREQUENTIST RATE
|
|
34
|
+
*
|
|
35
|
+
* Wilson score interval, Agresti-Coull, etc. are options but they're not
|
|
36
|
+
* naturally extensible to Thompson Sampling (which IS in the ThumbGate
|
|
37
|
+
* stack already, for gate-policy bandits). Beta-binomial gives us a posterior
|
|
38
|
+
* we can sample from when we want to allocate traffic adaptively across
|
|
39
|
+
* surfaces — same model, two uses.
|
|
40
|
+
*
|
|
41
|
+
* REFERENCES
|
|
42
|
+
* Wikipedia: Beta-binomial distribution
|
|
43
|
+
* ThumbGate's existing scripts/thompson-sampling.js — uses Beta posteriors
|
|
44
|
+
* for arm selection in the gate-policy bandit.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
'use strict';
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// Beta distribution math
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* log Gamma function (Lanczos approximation). Used to compute Beta-function
|
|
55
|
+
* normalizing constants when we need PDF / CDF values. Lanczos is good to
|
|
56
|
+
* ~14 digits over the positive reals which is plenty for our use case
|
|
57
|
+
* (conversion-rate counts; α and β are small integers + prior).
|
|
58
|
+
*
|
|
59
|
+
* @param {number} x
|
|
60
|
+
* @returns {number}
|
|
61
|
+
*/
|
|
62
|
+
function logGamma(x) {
|
|
63
|
+
if (x <= 0) {
|
|
64
|
+
throw new RangeError(`logGamma requires positive input, got ${x}`);
|
|
65
|
+
}
|
|
66
|
+
// Lanczos approximation with g = 7, n = 9
|
|
67
|
+
const g = 7;
|
|
68
|
+
const c = [
|
|
69
|
+
0.99999999999980993,
|
|
70
|
+
676.5203681218851,
|
|
71
|
+
-1259.1392167224028,
|
|
72
|
+
771.32342877765313,
|
|
73
|
+
-176.61502916214059,
|
|
74
|
+
12.507343278686905,
|
|
75
|
+
-0.13857109526572012,
|
|
76
|
+
9.9843695780195716e-6,
|
|
77
|
+
1.5056327351493116e-7,
|
|
78
|
+
];
|
|
79
|
+
if (x < 0.5) {
|
|
80
|
+
// Reflection formula
|
|
81
|
+
return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
|
|
82
|
+
}
|
|
83
|
+
const z = x - 1;
|
|
84
|
+
let sum = c[0];
|
|
85
|
+
for (let i = 1; i < g + 2; i += 1) {
|
|
86
|
+
sum += c[i] / (z + i);
|
|
87
|
+
}
|
|
88
|
+
const t = z + g + 0.5;
|
|
89
|
+
return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(sum);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Regularized incomplete beta function I_x(α, β), computed by Lentz's
|
|
94
|
+
* algorithm for the continued fraction. This is the CDF of the Beta
|
|
95
|
+
* distribution at point x.
|
|
96
|
+
*
|
|
97
|
+
* @param {number} x — point in [0, 1]
|
|
98
|
+
* @param {number} a — alpha (>0)
|
|
99
|
+
* @param {number} b — beta (>0)
|
|
100
|
+
* @returns {number}
|
|
101
|
+
*/
|
|
102
|
+
function regularizedIncompleteBeta(x, a, b) {
|
|
103
|
+
if (x <= 0) return 0;
|
|
104
|
+
if (x >= 1) return 1;
|
|
105
|
+
if (a <= 0 || b <= 0) {
|
|
106
|
+
throw new RangeError(`regularizedIncompleteBeta requires a, b > 0; got a=${a} b=${b}`);
|
|
107
|
+
}
|
|
108
|
+
// Continued fraction expansion. Use symmetry to ensure faster convergence.
|
|
109
|
+
const bt = Math.exp(
|
|
110
|
+
logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x)
|
|
111
|
+
);
|
|
112
|
+
if (x < (a + 1) / (a + b + 2)) {
|
|
113
|
+
return (bt * betaContinuedFraction(x, a, b)) / a;
|
|
114
|
+
}
|
|
115
|
+
return 1 - (bt * betaContinuedFraction(1 - x, b, a)) / b;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Lentz-method continued-fraction evaluator for the incomplete beta.
|
|
120
|
+
*
|
|
121
|
+
* @param {number} x
|
|
122
|
+
* @param {number} a
|
|
123
|
+
* @param {number} b
|
|
124
|
+
* @returns {number}
|
|
125
|
+
*/
|
|
126
|
+
function betaContinuedFraction(x, a, b) {
|
|
127
|
+
const MAX_ITERATIONS = 200;
|
|
128
|
+
const EPS = 3e-15;
|
|
129
|
+
const FPMIN = 1e-300;
|
|
130
|
+
const qab = a + b;
|
|
131
|
+
const qap = a + 1;
|
|
132
|
+
const qam = a - 1;
|
|
133
|
+
let c = 1;
|
|
134
|
+
let d = 1 - (qab * x) / qap;
|
|
135
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
136
|
+
d = 1 / d;
|
|
137
|
+
let h = d;
|
|
138
|
+
for (let m = 1; m <= MAX_ITERATIONS; m += 1) {
|
|
139
|
+
const m2 = 2 * m;
|
|
140
|
+
let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
|
|
141
|
+
d = 1 + aa * d;
|
|
142
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
143
|
+
c = 1 + aa / c;
|
|
144
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
145
|
+
d = 1 / d;
|
|
146
|
+
h *= d * c;
|
|
147
|
+
aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
|
|
148
|
+
d = 1 + aa * d;
|
|
149
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
150
|
+
c = 1 + aa / c;
|
|
151
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
152
|
+
d = 1 / d;
|
|
153
|
+
const del = d * c;
|
|
154
|
+
h *= del;
|
|
155
|
+
if (Math.abs(del - 1) < EPS) {
|
|
156
|
+
return h;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return h;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Inverse CDF (quantile function) of the Beta distribution. Uses
|
|
164
|
+
* bisection on the regularized incomplete beta. Slow, but bisection is
|
|
165
|
+
* deterministic and we only call this twice per surface per rollup, so
|
|
166
|
+
* speed doesn't matter.
|
|
167
|
+
*
|
|
168
|
+
* @param {number} p — probability in (0, 1)
|
|
169
|
+
* @param {number} a — alpha (>0)
|
|
170
|
+
* @param {number} b — beta (>0)
|
|
171
|
+
* @returns {number}
|
|
172
|
+
*/
|
|
173
|
+
function betaQuantile(p, a, b) {
|
|
174
|
+
if (p <= 0) return 0;
|
|
175
|
+
if (p >= 1) return 1;
|
|
176
|
+
if (a <= 0 || b <= 0) {
|
|
177
|
+
throw new RangeError(`betaQuantile requires a, b > 0; got a=${a} b=${b}`);
|
|
178
|
+
}
|
|
179
|
+
// Bisection
|
|
180
|
+
let lo = 0;
|
|
181
|
+
let hi = 1;
|
|
182
|
+
const EPS = 1e-10;
|
|
183
|
+
const MAX_ITER = 100;
|
|
184
|
+
for (let i = 0; i < MAX_ITER; i += 1) {
|
|
185
|
+
const mid = (lo + hi) / 2;
|
|
186
|
+
const cdf = regularizedIncompleteBeta(mid, a, b);
|
|
187
|
+
if (Math.abs(cdf - p) < EPS) {
|
|
188
|
+
return mid;
|
|
189
|
+
}
|
|
190
|
+
if (cdf < p) {
|
|
191
|
+
lo = mid;
|
|
192
|
+
} else {
|
|
193
|
+
hi = mid;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return (lo + hi) / 2;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
// Beta-binomial conversion-rate inference
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Default weakly-informative prior: Beta(1, 19) reflects "most dev-tool
|
|
205
|
+
* surfaces convert at around 5% with broad uncertainty." Mean 0.05, mode 0.
|
|
206
|
+
* Equivalent to "we've seen 1 prior success out of 20 prior trials."
|
|
207
|
+
*
|
|
208
|
+
* The choice is opinionated but defensible — the alternative (Beta(1,1),
|
|
209
|
+
* uniform) puts too much mass on >50% conversion rates, which is unrealistic
|
|
210
|
+
* for cold landing pages. The prior gets washed out by ~30 real observations
|
|
211
|
+
* either way.
|
|
212
|
+
*/
|
|
213
|
+
const DEFAULT_PRIOR_ALPHA = 1;
|
|
214
|
+
const DEFAULT_PRIOR_BETA = 19;
|
|
215
|
+
const DEFAULT_CREDIBLE_LEVEL = 0.95;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Compute the posterior Beta distribution parameters for a conversion rate
|
|
219
|
+
* given observed successes and trials, with a configurable prior.
|
|
220
|
+
*
|
|
221
|
+
* @param {object} input
|
|
222
|
+
* @param {number} input.successes — non-negative integer count of conversions
|
|
223
|
+
* @param {number} input.trials — non-negative integer count of visitor sessions
|
|
224
|
+
* @param {number} [input.priorAlpha=DEFAULT_PRIOR_ALPHA]
|
|
225
|
+
* @param {number} [input.priorBeta=DEFAULT_PRIOR_BETA]
|
|
226
|
+
* @returns {{alpha: number, beta: number}}
|
|
227
|
+
*/
|
|
228
|
+
function posteriorParameters({
|
|
229
|
+
successes,
|
|
230
|
+
trials,
|
|
231
|
+
priorAlpha = DEFAULT_PRIOR_ALPHA,
|
|
232
|
+
priorBeta = DEFAULT_PRIOR_BETA,
|
|
233
|
+
}) {
|
|
234
|
+
if (!Number.isFinite(successes) || successes < 0) {
|
|
235
|
+
throw new RangeError(`successes must be a non-negative number, got ${successes}`);
|
|
236
|
+
}
|
|
237
|
+
if (!Number.isFinite(trials) || trials < 0) {
|
|
238
|
+
throw new RangeError(`trials must be a non-negative number, got ${trials}`);
|
|
239
|
+
}
|
|
240
|
+
if (successes > trials) {
|
|
241
|
+
throw new RangeError(`successes (${successes}) cannot exceed trials (${trials})`);
|
|
242
|
+
}
|
|
243
|
+
if (priorAlpha <= 0 || priorBeta <= 0) {
|
|
244
|
+
throw new RangeError(`prior parameters must be positive; got α=${priorAlpha} β=${priorBeta}`);
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
alpha: priorAlpha + successes,
|
|
248
|
+
beta: priorBeta + (trials - successes),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Compute a posterior credible interval and point estimate (mean) for a
|
|
254
|
+
* conversion rate given observed successes and trials.
|
|
255
|
+
*
|
|
256
|
+
* Returns the full evidence trail — prior, posterior parameters, mean,
|
|
257
|
+
* mode, and lower/upper bounds of the equal-tailed credible interval — so
|
|
258
|
+
* callers can render exactly the uncertainty they need.
|
|
259
|
+
*
|
|
260
|
+
* @param {object} input
|
|
261
|
+
* @param {number} input.successes
|
|
262
|
+
* @param {number} input.trials
|
|
263
|
+
* @param {number} [input.priorAlpha]
|
|
264
|
+
* @param {number} [input.priorBeta]
|
|
265
|
+
* @param {number} [input.credibleLevel=0.95] — e.g. 0.95 for 95% CI
|
|
266
|
+
* @returns {object}
|
|
267
|
+
*/
|
|
268
|
+
function estimateConversionRate({
|
|
269
|
+
successes,
|
|
270
|
+
trials,
|
|
271
|
+
priorAlpha = DEFAULT_PRIOR_ALPHA,
|
|
272
|
+
priorBeta = DEFAULT_PRIOR_BETA,
|
|
273
|
+
credibleLevel = DEFAULT_CREDIBLE_LEVEL,
|
|
274
|
+
}) {
|
|
275
|
+
if (credibleLevel <= 0 || credibleLevel >= 1) {
|
|
276
|
+
throw new RangeError(`credibleLevel must be in (0, 1); got ${credibleLevel}`);
|
|
277
|
+
}
|
|
278
|
+
const { alpha, beta } = posteriorParameters({ successes, trials, priorAlpha, priorBeta });
|
|
279
|
+
const mean = alpha / (alpha + beta);
|
|
280
|
+
// Mode of Beta(α, β):
|
|
281
|
+
// α > 1 AND β > 1 — single interior mode at (α-1)/(α+β-2)
|
|
282
|
+
// α ≤ 1 < β, OR β ≤ 1 < α — boundary mode at the larger-density end
|
|
283
|
+
// α < 1 AND β < 1 — BIMODAL: density spikes at both 0 and 1
|
|
284
|
+
// (U-shaped), with 0.5 as the antimode.
|
|
285
|
+
// We report the boundary with higher
|
|
286
|
+
// density. Density at 0 is finite when
|
|
287
|
+
// α > 1 and zero when α < 1; at α=β<1
|
|
288
|
+
// the two boundaries are equally peaked
|
|
289
|
+
// so we tie-break to mean side.
|
|
290
|
+
// α == 1 AND β == 1 — flat (uniform); no unique mode, report mean.
|
|
291
|
+
let mode;
|
|
292
|
+
if (alpha > 1 && beta > 1) {
|
|
293
|
+
mode = (alpha - 1) / (alpha + beta - 2);
|
|
294
|
+
} else if (alpha <= 1 && beta > 1) {
|
|
295
|
+
mode = 0;
|
|
296
|
+
} else if (alpha > 1 && beta <= 1) {
|
|
297
|
+
mode = 1;
|
|
298
|
+
} else if (alpha < 1 && beta < 1) {
|
|
299
|
+
// U-shaped Beta. Compare unnormalized densities at the boundaries via
|
|
300
|
+
// the log-density limit; whichever end has higher mass is the dominant
|
|
301
|
+
// mode. For Beta(α, β) with α, β < 1, log f(x) -> +∞ as x -> 0 with
|
|
302
|
+
// exponent -(1-α), and as x -> 1 with exponent -(1-β). Higher 1-α
|
|
303
|
+
// means a sharper spike at 0; higher 1-β means a sharper spike at 1.
|
|
304
|
+
if (1 - alpha > 1 - beta) mode = 0;
|
|
305
|
+
else if (1 - beta > 1 - alpha) mode = 1;
|
|
306
|
+
else mode = mean < 0.5 ? 0 : 1;
|
|
307
|
+
} else {
|
|
308
|
+
// α == 1 AND β == 1 — uniform. Mean is as principled as anything.
|
|
309
|
+
mode = mean;
|
|
310
|
+
}
|
|
311
|
+
const tail = (1 - credibleLevel) / 2;
|
|
312
|
+
const lower = betaQuantile(tail, alpha, beta);
|
|
313
|
+
const upper = betaQuantile(1 - tail, alpha, beta);
|
|
314
|
+
// The "honest" sample size we've effectively committed to claiming.
|
|
315
|
+
const effectiveSampleSize = alpha + beta - priorAlpha - priorBeta;
|
|
316
|
+
return {
|
|
317
|
+
successes,
|
|
318
|
+
trials,
|
|
319
|
+
priorAlpha,
|
|
320
|
+
priorBeta,
|
|
321
|
+
posteriorAlpha: alpha,
|
|
322
|
+
posteriorBeta: beta,
|
|
323
|
+
credibleLevel,
|
|
324
|
+
mean,
|
|
325
|
+
mode,
|
|
326
|
+
lower,
|
|
327
|
+
upper,
|
|
328
|
+
effectiveSampleSize,
|
|
329
|
+
// A human-readable verdict that captures how much to trust this estimate.
|
|
330
|
+
verdict: classifyVerdict({ trials, lower, upper }),
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Classify how trustworthy a posterior estimate is given the data volume
|
|
336
|
+
* and the width of the credible interval. We use three buckets:
|
|
337
|
+
*
|
|
338
|
+
* "insufficient_data" trials < 30 (prior dominates)
|
|
339
|
+
* "wide_uncertainty" interval width > 0.10 (10 percentage points)
|
|
340
|
+
* "credible" interval width <= 0.10
|
|
341
|
+
*
|
|
342
|
+
* The 30-trial cutoff is the conventional rule-of-thumb for binomial
|
|
343
|
+
* estimates to start trusting the empirical mean. The 10pp cutoff is a
|
|
344
|
+
* judgement call — narrower than 10pp is "we could act on this."
|
|
345
|
+
*
|
|
346
|
+
* @param {object} input
|
|
347
|
+
* @param {number} input.trials
|
|
348
|
+
* @param {number} input.lower
|
|
349
|
+
* @param {number} input.upper
|
|
350
|
+
* @returns {"insufficient_data"|"wide_uncertainty"|"credible"}
|
|
351
|
+
*/
|
|
352
|
+
function classifyVerdict({ trials, lower, upper }) {
|
|
353
|
+
if (trials < 30) return 'insufficient_data';
|
|
354
|
+
if (upper - lower > 0.1) return 'wide_uncertainty';
|
|
355
|
+
return 'credible';
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Compute conversion-rate estimates for an array of surfaces, each with
|
|
360
|
+
* its own successes/trials counts. Returns the same array decorated with
|
|
361
|
+
* estimate fields, optionally sorted by lower bound of the credible
|
|
362
|
+
* interval (the "pessimistic ranking" — surfaces ranked by what we're
|
|
363
|
+
* confident they're AT LEAST converting at).
|
|
364
|
+
*
|
|
365
|
+
* Pessimistic ranking is the right default for the bandit case: it
|
|
366
|
+
* prevents allocating traffic to a surface whose point estimate is high
|
|
367
|
+
* but whose lower bound is near zero (i.e. one lucky charge on 2 visitors).
|
|
368
|
+
*
|
|
369
|
+
* @param {Array<{surface: string, successes: number, trials: number}>} surfaces
|
|
370
|
+
* @param {object} [opts]
|
|
371
|
+
* @param {number} [opts.priorAlpha]
|
|
372
|
+
* @param {number} [opts.priorBeta]
|
|
373
|
+
* @param {number} [opts.credibleLevel]
|
|
374
|
+
* @param {"lower"|"mean"|"upper"|"none"} [opts.sortBy="lower"]
|
|
375
|
+
* @returns {Array<object>}
|
|
376
|
+
*/
|
|
377
|
+
function rankSurfaces(surfaces, opts = {}) {
|
|
378
|
+
const { sortBy = 'lower' } = opts;
|
|
379
|
+
const decorated = surfaces.map((row) => ({
|
|
380
|
+
...row,
|
|
381
|
+
estimate: estimateConversionRate({
|
|
382
|
+
successes: row.successes,
|
|
383
|
+
trials: row.trials,
|
|
384
|
+
priorAlpha: opts.priorAlpha,
|
|
385
|
+
priorBeta: opts.priorBeta,
|
|
386
|
+
credibleLevel: opts.credibleLevel,
|
|
387
|
+
}),
|
|
388
|
+
}));
|
|
389
|
+
if (sortBy === 'none') return decorated;
|
|
390
|
+
const key = sortBy === 'mean' || sortBy === 'upper' ? sortBy : 'lower';
|
|
391
|
+
return decorated.sort((a, b) => b.estimate[key] - a.estimate[key]);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Render a markdown summary of conversion-rate estimates suitable for
|
|
396
|
+
* inclusion in the unified revenue rollup.
|
|
397
|
+
*
|
|
398
|
+
* @param {Array<{surface: string, successes: number, trials: number, estimate: object}>} ranked
|
|
399
|
+
* @returns {string}
|
|
400
|
+
*/
|
|
401
|
+
function renderConversionMarkdown(ranked) {
|
|
402
|
+
const lines = [];
|
|
403
|
+
// Pull the credible level from the first ranked row's estimate so the
|
|
404
|
+
// heading and column label reflect what the caller actually requested
|
|
405
|
+
// (instead of hardcoding 95% when, say, a 90% CI was computed).
|
|
406
|
+
const credibleLevel = ranked.length && ranked[0].estimate
|
|
407
|
+
? ranked[0].estimate.credibleLevel
|
|
408
|
+
: DEFAULT_CREDIBLE_LEVEL;
|
|
409
|
+
const ciLabel = `${Math.round(credibleLevel * 100)}% CI`;
|
|
410
|
+
lines.push(`## Per-Surface Conversion (Bayesian beta-binomial, ${ciLabel})`);
|
|
411
|
+
lines.push('');
|
|
412
|
+
if (!ranked.length) {
|
|
413
|
+
lines.push('_No surfaces measured._');
|
|
414
|
+
return lines.join('\n') + '\n';
|
|
415
|
+
}
|
|
416
|
+
lines.push(`| Surface | Trials | Successes | Mean | ${ciLabel} | Verdict |`);
|
|
417
|
+
lines.push('| --- | ---: | ---: | ---: | --- | --- |');
|
|
418
|
+
for (const row of ranked) {
|
|
419
|
+
const est = row.estimate;
|
|
420
|
+
const mean = (est.mean * 100).toFixed(2);
|
|
421
|
+
const lo = (est.lower * 100).toFixed(2);
|
|
422
|
+
const hi = (est.upper * 100).toFixed(2);
|
|
423
|
+
lines.push(`| \`${row.surface}\` | ${row.trials} | ${row.successes} | ${mean}% | [${lo}%, ${hi}%] | ${est.verdict} |`);
|
|
424
|
+
}
|
|
425
|
+
lines.push('');
|
|
426
|
+
lines.push(`Verdicts: \`insufficient_data\` = <30 trials, prior still dominates. \`wide_uncertainty\` = ${ciLabel} wider than 10pp. \`credible\` = narrow enough to act on.`);
|
|
427
|
+
return lines.join('\n') + '\n';
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
module.exports = {
|
|
431
|
+
DEFAULT_PRIOR_ALPHA,
|
|
432
|
+
DEFAULT_PRIOR_BETA,
|
|
433
|
+
DEFAULT_CREDIBLE_LEVEL,
|
|
434
|
+
logGamma,
|
|
435
|
+
regularizedIncompleteBeta,
|
|
436
|
+
betaQuantile,
|
|
437
|
+
posteriorParameters,
|
|
438
|
+
estimateConversionRate,
|
|
439
|
+
classifyVerdict,
|
|
440
|
+
rankSurfaces,
|
|
441
|
+
renderConversionMarkdown,
|
|
442
|
+
};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* cost-cli.js — `thumbgate cost` subcommand.
|
|
5
|
+
*
|
|
6
|
+
* Surfaces the existing computeTokenSavings() output as a human-readable
|
|
7
|
+
* report so users can see, in plain dollars, what their PreToolUse gates
|
|
8
|
+
* are worth. Reads gate-stats.json (same file the dashboard reads) and
|
|
9
|
+
* the lesson DB for context.
|
|
10
|
+
*
|
|
11
|
+
* Positioning answer to the 2026 FinOps-for-AI pitch: ThumbGate isn't
|
|
12
|
+
* a competing FinOps tool — it's the *enforcement* layer that prevents
|
|
13
|
+
* the spend FinOps tools would otherwise just be reporting on.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const fs = require('node:fs');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
const {
|
|
19
|
+
computeTokenSavings,
|
|
20
|
+
formatDollars,
|
|
21
|
+
formatTokens,
|
|
22
|
+
} = require('./token-savings');
|
|
23
|
+
|
|
24
|
+
const DEFAULT_STATS_PATH = path.join(
|
|
25
|
+
process.env.HOME || process.env.USERPROFILE || '/tmp',
|
|
26
|
+
'.thumbgate',
|
|
27
|
+
'gate-stats.json',
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
function readGateStats(statsPath = DEFAULT_STATS_PATH) {
|
|
31
|
+
try {
|
|
32
|
+
if (!fs.existsSync(statsPath)) return null;
|
|
33
|
+
const raw = fs.readFileSync(statsPath, 'utf8');
|
|
34
|
+
const parsed = JSON.parse(raw);
|
|
35
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
36
|
+
} catch (_err) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function summarizeTopGate(byGate) {
|
|
42
|
+
if (!byGate || typeof byGate !== 'object') return null;
|
|
43
|
+
let topId = null;
|
|
44
|
+
let topCount = 0;
|
|
45
|
+
for (const [id, stat] of Object.entries(byGate)) {
|
|
46
|
+
const n = Number(stat && stat.blocked) || 0;
|
|
47
|
+
if (n > topCount) {
|
|
48
|
+
topCount = n;
|
|
49
|
+
topId = id;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return topId ? { id: topId, blocked: topCount } : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function buildReport({ statsPath = DEFAULT_STATS_PATH, modelMix } = {}) {
|
|
56
|
+
// Read once, then use the null vs. parsed-object distinction to derive
|
|
57
|
+
// statsExists — avoids a second filesystem hit per the gitar-bot perf
|
|
58
|
+
// note on PR #2281.
|
|
59
|
+
const raw = readGateStats(statsPath);
|
|
60
|
+
const stats = raw || { blocked: 0, warned: 0, passed: 0, byGate: {} };
|
|
61
|
+
const blockedCalls = Number(stats.blocked) || 0;
|
|
62
|
+
const savings = computeTokenSavings({
|
|
63
|
+
blockedCalls,
|
|
64
|
+
modelMix,
|
|
65
|
+
});
|
|
66
|
+
return {
|
|
67
|
+
statsPath,
|
|
68
|
+
statsExists: raw !== null,
|
|
69
|
+
blocked: blockedCalls,
|
|
70
|
+
warned: Number(stats.warned) || 0,
|
|
71
|
+
passed: Number(stats.passed) || 0,
|
|
72
|
+
topGate: summarizeTopGate(stats.byGate),
|
|
73
|
+
savings,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function renderHuman(report) {
|
|
78
|
+
const out = [];
|
|
79
|
+
out.push('');
|
|
80
|
+
out.push('💰 ThumbGate cost-savings — cumulative');
|
|
81
|
+
out.push('─'.repeat(50));
|
|
82
|
+
|
|
83
|
+
if (!report.statsExists) {
|
|
84
|
+
out.push('');
|
|
85
|
+
out.push(` No gate-stats.json yet at ${report.statsPath}.`);
|
|
86
|
+
out.push(' ThumbGate writes it the first time a PreToolUse gate fires.');
|
|
87
|
+
out.push(' Run `thumbgate init` if you haven\'t installed the hook,');
|
|
88
|
+
out.push(' or wait until your first agent session triggers a block.');
|
|
89
|
+
out.push('');
|
|
90
|
+
return out.join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
out.push('');
|
|
94
|
+
out.push(` Tool calls blocked : ${report.blocked.toLocaleString()}`);
|
|
95
|
+
out.push(` Tool calls warned : ${report.warned.toLocaleString()}`);
|
|
96
|
+
out.push(` Tool calls passed : ${report.passed.toLocaleString()}`);
|
|
97
|
+
if (report.topGate) {
|
|
98
|
+
out.push(` Top blocker : ${report.topGate.id} (${report.topGate.blocked} blocks)`);
|
|
99
|
+
}
|
|
100
|
+
out.push('');
|
|
101
|
+
out.push(' Tokens you did NOT spend');
|
|
102
|
+
out.push(` Input : ${formatTokens(report.savings.tokensSavedInput)}`);
|
|
103
|
+
out.push(` Output : ${formatTokens(report.savings.tokensSavedOutput)}`);
|
|
104
|
+
out.push(` Total : ${formatTokens(report.savings.tokensSavedTotal)}`);
|
|
105
|
+
out.push('');
|
|
106
|
+
out.push(` Estimated $ saved : ${formatDollars(report.savings.dollarsSaved)}`);
|
|
107
|
+
out.push('');
|
|
108
|
+
out.push(
|
|
109
|
+
' Methodology: conservative, 2k input + 600 output tokens per blocked call,',
|
|
110
|
+
);
|
|
111
|
+
out.push(
|
|
112
|
+
' Sonnet-heavy mix (80/15/5). Override with `--mix` JSON flag.',
|
|
113
|
+
);
|
|
114
|
+
out.push('');
|
|
115
|
+
return out.join('\n');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function parseArgs(argv) {
|
|
119
|
+
const args = { json: false, statsPath: undefined, modelMix: undefined };
|
|
120
|
+
for (let i = 0; i < argv.length; i++) {
|
|
121
|
+
const a = argv[i];
|
|
122
|
+
if (a === '--json') args.json = true;
|
|
123
|
+
else if (a === '--stats' || a === '--stats-path') args.statsPath = argv[++i];
|
|
124
|
+
else if (a === '--mix') {
|
|
125
|
+
try { args.modelMix = JSON.parse(argv[++i]); }
|
|
126
|
+
catch { args.modelMix = undefined; }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return args;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function main(argv = process.argv.slice(2)) {
|
|
133
|
+
const args = parseArgs(argv);
|
|
134
|
+
const report = buildReport({ statsPath: args.statsPath, modelMix: args.modelMix });
|
|
135
|
+
if (args.json) {
|
|
136
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
process.stdout.write(renderHuman(report));
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (path.resolve(process.argv[1] || '') === path.resolve(__filename)) {
|
|
144
|
+
process.exit(main());
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = { buildReport, renderHuman, readGateStats, parseArgs, main };
|