thumbgate 1.40.3 → 1.40.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/comet-session-logger/SKILL.md +8 -5
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +7 -2
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- 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 +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/config/github-about.json +1 -1
- package/config/post-deploy-marketing-pages.json +1 -1
- package/package.json +35 -7
- package/public/about.html +2 -2
- package/public/admin.html +546 -50
- package/public/case-studies.html +1 -0
- package/public/dashboard.html +7 -6
- package/public/diagnostic.html +15 -12
- package/public/index.html +210 -88
- package/public/install.html +9 -8
- package/public/js/connect-panel.js +437 -0
- package/public/learn.html +8 -0
- package/public/numbers.html +2 -2
- package/public/preview.html +42 -0
- package/public/pricing.html +55 -10
- package/public/support.html +1 -1
- package/public/terms.html +1 -1
- package/scripts/auto-promote-gates.js +29 -4
- package/scripts/billing.js +189 -4
- package/scripts/cap-hit-counter.js +47 -0
- package/scripts/checkout-human-gate.js +248 -0
- package/scripts/checkout-session-count.js +119 -0
- package/scripts/claude-feedback-sync.js +4 -2
- package/scripts/feedback-loop.js +41 -5
- package/scripts/first-block-upsell.js +187 -0
- package/scripts/gates-engine.js +37 -108
- package/scripts/human-feedback.js +20 -1
- package/scripts/ops-log.js +91 -0
- package/scripts/ops-report.js +174 -0
- package/scripts/owner-admin.js +508 -27
- package/scripts/owner-telemetry.js +151 -0
- package/scripts/rate-limiter.js +8 -2
- package/scripts/statusline-human-counts.js +71 -8
- package/scripts/statusline.sh +15 -2
- package/scripts/telemetry-analytics.js +4 -0
- package/scripts/tool-contract-validator.js +13 -3
- package/scripts/tool-registry.js +1 -1
- package/scripts/utm-source-summary.js +88 -0
- package/server.json +2 -2
- package/skills/comet-session-logger/SKILL.md +8 -5
- package/src/api/server.js +649 -107
- package/src/mcp/email-triage-server/index.js +92 -14
package/public/pricing.html
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
6
|
<title>Pricing — ThumbGate Pro | ThumbGate</title>
|
|
7
|
-
<meta name="description" content="Free local capture and
|
|
7
|
+
<meta name="description" content="Free local capture and PreToolUse gates for Claude Code. Choose Pro for recall, dashboard, and exports.">
|
|
8
8
|
<link rel="canonical" href="__APP_ORIGIN__/pricing">
|
|
9
9
|
<link rel="alternate" type="text/markdown" title="ThumbGate LLM context" href="__APP_ORIGIN__/llm-context.md">
|
|
10
10
|
<meta property="og:title" content="ThumbGate Pricing — ThumbGate Pro">
|
|
11
|
-
<meta property="og:description" content="Free local capture and
|
|
12
|
-
<meta name="twitter:description" content="Free local capture and
|
|
11
|
+
<meta property="og:description" content="Free local capture and PreToolUse gates for Claude Code. Choose Pro for recall, dashboard, and exports.">
|
|
12
|
+
<meta name="twitter:description" content="Free local capture and PreToolUse gates for Claude Code. Choose Pro for recall, dashboard, and exports.">
|
|
13
13
|
<meta property="og:url" content="__APP_ORIGIN__/pricing">
|
|
14
14
|
<meta property="og:type" content="product">
|
|
15
15
|
<script type="application/ld+json">
|
|
@@ -51,6 +51,10 @@
|
|
|
51
51
|
@media (max-width:900px) { .offer-grid { grid-template-columns:1fr; } }
|
|
52
52
|
.eyebrow { color:var(--green); font-size:.76rem; font-weight:850; letter-spacing:.14em; text-transform:uppercase; }
|
|
53
53
|
h1 { max-width:760px; margin:14px 0 18px; font-size:clamp(2.5rem,6vw,5.15rem); line-height:.96; letter-spacing:-.055em; }
|
|
54
|
+
.audience { max-width:660px; margin:0 0 14px; color:var(--ink); font-size:1.05rem; }
|
|
55
|
+
.gate-demo { margin:0 0 8px; max-width:100%; }
|
|
56
|
+
.gate-demo video { display:block; width:100%; height:auto; aspect-ratio:960 / 722; border:1px solid var(--line); border-radius:14px; background:#090d14; }
|
|
57
|
+
.gate-demo figcaption { margin-top:10px; color:var(--muted); font-size:.86rem; line-height:1.45; }
|
|
54
58
|
.lede { max-width:660px; margin:0 0 28px; color:var(--muted); font-size:1.13rem; }
|
|
55
59
|
.outcome { display:grid; gap:12px; margin-top:34px; }
|
|
56
60
|
.outcome-row { display:flex; gap:13px; align-items:flex-start; }
|
|
@@ -64,6 +68,9 @@
|
|
|
64
68
|
.fine { margin:12px 0 0; color:var(--muted); font-size:.79rem; }
|
|
65
69
|
.boundary { margin-top:18px; padding:14px 16px; border-left:4px solid var(--red); background:#fff5f2; color:#63332d; font-size:.9rem; }
|
|
66
70
|
section { padding-top:76px; }
|
|
71
|
+
table.compare { width:100%; border-collapse:collapse; margin:16px 0; font-size:.95rem; }
|
|
72
|
+
table.compare th, table.compare td { border:1px solid var(--line, rgba(128,128,128,.35)); padding:10px 12px; text-align:left; vertical-align:top; }
|
|
73
|
+
table.compare caption { text-align:left; color:var(--muted, #6b7280); padding-bottom:6px; }
|
|
67
74
|
h2 { margin:0 0 14px; font-size:clamp(1.8rem,3.5vw,2.8rem); letter-spacing:-.035em; }
|
|
68
75
|
.section-lede { max-width:680px; color:var(--muted); }
|
|
69
76
|
.steps { display:grid; grid-template-columns:repeat(3,1fr); gap:14px; margin-top:28px; }
|
|
@@ -115,6 +122,7 @@
|
|
|
115
122
|
<meta http-equiv="origin-trial" content="A06wj3yXAwOhT5Cd5WYdVQotlYa/OID3SW099ZQB+cs9eHeJmtH1yHudLwqDKZ7y43tQvLB4TfM/pjmUa7aJNQsAAAB4eyJvcmlnaW4iOiJodHRwczovL3d3dy50aHVtYmdhdGUuYXBwOjQ0MyIsImZlYXR1cmUiOiJXZWJNQ1AiLCJleHBpcnkiOjE4MDYzNjQ4MDAsImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9" />
|
|
116
123
|
<script src="/js/webmcp.js" defer></script>
|
|
117
124
|
<script src="/js/buyer-intent.js" defer></script>
|
|
125
|
+
<script src="/js/connect-panel.js" defer></script>
|
|
118
126
|
</head>
|
|
119
127
|
<body>
|
|
120
128
|
<nav>
|
|
@@ -137,31 +145,61 @@
|
|
|
137
145
|
<main class="shell">
|
|
138
146
|
<div class="hero">
|
|
139
147
|
<div>
|
|
140
|
-
<div class="eyebrow">Free local gates
|
|
141
|
-
<h1>
|
|
142
|
-
<p class="
|
|
148
|
+
<div class="eyebrow">Claude Code guardrails. Free local gates, optional Pro.</div>
|
|
149
|
+
<h1>Get warned before Claude Code repeats a mistake you already paid for.</h1>
|
|
150
|
+
<p class="audience" id="pricing-audience"><strong>Who it's for:</strong> Claude Code users whose agent has already broken something once. The local CLI is free and stays free.</p>
|
|
151
|
+
<p class="lede">Free local gates for Claude Code, or self-serve Pro. Choose the plan that fits your workflow.</p>
|
|
152
|
+
|
|
153
|
+
<figure class="gate-demo" id="gate-demo">
|
|
154
|
+
<video id="gate-demo-video" width="960" height="722" controls autoplay muted loop playsinline preload="auto" poster="/media/thumbgate-gate-demo-poster.jpg" aria-label="Recording: Claude Code deletes a folder, gets thumbs-down three times, and the fourth session is blocked by the gate">
|
|
155
|
+
<source src="/media/thumbgate-gate-demo.mp4" type="video/mp4">
|
|
156
|
+
</video>
|
|
157
|
+
<figcaption>Real 58-second run with <code>THUMBGATE_STRICT_ENFORCEMENT=1</code>: three thumbs-downs, then the fourth attempt is denied. A reworded delete is not caught. <a href="https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/demo/gate-demo/README.md" target="_blank" rel="noopener">How it was recorded</a>.</figcaption>
|
|
158
|
+
</figure>
|
|
143
159
|
|
|
144
160
|
<div class="outcome">
|
|
145
|
-
<div class="outcome-row"><span class="tick">✓</span><span>Pro: recall, dashboard,
|
|
146
|
-
<div class="outcome-row"><span class="tick">✓</span><span><strong>Free local evaluate:</strong> <code>npx thumbgate init</code
|
|
161
|
+
<div class="outcome-row"><span class="tick">✓</span><span>Pro: Claude Code recall, dashboard, and exports.</span></div>
|
|
162
|
+
<div class="outcome-row"><span class="tick">✓</span><span><strong>Free local evaluate:</strong> <code>npx thumbgate init</code>. Secret leaks and catastrophic commands (force-push, reset --hard, rm -rf on home or root, DROP TABLE) are denied from the start; other flagged actions warn.</span></div>
|
|
147
163
|
<div class="outcome-row"><span class="tick">✓</span><span>Team and enterprise subscriptions are not available through self-serve checkout. Compare the free CLI and individual Pro software features before choosing.</span></div>
|
|
148
164
|
</div>
|
|
149
165
|
</div>
|
|
150
166
|
|
|
167
|
+
<div id="connect-panel" aria-label="Connect ThumbGate to your agent"></div>
|
|
168
|
+
|
|
151
169
|
<div class="offer-grid" id="buy">
|
|
152
170
|
<aside id="enterprise-gate" class="card pro-card" data-primary-checkout>
|
|
153
171
|
<h2>ThumbGate Pro</h2>
|
|
154
172
|
<div class="price">$__PRO_PRICE_DOLLARS__<span>/month</span></div>
|
|
155
173
|
<p>__PRO_PRICE_LABEL__</p>
|
|
156
|
-
<p>Pro adds recall, dashboard,
|
|
174
|
+
<p>Pro adds recall, dashboard, and exports for Claude Code. The free local CLI includes local capture and PreToolUse gates.</p>
|
|
157
175
|
<a class="button button-primary" href="/checkout/pro" data-offer-link data-value="__PRO_PRICE_DOLLARS__" data-revenue-cta data-cta-id="pricing_pro_checkout" data-cta-placement="offers" data-plan-id="pro">Get Pro</a>
|
|
176
|
+
<p class="annual-option" id="pro-annual">Or pay yearly: <strong>$149/year</strong> (about $12.42/month, saves $79 against twelve monthly payments). <a href="/checkout/pro?billing_cycle=annual" data-offer-link data-value="149" data-revenue-cta data-cta-id="pricing_pro_annual_checkout" data-cta-placement="offers" data-plan-id="pro_annual">Get Pro yearly</a></p>
|
|
158
177
|
<p><a href="/install">Start with the free CLI</a></p>
|
|
159
178
|
</aside>
|
|
160
179
|
</div>
|
|
161
180
|
</div>
|
|
162
181
|
|
|
182
|
+
<section id="free-vs-pro"><h2>Free vs Pro</h2>
|
|
183
|
+
<p>Strict blocking of catastrophic commands is free. Pro is about memory.</p>
|
|
184
|
+
<table class="compare">
|
|
185
|
+
<caption>Free and Pro, from the license checks in the code</caption>
|
|
186
|
+
<thead><tr><th>Feature</th><th>Free</th><th>Pro</th></tr></thead>
|
|
187
|
+
<tbody>
|
|
188
|
+
<tr><th>Blocked by default: force-push, <code>git reset --hard</code>, <code>git clean -f</code>, <code>rm -rf</code> on home or root, <code>DROP TABLE</code></th><td>Yes</td><td>Yes</td></tr>
|
|
189
|
+
<tr><th>Gate blocks per day (strict mode)</th><td>Unlimited</td><td>Unlimited</td></tr>
|
|
190
|
+
<tr><th>Learned rules from your thumbs-down that stay active (warn; block in strict mode)</th><td>3</td><td>All</td></tr>
|
|
191
|
+
<tr><th>Recall of past lessons</th><td>No</td><td>Yes</td></tr>
|
|
192
|
+
<tr><th>Lesson search</th><td>No</td><td>Yes</td></tr>
|
|
193
|
+
<tr><th>Multi-hop recall, synthetic DPO pairs</th><td>No</td><td>Yes</td></tr>
|
|
194
|
+
<tr><th>Team-shared rules</th><td>Coming</td><td>Coming</td></tr>
|
|
195
|
+
<tr><th>Lessons synced across machines</th><td>Coming</td><td>Coming</td></tr>
|
|
196
|
+
<tr><th>Audit history for managers</th><td>Coming</td><td>Coming</td></tr>
|
|
197
|
+
</tbody>
|
|
198
|
+
</table>
|
|
199
|
+
</section>
|
|
200
|
+
|
|
163
201
|
<section id="value"><h2>Free local protection. Pro recall.</h2>
|
|
164
|
-
<p>Install the
|
|
202
|
+
<p>Install the Claude Code plugin, then run <code>npx thumbgate init --agent claude</code>. Upgrade when you need recall, dashboard, and exports.</p>
|
|
165
203
|
<p>Pro: __PRO_PRICE_LABEL__. <a href="/checkout/pro">Get Pro</a>.</p>
|
|
166
204
|
<p><a href="https://github.com/IgorGanapolsky/ThumbGate/blob/main/docs/VERIFICATION_EVIDENCE.md">Read verification evidence</a>.</p>
|
|
167
205
|
<p>Shared hosting, SSO, compliance packaging, and organization-wide rollout are not generally available.</p>
|
|
@@ -173,6 +211,13 @@
|
|
|
173
211
|
<span>ThumbGate · Local AI-agent gates</span>
|
|
174
212
|
<div class="footer-links"><a href="/support">Support</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/third-party-notices">Third-Party Notices</a><a href="/llm-context.md">LLM context</a><a href="/dashboard">Subscriber login</a><a href="/portal">Billing portal</a></div>
|
|
175
213
|
</div>
|
|
214
|
+
<div class="shell" data-also-by-igor style="margin-top:12px;font-size:14px;">
|
|
215
|
+
<strong>Also by Igor</strong>
|
|
216
|
+
<ul style="list-style:none;margin:6px 0 0;padding:0;">
|
|
217
|
+
<li><a href="https://macyolosafeguards.io/?utm_source=thumbgate" rel="noopener">Mac YOLO Safeguards</a>: Free menu bar app that cleans up what coding agents leave running on your Mac.</li>
|
|
218
|
+
<li><a href="https://dayglass.io/?utm_source=thumbgate" rel="noopener">Dayglass</a>: Private AI memory for your Mac calls and work, no meeting bot.</li>
|
|
219
|
+
</ul>
|
|
220
|
+
</div>
|
|
176
221
|
<div class="shell" style="margin-top:12px;font-size:12px;color:#6b7280;text-align:center;">
|
|
177
222
|
Anthropic, Claude, OpenAI, ChatGPT, Cursor, Codex, Perplexity, Hermes, MCP, GitHub, Google, Nvidia, Railway, Stripe, Supabase, PostHog, and Plausible are trademarks of their respective owners. ThumbGate is an independent product.
|
|
178
223
|
</div>
|
package/public/support.html
CHANGED
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
</ul>
|
|
50
50
|
</div>
|
|
51
51
|
<h2>Refunds</h2>
|
|
52
|
-
<p>Pro subscription refunds follow the <a href="/terms">Terms of Service</a>. Self-serve Pro: new paid subscribers may request a refund within <strong>7
|
|
52
|
+
<p>Pro subscription refunds follow the <a href="/terms">Terms of Service</a>. Self-serve Pro: new paid subscribers may request a refund within <strong>7 days</strong> of the initial charge if the product is unusable because of a documented platform defect we cannot remediate; after that, renewals are non-refundable except as required by law. Managed $499 Workflow Gate refunds are defined in Terms (refunded in full only when discovery shows the workflow cannot be reduced to a supported gate, subject to any disclosed diagnostic fee).</p>
|
|
53
53
|
<h2>Status</h2>
|
|
54
54
|
<p>API health: <a href="https://thumbgate-production.up.railway.app/health">/health</a>. Open-source issues: <a href="https://github.com/IgorGanapolsky/ThumbGate/issues">GitHub Issues</a>.</p>
|
|
55
55
|
<h2>Security</h2>
|
package/public/terms.html
CHANGED
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
<p>Free tiers, open-source local binaries, and promotional trials are provided strictly "AS-IS" without SLA, indemnification, or support obligations.</p>
|
|
71
71
|
|
|
72
72
|
<h3>2.4 Refunds</h3>
|
|
73
|
-
<p>
|
|
73
|
+
<p>A new self-serve Pro subscriber may request a refund within <strong>7 days</strong> of the initial charge if the product is unusable because of a documented platform defect we cannot remediate. After that, recurring subscription fees are non-refundable except as required by law. The <strong>$499 Workflow Gate</strong> is refundable only if technical discovery determines that your workflow cannot be reduced to a supported ThumbGate gate, subject to a non-refundable diagnostic fee as described in Section 3.</p>
|
|
74
74
|
|
|
75
75
|
<h3>2.5 Acceptable Use Policy (AUP)</h3>
|
|
76
76
|
<p>You shall NOT use the Services to violate law, tamper with third-party security, reverse-engineer proprietary cloud components, submit malicious payloads, or conduct unauthorized scraping or spam.</p>
|
|
@@ -7,7 +7,15 @@ const fs = require('fs');
|
|
|
7
7
|
const path = require('path');
|
|
8
8
|
const { resolveFeedbackDir } = require('./feedback-paths');
|
|
9
9
|
|
|
10
|
+
// Free keeps at most this many learned rules on disk (and enforces the first FREE_TIER_MAX_GATES of them). Pro is not capped:
|
|
11
|
+
// the site promises Pro keeps every learned rule active. Stale rules still expire after the rule TTL, which bounds the file.
|
|
10
12
|
const MAX_AUTO_GATES = 10;
|
|
13
|
+
|
|
14
|
+
// The most auto-promoted gates to keep for this caller. `options.isPro` (boolean or function) lets a test pick the tier.
|
|
15
|
+
function autoGateLimit(options = {}) {
|
|
16
|
+
const pro = typeof options.isPro === 'function' ? options.isPro() : typeof options.isPro === 'boolean' ? options.isPro : require('./rate-limiter').isProTier();
|
|
17
|
+
return pro ? Infinity : MAX_AUTO_GATES;
|
|
18
|
+
}
|
|
11
19
|
// 1+ failure auto-promotes to a warning gate. Cold buyers expect "one 👎 → blocked next time"
|
|
12
20
|
// — a 2-capture threshold made first-capture invisible and broke the activation loop. Block
|
|
13
21
|
// escalation still requires 3 captures (BLOCK_THRESHOLD) so noise doesn't auto-hard-block.
|
|
@@ -573,8 +581,9 @@ function forcePromote(context, action = 'block', options = {}) {
|
|
|
573
581
|
data.gates = data.gates.filter((existing) => existing.id !== gateId || existing.projectKey !== project.projectKey);
|
|
574
582
|
data.gates.unshift(gate);
|
|
575
583
|
|
|
576
|
-
|
|
577
|
-
|
|
584
|
+
const keepLimit = autoGateLimit(options);
|
|
585
|
+
if (data.gates.length > keepLimit) {
|
|
586
|
+
data.gates = data.gates.slice(0, keepLimit);
|
|
578
587
|
}
|
|
579
588
|
|
|
580
589
|
data.promotionLog = data.promotionLog || [];
|
|
@@ -625,6 +634,7 @@ function promote(feedbackLogPath, options) {
|
|
|
625
634
|
...inertRemoved.map((e) => ({ type: 'quarantined-inert-prose', gateId: e.id, pattern: e.pattern })),
|
|
626
635
|
];
|
|
627
636
|
|
|
637
|
+
let upgradeLine;
|
|
628
638
|
for (const group of Object.values(groups)) {
|
|
629
639
|
if (group.count < WARN_THRESHOLD) continue;
|
|
630
640
|
|
|
@@ -659,6 +669,10 @@ function promote(feedbackLogPath, options) {
|
|
|
659
669
|
}
|
|
660
670
|
// Update occurrence count even if no action change
|
|
661
671
|
data.gates[existingIdx].occurrences = group.count;
|
|
672
|
+
// The deny text quotes the count; keep it in step so a block does not say "1 occurrences".
|
|
673
|
+
if (String(data.gates[existingIdx].message || '').startsWith('Auto-promoted ')) {
|
|
674
|
+
data.gates[existingIdx].message = buildGateRule(group, data.gates[existingIdx].action).message;
|
|
675
|
+
}
|
|
662
676
|
continue;
|
|
663
677
|
}
|
|
664
678
|
|
|
@@ -704,7 +718,7 @@ function promote(feedbackLogPath, options) {
|
|
|
704
718
|
}
|
|
705
719
|
|
|
706
720
|
// Enforce max limit — rotate oldest
|
|
707
|
-
if (data.gates.length >=
|
|
721
|
+
if (data.gates.length >= autoGateLimit(opts)) {
|
|
708
722
|
const removed = data.gates.shift();
|
|
709
723
|
promotions.push({ type: 'rotated', removedGateId: removed.id });
|
|
710
724
|
}
|
|
@@ -717,6 +731,16 @@ function promote(feedbackLogPath, options) {
|
|
|
717
731
|
occurrences: group.count,
|
|
718
732
|
...(gate.quarantined ? { falseBlocks: regression.falseBlocks, allowSampleSize: regression.allowSampleSize } : {}),
|
|
719
733
|
});
|
|
734
|
+
|
|
735
|
+
// Free tier enforces only the first FREE_TIER_MAX_GATES learned rules (see gates-engine
|
|
736
|
+
// loadGates). A rule past that is stored but not enforced: count it and say so once.
|
|
737
|
+
const rateLimiter = require('./rate-limiter');
|
|
738
|
+
if (data.gates.length > rateLimiter.FREE_TIER_MAX_GATES && !rateLimiter.isProTier()) {
|
|
739
|
+
const line = rateLimiter.capUpgradeLine(group.latestContext || gate.id);
|
|
740
|
+
promotions.push({ type: 'cap-hit', gateId: gate.id, enforced: false, cap: rateLimiter.FREE_TIER_MAX_GATES, activeGates: data.gates.length });
|
|
741
|
+
require('./cap-hit-counter').recordCapHit({ feedbackDir: opts.feedbackDir, cap: rateLimiter.FREE_TIER_MAX_GATES, activeGates: data.gates.length });
|
|
742
|
+
if (line) upgradeLine = line;
|
|
743
|
+
}
|
|
720
744
|
}
|
|
721
745
|
|
|
722
746
|
// Log promotions
|
|
@@ -727,7 +751,7 @@ function promote(feedbackLogPath, options) {
|
|
|
727
751
|
|
|
728
752
|
saveAutoGates(data, opts);
|
|
729
753
|
|
|
730
|
-
return { promotions, totalGates: data.gates.length, data };
|
|
754
|
+
return { promotions, totalGates: data.gates.length, data, ...(upgradeLine ? { upgradeLine } : {}) };
|
|
731
755
|
}
|
|
732
756
|
|
|
733
757
|
function runCli(argv = process.argv.slice(2)) {
|
|
@@ -793,6 +817,7 @@ module.exports = {
|
|
|
793
817
|
getRuleTtlDays,
|
|
794
818
|
getRuleTtlMs,
|
|
795
819
|
MAX_AUTO_GATES,
|
|
820
|
+
autoGateLimit,
|
|
796
821
|
WARN_THRESHOLD,
|
|
797
822
|
BLOCK_THRESHOLD,
|
|
798
823
|
WINDOW_DAYS,
|
package/scripts/billing.js
CHANGED
|
@@ -155,6 +155,11 @@ function getStripeConstructor() {
|
|
|
155
155
|
}
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
// Test seam: lets tests inject a fake Stripe client (null restores the real one).
|
|
159
|
+
function setStripeClientForTests(client) {
|
|
160
|
+
_stripeClient = client || null;
|
|
161
|
+
}
|
|
162
|
+
|
|
158
163
|
function getStripeClient() {
|
|
159
164
|
if (!_stripeClient) {
|
|
160
165
|
if (!CONFIG.STRIPE_SECRET_KEY) {
|
|
@@ -2412,6 +2417,144 @@ async function listStripeReconciledRevenueEvents({ signal, deadline = Infinity }
|
|
|
2412
2417
|
return result(reconciled, diagnostics.complete ? 'ok' : 'partial');
|
|
2413
2418
|
}
|
|
2414
2419
|
|
|
2420
|
+
// How far a Stripe Checkout session got. A raw session (nobody typed an email,
|
|
2421
|
+
// no payment attempt) is what crawlers and probes create, so it is not a
|
|
2422
|
+
// qualified checkout start.
|
|
2423
|
+
function classifyCheckoutSessionDepth(session) {
|
|
2424
|
+
if (!session || typeof session !== 'object') return 'raw';
|
|
2425
|
+
if (session.payment_status === 'paid' || session.status === 'complete') return 'paid';
|
|
2426
|
+
if (normalizeText(session.payment_intent) || normalizeText(session.setup_intent)) return 'payment_attempt';
|
|
2427
|
+
const email = normalizeText(session.customer_details?.email) || normalizeText(session.customer_email);
|
|
2428
|
+
if (email && !isSyntheticOrOwnerCheckoutEmail(email)) return 'identified';
|
|
2429
|
+
return 'raw';
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
const CHECKOUT_DEPTH_CACHE_MS = 5 * 60 * 1000;
|
|
2433
|
+
const CHECKOUT_DEPTH_PARTIAL_CACHE_MS = 60 * 1000;
|
|
2434
|
+
const CHECKOUT_DEPTH_LOOKBACK_SECONDS = 35 * 24 * 60 * 60;
|
|
2435
|
+
let checkoutDepthCache = null;
|
|
2436
|
+
|
|
2437
|
+
async function listStripeCheckoutSessionDepth({
|
|
2438
|
+
signal, deadline = Date.now() + 6000, stripeClient = null, maxPages = 12, nowMs = Date.now(),
|
|
2439
|
+
} = {}) {
|
|
2440
|
+
const empty = (status) => ({ status, complete: false, byId: {} });
|
|
2441
|
+
if (!stripeClient && !CONFIG.STRIPE_SECRET_KEY) return empty('unconfigured');
|
|
2442
|
+
const sinceEpochSeconds = Math.floor(nowMs / 1000) - CHECKOUT_DEPTH_LOOKBACK_SECONDS;
|
|
2443
|
+
if (!stripeClient && checkoutDepthCache && nowMs < checkoutDepthCache.expiresAt) return checkoutDepthCache.value;
|
|
2444
|
+
let stripe = stripeClient;
|
|
2445
|
+
if (!stripe) {
|
|
2446
|
+
try {
|
|
2447
|
+
stripe = getStripeClient();
|
|
2448
|
+
} catch {
|
|
2449
|
+
return empty('unavailable');
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
const byId = {};
|
|
2453
|
+
let complete = true;
|
|
2454
|
+
let startingAfter = null;
|
|
2455
|
+
try {
|
|
2456
|
+
for (let page = 0; page < maxPages; page += 1) {
|
|
2457
|
+
if (signal?.aborted || Date.now() >= deadline) { complete = false; break; }
|
|
2458
|
+
const timeout = Math.max(1, Math.min(8000, deadline - Date.now()));
|
|
2459
|
+
const params = { limit: 100, created: { gte: sinceEpochSeconds } };
|
|
2460
|
+
if (startingAfter) params.starting_after = startingAfter;
|
|
2461
|
+
const listed = await withTimeout(withStripeReadSlot(
|
|
2462
|
+
() => stripe.checkout.sessions.list(params, { timeout, maxNetworkRetries: 0 }),
|
|
2463
|
+
{ signal }
|
|
2464
|
+
), timeout);
|
|
2465
|
+
const rows = Array.isArray(listed?.data) ? listed.data : [];
|
|
2466
|
+
for (const row of rows) {
|
|
2467
|
+
if (row?.id) byId[row.id] = classifyCheckoutSessionDepth(row);
|
|
2468
|
+
}
|
|
2469
|
+
if (!listed?.has_more || rows.length === 0) break;
|
|
2470
|
+
startingAfter = rows[rows.length - 1].id;
|
|
2471
|
+
if (page === maxPages - 1) complete = false;
|
|
2472
|
+
}
|
|
2473
|
+
} catch {
|
|
2474
|
+
complete = false;
|
|
2475
|
+
}
|
|
2476
|
+
const value = { status: complete ? 'ok' : 'partial', complete, byId };
|
|
2477
|
+
if (!stripeClient) {
|
|
2478
|
+
checkoutDepthCache = {
|
|
2479
|
+
value,
|
|
2480
|
+
expiresAt: nowMs + (complete ? CHECKOUT_DEPTH_CACHE_MS : CHECKOUT_DEPTH_PARTIAL_CACHE_MS),
|
|
2481
|
+
};
|
|
2482
|
+
}
|
|
2483
|
+
return value;
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
// Counts the window's checkout_session_created rows by how far each Stripe
|
|
2487
|
+
// session got. Only when every session was found does it replace the
|
|
2488
|
+
// telemetry-based count of qualified checkout starts.
|
|
2489
|
+
function summarizeCheckoutSessionDepth(acquisitionEvents = [], depthLookup = null) {
|
|
2490
|
+
const counts = { raw: 0, identified: 0, payment_attempt: 0, paid: 0 };
|
|
2491
|
+
const byId = depthLookup && typeof depthLookup.byId === 'object' ? depthLookup.byId : null;
|
|
2492
|
+
let sessionsCreated = 0;
|
|
2493
|
+
let unresolved = 0;
|
|
2494
|
+
for (const entry of acquisitionEvents) {
|
|
2495
|
+
if (!entry || entry.event !== 'checkout_session_created') continue;
|
|
2496
|
+
sessionsCreated += 1;
|
|
2497
|
+
const depth = byId ? byId[normalizeText(entry.evidence)] : null;
|
|
2498
|
+
if (depth && Object.hasOwn(counts, depth)) counts[depth] += 1;
|
|
2499
|
+
else unresolved += 1;
|
|
2500
|
+
}
|
|
2501
|
+
const available = Boolean(byId) && unresolved === 0;
|
|
2502
|
+
return {
|
|
2503
|
+
basis: available ? 'stripe_session_lookup' : 'telemetry_heuristic',
|
|
2504
|
+
lookupStatus: depthLookup?.status || 'not_requested',
|
|
2505
|
+
sessionsCreated,
|
|
2506
|
+
raw: counts.raw,
|
|
2507
|
+
identified: counts.identified,
|
|
2508
|
+
paymentAttempt: counts.payment_attempt,
|
|
2509
|
+
paid: counts.paid,
|
|
2510
|
+
unresolved,
|
|
2511
|
+
qualifiedCheckoutStarts: counts.identified + counts.payment_attempt + counts.paid,
|
|
2512
|
+
};
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
// Read-only check that a /success visit carries a real, paid Checkout session.
|
|
2516
|
+
// Bots, probes and our own agents can GET /success with any query string, so a
|
|
2517
|
+
// visit only counts when Stripe says the session id is paid.
|
|
2518
|
+
const SUCCESS_VERIFY_CACHE_MS = 5 * 60 * 1000;
|
|
2519
|
+
const SUCCESS_VERIFY_FAIL_CACHE_MS = 60 * 1000;
|
|
2520
|
+
const SUCCESS_VERIFY_CACHE_MAX = 500;
|
|
2521
|
+
const successVerifyCache = new Map();
|
|
2522
|
+
|
|
2523
|
+
async function verifyPaidCheckoutSession(sessionId, { stripeClient = null } = {}) {
|
|
2524
|
+
const id = normalizeText(sessionId);
|
|
2525
|
+
if (!id) return { verified: false, reason: 'missing_session_id' };
|
|
2526
|
+
if (!/^cs_(?:live|test)_[A-Za-z0-9]{8,}$/.test(id)) return { verified: false, reason: 'malformed_session_id' };
|
|
2527
|
+
const cached = !stripeClient ? successVerifyCache.get(id) : null;
|
|
2528
|
+
if (cached && Date.now() < cached.expiresAt) return cached.result;
|
|
2529
|
+
let session = null;
|
|
2530
|
+
let result;
|
|
2531
|
+
try {
|
|
2532
|
+
if (!stripeClient && LOCAL_MODE()) {
|
|
2533
|
+
session = loadLocalCheckoutSessions().sessions[id] || null;
|
|
2534
|
+
} else {
|
|
2535
|
+
const stripe = stripeClient || getStripeClient();
|
|
2536
|
+
session = await withTimeout(withStripeReadSlot(() => stripe.checkout.sessions.retrieve(id)));
|
|
2537
|
+
}
|
|
2538
|
+
if (!session) {
|
|
2539
|
+
result = { verified: false, reason: 'unknown_session' };
|
|
2540
|
+
} else {
|
|
2541
|
+
const paid = session.payment_status === 'paid'
|
|
2542
|
+
|| (session.mode === 'subscription' && session.payment_status === 'no_payment_required');
|
|
2543
|
+
result = paid ? { verified: true, reason: 'paid' } : { verified: false, reason: 'not_paid' };
|
|
2544
|
+
}
|
|
2545
|
+
} catch (error) {
|
|
2546
|
+
result = { verified: false, reason: /no such/i.test(error?.message || '') ? 'unknown_session' : 'lookup_failed' };
|
|
2547
|
+
}
|
|
2548
|
+
if (!stripeClient) {
|
|
2549
|
+
if (successVerifyCache.size >= SUCCESS_VERIFY_CACHE_MAX) successVerifyCache.clear();
|
|
2550
|
+
successVerifyCache.set(id, {
|
|
2551
|
+
result,
|
|
2552
|
+
expiresAt: Date.now() + (result.verified ? SUCCESS_VERIFY_CACHE_MS : SUCCESS_VERIFY_FAIL_CACHE_MS),
|
|
2553
|
+
});
|
|
2554
|
+
}
|
|
2555
|
+
return result;
|
|
2556
|
+
}
|
|
2557
|
+
|
|
2415
2558
|
function getFunnelAnalytics(options = {}) {
|
|
2416
2559
|
const analyticsWindow = resolveAnalyticsWindow(options);
|
|
2417
2560
|
const extraRevenueEvents = Array.isArray(options.extraRevenueEvents) ? options.extraRevenueEvents : [];
|
|
@@ -2802,12 +2945,19 @@ function getBusinessAnalytics(options = {}) {
|
|
|
2802
2945
|
return !paidEventsGross.some((order) => resolveRevenueEventKey(order) === eventKey);
|
|
2803
2946
|
}).length;
|
|
2804
2947
|
|
|
2948
|
+
const checkoutSessionDepth = summarizeCheckoutSessionDepth(acquisitionEvents, options.checkoutSessionDepth);
|
|
2949
|
+
const telemetryCheckoutStarts = telemetry.ctas ? (telemetry.ctas.qualifiedCheckoutStarts ?? telemetry.ctas.checkoutStarts ?? 0) : 0;
|
|
2805
2950
|
const trafficMetrics = {
|
|
2806
2951
|
visitors: telemetry.visitors ? telemetry.visitors.uniqueVisitors || 0 : 0,
|
|
2807
2952
|
sessions: telemetry.visitors ? telemetry.visitors.uniqueSessions || 0 : 0,
|
|
2808
2953
|
pageViews: telemetry.visitors ? telemetry.visitors.pageViews || 0 : 0,
|
|
2809
2954
|
ctaClicks: telemetry.ctas ? telemetry.ctas.totalClicks || 0 : 0,
|
|
2810
|
-
|
|
2955
|
+
// Qualified = the Stripe session got past raw (an email entered or a payment
|
|
2956
|
+
// attempted). Falls back to the telemetry heuristic when Stripe was not asked.
|
|
2957
|
+
checkoutStarts: checkoutSessionDepth.basis === 'stripe_session_lookup'
|
|
2958
|
+
? checkoutSessionDepth.qualifiedCheckoutStarts
|
|
2959
|
+
: telemetryCheckoutStarts,
|
|
2960
|
+
checkoutStartsBasis: checkoutSessionDepth.basis,
|
|
2811
2961
|
checkoutSuccessPageViews: telemetry.ctas ? telemetry.ctas.successPageViews || 0 : 0,
|
|
2812
2962
|
checkoutCancelPageViews: telemetry.ctas ? (telemetry.ctas.qualifiedCancelPageViews ?? telemetry.ctas.cancelPageViews ?? 0) : 0,
|
|
2813
2963
|
checkoutPaidConfirmations: telemetry.ctas ? telemetry.ctas.paidConfirmations || 0 : 0,
|
|
@@ -2991,6 +3141,7 @@ function getBusinessAnalytics(options = {}) {
|
|
|
2991
3141
|
conversionByOfferCode,
|
|
2992
3142
|
},
|
|
2993
3143
|
trafficMetrics,
|
|
3144
|
+
checkoutSessionDepth,
|
|
2994
3145
|
ctas: telemetry.ctas || {},
|
|
2995
3146
|
operatorGeneratedAcquisition,
|
|
2996
3147
|
dataQuality,
|
|
@@ -3078,6 +3229,7 @@ function getBillingSummary(options = {}) {
|
|
|
3078
3229
|
newsletter: business.newsletter,
|
|
3079
3230
|
attribution: business.attribution,
|
|
3080
3231
|
trafficMetrics: business.trafficMetrics,
|
|
3232
|
+
checkoutSessionDepth: business.checkoutSessionDepth,
|
|
3081
3233
|
ctas: business.ctas,
|
|
3082
3234
|
operatorGeneratedAcquisition: business.operatorGeneratedAcquisition,
|
|
3083
3235
|
dataQuality: business.dataQuality,
|
|
@@ -3110,6 +3262,7 @@ function buildBillingSummaryFailure(error) {
|
|
|
3110
3262
|
|
|
3111
3263
|
async function getBillingSummariesLive(optionsByWindow = {}, {
|
|
3112
3264
|
listStripeReconciledRevenueEventsFn = listStripeReconciledRevenueEvents,
|
|
3265
|
+
listStripeCheckoutSessionDepthFn = listStripeCheckoutSessionDepth,
|
|
3113
3266
|
signal,
|
|
3114
3267
|
} = {}) {
|
|
3115
3268
|
const entries = Object.entries(optionsByWindow || {});
|
|
@@ -3122,6 +3275,9 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
|
|
|
3122
3275
|
if (signal?.aborted) abort();
|
|
3123
3276
|
let extraRevenueEvents = [];
|
|
3124
3277
|
let reconciliation = { status: 'ok', complete: true };
|
|
3278
|
+
const depthPromise = Promise.resolve()
|
|
3279
|
+
.then(() => listStripeCheckoutSessionDepthFn({ signal: controller.signal }))
|
|
3280
|
+
.catch(() => null);
|
|
3125
3281
|
try {
|
|
3126
3282
|
extraRevenueEvents = await withTimeout(listStripeReconciledRevenueEventsFn({
|
|
3127
3283
|
signal: controller.signal, deadline: Date.now() + reconciliationTimeoutMs,
|
|
@@ -3129,6 +3285,10 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
|
|
|
3129
3285
|
reconciliation = extraRevenueEvents.reconciliation || reconciliation;
|
|
3130
3286
|
} catch (error) {
|
|
3131
3287
|
reconciliation = { status: /timeout/i.test(error?.message || '') ? 'timeout' : 'unavailable', complete: false };
|
|
3288
|
+
}
|
|
3289
|
+
let checkoutSessionDepth = null;
|
|
3290
|
+
try {
|
|
3291
|
+
checkoutSessionDepth = await depthPromise;
|
|
3132
3292
|
} finally {
|
|
3133
3293
|
controller.abort();
|
|
3134
3294
|
signal?.removeEventListener('abort', abort);
|
|
@@ -3136,7 +3296,7 @@ async function getBillingSummariesLive(optionsByWindow = {}, {
|
|
|
3136
3296
|
if (signal?.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' });
|
|
3137
3297
|
try {
|
|
3138
3298
|
return Object.fromEntries(entries.map(([key, options]) => [key, {
|
|
3139
|
-
...getBillingSummary({ ...options, extraRevenueEvents }), reconciliation,
|
|
3299
|
+
...getBillingSummary({ ...options, extraRevenueEvents, checkoutSessionDepth }), reconciliation,
|
|
3140
3300
|
}]));
|
|
3141
3301
|
} catch (error) {
|
|
3142
3302
|
return Object.fromEntries(entries.map(([key]) => [key, { ...buildBillingSummaryFailure(error), reconciliation }]));
|
|
@@ -3387,10 +3547,25 @@ function isLiveStripeKey(key) {
|
|
|
3387
3547
|
return /^(sk|rk)_live_/.test(String(key || ''));
|
|
3388
3548
|
}
|
|
3389
3549
|
|
|
3390
|
-
|
|
3550
|
+
// Where a session came from. Always present on a session our server creates; a
|
|
3551
|
+
// missing value is the word "unknown" so the key is never absent.
|
|
3552
|
+
const CLICK_METADATA_KEYS = ['landingPage', 'referrer', 'uaClass', 'buttonId'];
|
|
3553
|
+
|
|
3554
|
+
function resolveClickMetadata(humanClick) {
|
|
3555
|
+
const given = humanClick && typeof humanClick.metadata === 'object' && humanClick.metadata ? humanClick.metadata : {};
|
|
3556
|
+
const resolved = {};
|
|
3557
|
+
for (const key of CLICK_METADATA_KEYS) {
|
|
3558
|
+
const value = String(given[key] == null ? '' : given[key]).trim();
|
|
3559
|
+
resolved[key] = value ? value.slice(0, 200) : 'unknown';
|
|
3560
|
+
}
|
|
3561
|
+
return resolved;
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, installId, traceId, packId = null, metadata = {}, appOrigin, humanClick = null } = {}) {
|
|
3391
3565
|
const resolvedTraceId = traceId || metadata.traceId || createTraceId('checkout');
|
|
3392
3566
|
const baseCheckoutMetadata = sanitizeMetadata({
|
|
3393
3567
|
...metadata,
|
|
3568
|
+
...resolveClickMetadata(humanClick),
|
|
3394
3569
|
installId: installId || metadata.installId || 'unknown',
|
|
3395
3570
|
traceId: resolvedTraceId,
|
|
3396
3571
|
});
|
|
@@ -3441,6 +3616,15 @@ async function createCheckoutSession({ successUrl, cancelUrl, customerEmail, ins
|
|
|
3441
3616
|
throw blockedErr;
|
|
3442
3617
|
}
|
|
3443
3618
|
|
|
3619
|
+
// A Stripe session opens only for a request the human-click gate admitted
|
|
3620
|
+
// (scripts/checkout-human-gate.js). Refused before any Stripe call.
|
|
3621
|
+
if (!(humanClick && humanClick.admitted === true)) {
|
|
3622
|
+
const refused = new Error('Refusing to open a Stripe Checkout session without a confirmed human click.');
|
|
3623
|
+
refused.statusCode = 403;
|
|
3624
|
+
refused.code = 'HUMAN_CLICK_REQUIRED';
|
|
3625
|
+
throw refused;
|
|
3626
|
+
}
|
|
3627
|
+
|
|
3444
3628
|
const stripe = getStripeClient();
|
|
3445
3629
|
|
|
3446
3630
|
if (!packId) {
|
|
@@ -4974,8 +5158,9 @@ module.exports = {
|
|
|
4974
5158
|
withStripeReadSlot, getBillingAnalyticsReadPaths,
|
|
4975
5159
|
_mergeRevenueEvents: mergeRevenueEvents,
|
|
4976
5160
|
_buildStripeReconciledRevenueEvent: buildStripeReconciledRevenueEvent,
|
|
4977
|
-
CONFIG, createCheckoutSession, isAutomatedCheckoutRequest, isSyntheticOrOwnerCheckoutEmail, createBillingPortalSession, getCheckoutSessionStatus, provisionApiKey, resolvePaidEntitlementForEmail, rotateApiKey, validateApiKey, recordUsage, recordAccountFirstBlock, disableCustomerKeys, handleWebhook, verifyWebhookSignature, verifyGithubWebhookSignature, verifyPayPalWebhookSignature, recordGithubMarketplaceWebhookDelivery, recordPayPalWebhookDelivery, handleGithubWebhook, loadKeyStore, appendFunnelEvent, appendRevenueEvent, loadFunnelLedger, loadRevenueLedger, loadGithubMarketplaceWebhookLedger, loadPayPalWebhookLedger, loadNewsletterSubscribers, loadResolvedRevenueEvents, getFunnelAnalytics, getBusinessAnalytics, getBillingSummary, getBillingSummaryLive, getBillingSummariesLive, listStripeReconciledRevenueEvents, repairGithubMarketplaceRevenueLedger,
|
|
5161
|
+
CONFIG, createCheckoutSession, isAutomatedCheckoutRequest, isSyntheticOrOwnerCheckoutEmail, createBillingPortalSession, getCheckoutSessionStatus, provisionApiKey, resolvePaidEntitlementForEmail, rotateApiKey, validateApiKey, recordUsage, recordAccountFirstBlock, disableCustomerKeys, handleWebhook, verifyWebhookSignature, verifyGithubWebhookSignature, verifyPayPalWebhookSignature, recordGithubMarketplaceWebhookDelivery, recordPayPalWebhookDelivery, handleGithubWebhook, loadKeyStore, appendFunnelEvent, appendRevenueEvent, loadFunnelLedger, loadRevenueLedger, loadGithubMarketplaceWebhookLedger, loadPayPalWebhookLedger, loadNewsletterSubscribers, loadResolvedRevenueEvents, getFunnelAnalytics, getBusinessAnalytics, getBillingSummary, getBillingSummaryLive, getBillingSummariesLive, listStripeReconciledRevenueEvents, listStripeCheckoutSessionDepth, classifyCheckoutSessionDepth, summarizeCheckoutSessionDepth, verifyPaidCheckoutSession, repairGithubMarketplaceRevenueLedger,
|
|
4978
5162
|
_buildCheckoutSessionPayload: buildCheckoutSessionPayload,
|
|
5163
|
+
_setStripeClient: setStripeClientForTests,
|
|
4979
5164
|
_filterQualifiedCheckoutFunnelEvents: filterQualifiedCheckoutFunnelEvents,
|
|
4980
5165
|
_createSessionDroppingRejectedOptionals: createSessionDroppingRejectedOptionals,
|
|
4981
5166
|
_buildTrialActivationEmail: buildTrialActivationEmail,
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Local, opt-in counter for the moment a free install hits the learned-rule cap.
|
|
3
|
+
// - Off unless THUMBGATE_LOCAL_COUNTERS=1.
|
|
4
|
+
// - Writes one JSON line to <feedbackDir>/local-counters.jsonl: event, ts, cap, activeGates.
|
|
5
|
+
// No rule text, command, path or id. Nothing is sent anywhere; this module has no network code.
|
|
6
|
+
// - Never throws: a counter must not break feedback capture.
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { resolveFeedbackDir } = require('./feedback-paths');
|
|
11
|
+
|
|
12
|
+
const COUNTER_FILE = 'local-counters.jsonl';
|
|
13
|
+
const EVENT = 'rule_cap_hit';
|
|
14
|
+
|
|
15
|
+
function countersEnabled() {
|
|
16
|
+
return process.env.THUMBGATE_LOCAL_COUNTERS === '1';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function counterPath(options = {}) {
|
|
20
|
+
return path.join(options.feedbackDir || resolveFeedbackDir(options), COUNTER_FILE);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function recordCapHit({ feedbackDir, cap, activeGates, enabled = countersEnabled() } = {}) {
|
|
24
|
+
if (!enabled) return false;
|
|
25
|
+
try {
|
|
26
|
+
const file = counterPath({ feedbackDir });
|
|
27
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
28
|
+
fs.appendFileSync(file, `${JSON.stringify({ event: EVENT, ts: new Date().toISOString(), cap, activeGates })}\n`);
|
|
29
|
+
return true;
|
|
30
|
+
} catch (_) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readCapHitCount(options = {}) {
|
|
36
|
+
try {
|
|
37
|
+
return fs.readFileSync(counterPath(options), 'utf8')
|
|
38
|
+
.split('\n')
|
|
39
|
+
.filter((line) => {
|
|
40
|
+
try { return JSON.parse(line).event === EVENT; } catch (_) { return false; }
|
|
41
|
+
}).length;
|
|
42
|
+
} catch (_) {
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { COUNTER_FILE, EVENT, countersEnabled, recordCapHit, readCapHitCount };
|