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.
Files changed (54) hide show
  1. package/.agents/skills/comet-session-logger/SKILL.md +8 -5
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +7 -2
  5. package/adapters/claude/.mcp.json +3 -3
  6. package/adapters/forge/forge.yaml +3 -3
  7. package/adapters/future-agi/.mcp.json +1 -1
  8. package/adapters/future-agi/config.toml +1 -1
  9. package/adapters/future-agi/opencode.json +1 -1
  10. package/adapters/herdr/herdr-plugin.toml +2 -2
  11. package/adapters/mcp/server-stdio.js +1 -1
  12. package/adapters/opencode/opencode.json +1 -1
  13. package/config/github-about.json +1 -1
  14. package/config/post-deploy-marketing-pages.json +1 -1
  15. package/package.json +35 -7
  16. package/public/about.html +2 -2
  17. package/public/admin.html +546 -50
  18. package/public/case-studies.html +1 -0
  19. package/public/dashboard.html +7 -6
  20. package/public/diagnostic.html +15 -12
  21. package/public/index.html +210 -88
  22. package/public/install.html +9 -8
  23. package/public/js/connect-panel.js +437 -0
  24. package/public/learn.html +8 -0
  25. package/public/numbers.html +2 -2
  26. package/public/preview.html +42 -0
  27. package/public/pricing.html +55 -10
  28. package/public/support.html +1 -1
  29. package/public/terms.html +1 -1
  30. package/scripts/auto-promote-gates.js +29 -4
  31. package/scripts/billing.js +189 -4
  32. package/scripts/cap-hit-counter.js +47 -0
  33. package/scripts/checkout-human-gate.js +248 -0
  34. package/scripts/checkout-session-count.js +119 -0
  35. package/scripts/claude-feedback-sync.js +4 -2
  36. package/scripts/feedback-loop.js +41 -5
  37. package/scripts/first-block-upsell.js +187 -0
  38. package/scripts/gates-engine.js +37 -108
  39. package/scripts/human-feedback.js +20 -1
  40. package/scripts/ops-log.js +91 -0
  41. package/scripts/ops-report.js +174 -0
  42. package/scripts/owner-admin.js +508 -27
  43. package/scripts/owner-telemetry.js +151 -0
  44. package/scripts/rate-limiter.js +8 -2
  45. package/scripts/statusline-human-counts.js +71 -8
  46. package/scripts/statusline.sh +15 -2
  47. package/scripts/telemetry-analytics.js +4 -0
  48. package/scripts/tool-contract-validator.js +13 -3
  49. package/scripts/tool-registry.js +1 -1
  50. package/scripts/utm-source-summary.js +88 -0
  51. package/server.json +2 -2
  52. package/skills/comet-session-logger/SKILL.md +8 -5
  53. package/src/api/server.js +649 -107
  54. package/src/mcp/email-triage-server/index.js +92 -14
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * checkout-human-gate.js: decides whether a request may open a Stripe Checkout
5
+ * Session. A session is created only for a POST that carries a short-lived,
6
+ * single-use token fetched by page JS after a trusted pointer or keyboard
7
+ * event, from a browser-class user agent, with at most 2 admissions per IP per
8
+ * minute and a site-wide ceiling. Spec: docs/designs/2026-11-18-human-click-checkout.md.
9
+ *
10
+ * What this does not stop: a script that rotates IPs and calls the token
11
+ * endpoint itself. The ceiling bounds that, it does not prevent it.
12
+ */
13
+
14
+ const crypto = require('node:crypto');
15
+ const { classifyRequester } = require('./bot-detection');
16
+
17
+ const TOKEN_TTL_MS = 120 * 1000;
18
+ const BURST_MAX = 2;
19
+ const BURST_WINDOW_MS = 60 * 1000;
20
+ const BURST_MAX_KEYS = 5000;
21
+ const GLOBAL_MAX = 60;
22
+ const GLOBAL_WINDOW_MS = 60 * 60 * 1000;
23
+ const META_VALUE_MAX = 200;
24
+ const BUTTON_ID_PATTERN = /^[A-Za-z0-9_:.-]{1,80}$/;
25
+ const LANDING_PATH_PATTERN = /^\/[A-Za-z0-9/_.~%-]{0,199}$/;
26
+
27
+ function headerValue(headers, name) {
28
+ const value = headers && headers[name];
29
+ if (Array.isArray(value)) return value.join(',');
30
+ return typeof value === 'string' ? value : '';
31
+ }
32
+
33
+ function shortHash(value) {
34
+ return crypto.createHash('sha256').update(String(value || '')).digest('base64url').slice(0, 22);
35
+ }
36
+
37
+ // Same trust rule the intake alert limiter uses (buildIntakeAlertRateLimitKey in
38
+ // src/api/server.js): behind Railway, x-real-ip is overwritten at the ingress and
39
+ // can be trusted; anywhere else every forwarding header is caller controlled and
40
+ // is ignored. cf-connecting-ip and x-forwarded-for are never used: no Cloudflare
41
+ // fronts this site, so a client can set both.
42
+ function clientIpKey(headers = {}, remoteAddress = '', env = process.env) {
43
+ const behindRailway = Boolean(env && (env.RAILWAY_ENVIRONMENT_ID || env.RAILWAY_PROJECT_ID));
44
+ const realIp = headerValue(headers, 'x-real-ip').trim();
45
+ if (behindRailway && /^[0-9a-f:.]{3,64}$/i.test(realIp)) return realIp;
46
+ return String(remoteAddress || '').trim() || 'no-ip';
47
+ }
48
+
49
+ function classifyUserAgentClass(headers = {}) {
50
+ if (!headerValue(headers, 'user-agent').trim()) return 'unknown';
51
+ return classifyRequester(headers).isBot ? 'bot' : 'browser';
52
+ }
53
+
54
+ function createTokenService({ secret, now = Date.now, ttlMs = TOKEN_TTL_MS } = {}) {
55
+ if (!secret) throw new Error('createTokenService needs a signing value');
56
+ const used = new Map();
57
+
58
+ function sign(payload) {
59
+ return crypto.createHmac('sha256', secret).update(payload).digest('base64url');
60
+ }
61
+ function prune(at) {
62
+ for (const [nonce, expiresAt] of used) {
63
+ if (expiresAt > at) break;
64
+ used.delete(nonce);
65
+ }
66
+ }
67
+
68
+ function issue({ ipKey, userAgent, buttonId, landingPage }) {
69
+ const at = now();
70
+ const claims = {
71
+ iat: at,
72
+ exp: at + ttlMs,
73
+ ip: shortHash(ipKey),
74
+ ua: shortHash(userAgent),
75
+ btn: String(buttonId || '').slice(0, META_VALUE_MAX),
76
+ lp: String(landingPage || '').slice(0, META_VALUE_MAX),
77
+ n: crypto.randomBytes(12).toString('base64url'),
78
+ };
79
+ const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
80
+ return `${payload}.${sign(payload)}`;
81
+ }
82
+
83
+ // consume=false lets the caller check other limits first and burn the token last.
84
+ function verify(token, { ipKey, userAgent } = {}, { consume = true } = {}) {
85
+ if (!token || typeof token !== 'string') return { ok: false, reason: 'missing' };
86
+ const parts = token.split('.');
87
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return { ok: false, reason: 'malformed' };
88
+ const expected = Buffer.from(sign(parts[0]));
89
+ const given = Buffer.from(parts[1]);
90
+ if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
91
+ return { ok: false, reason: 'bad_signature' };
92
+ }
93
+ let claims;
94
+ try {
95
+ claims = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
96
+ } catch {
97
+ return { ok: false, reason: 'malformed' };
98
+ }
99
+ const at = now();
100
+ if (!claims || typeof claims.exp !== 'number' || claims.exp < at) return { ok: false, reason: 'expired' };
101
+ if (claims.ip !== shortHash(ipKey)) return { ok: false, reason: 'ip_mismatch' };
102
+ if (claims.ua !== shortHash(userAgent)) return { ok: false, reason: 'ua_mismatch' };
103
+ prune(at);
104
+ if (used.has(claims.n)) return { ok: false, reason: 'replayed' };
105
+ if (consume) used.set(claims.n, claims.exp);
106
+ return { ok: true, claims };
107
+ }
108
+
109
+ function consume(claims) {
110
+ if (claims && claims.n) used.set(claims.n, claims.exp);
111
+ }
112
+
113
+ return { issue, verify, consume };
114
+ }
115
+
116
+ function createBurstLimiter({ max = BURST_MAX, windowMs = BURST_WINDOW_MS, maxKeys = BURST_MAX_KEYS } = {}) {
117
+ const hits = new Map();
118
+ function recent(key, at) {
119
+ return (hits.get(key) || []).filter((stamp) => at - stamp <= windowMs);
120
+ }
121
+ return {
122
+ wouldAdmit(key, at = Date.now()) {
123
+ return recent(key, at).length < max;
124
+ },
125
+ // Records an admission and returns true, or returns false without recording
126
+ // when the key already used its allowance inside the window.
127
+ admit(key, at = Date.now()) {
128
+ const live = recent(key, at);
129
+ if (live.length >= max) {
130
+ hits.set(key, live);
131
+ return false;
132
+ }
133
+ live.push(at);
134
+ hits.delete(key);
135
+ hits.set(key, live);
136
+ while (hits.size > maxKeys) hits.delete(hits.keys().next().value);
137
+ return true;
138
+ },
139
+ size() {
140
+ return hits.size;
141
+ },
142
+ };
143
+ }
144
+
145
+ function cleanReferrer(raw) {
146
+ const text = String(raw || '').trim();
147
+ if (!text) return '';
148
+ let cut = text;
149
+ try {
150
+ const url = new URL(text);
151
+ cut = `${url.origin}${url.pathname}`;
152
+ } catch {
153
+ cut = text.split(/[?#]/)[0];
154
+ }
155
+ return cut.slice(0, META_VALUE_MAX);
156
+ }
157
+
158
+ // landingPage and buttonId come from the browser, so they are recorded as
159
+ // untrusted: only values shaped like a path or an id are kept.
160
+ function cleanLandingPage(raw) {
161
+ const text = String(raw || '').trim();
162
+ if (!text) return '';
163
+ let path = text;
164
+ try {
165
+ path = new URL(text, 'https://thumbgate.invalid').pathname;
166
+ } catch {
167
+ path = text.split(/[?#]/)[0];
168
+ }
169
+ return LANDING_PATH_PATTERN.test(path) ? path : '';
170
+ }
171
+
172
+ function cleanButtonId(raw) {
173
+ const text = String(raw || '').trim();
174
+ return BUTTON_ID_PATTERN.test(text) ? text : '';
175
+ }
176
+
177
+ // Always returns the four keys; a missing or invalid value is the word "unknown".
178
+ function buildClickMetadata({ headers = {}, claims = null } = {}) {
179
+ return {
180
+ landingPage: cleanLandingPage(claims && claims.lp) || 'unknown',
181
+ referrer: cleanReferrer(headerValue(headers, 'referer') || headerValue(headers, 'referrer')) || 'unknown',
182
+ uaClass: classifyUserAgentClass(headers),
183
+ buttonId: cleanButtonId(claims && claims.btn) || 'unknown',
184
+ };
185
+ }
186
+
187
+ function createHumanGate({
188
+ secret,
189
+ now = Date.now,
190
+ ttlMs,
191
+ max,
192
+ windowMs,
193
+ globalMax = GLOBAL_MAX,
194
+ globalWindowMs = GLOBAL_WINDOW_MS,
195
+ env = process.env,
196
+ } = {}) {
197
+ const tokens = createTokenService({ secret, now, ttlMs });
198
+ const limiter = createBurstLimiter({ max, windowMs });
199
+ const ceiling = createBurstLimiter({ max: globalMax, windowMs: globalWindowMs, maxKeys: 1 });
200
+
201
+ // Gives a token only to a browser-class user agent.
202
+ function issueToken({ headers = {}, remoteAddress = '', buttonId = '', landingPage = '' } = {}) {
203
+ if (classifyUserAgentClass(headers) !== 'browser') return null;
204
+ return tokens.issue({
205
+ ipKey: clientIpKey(headers, remoteAddress, env),
206
+ userAgent: headerValue(headers, 'user-agent'),
207
+ buttonId,
208
+ landingPage,
209
+ });
210
+ }
211
+
212
+ function admit({ method, headers = {}, remoteAddress = '', token } = {}) {
213
+ const refuse = (status, reason) => ({ ok: false, status, reason });
214
+ if (String(method || '').toUpperCase() !== 'POST') return refuse(405, 'method_not_post');
215
+ const uaClass = classifyUserAgentClass(headers);
216
+ if (uaClass !== 'browser') return refuse(403, `ua_${uaClass}`);
217
+ const ipKey = clientIpKey(headers, remoteAddress, env);
218
+ const checked = tokens.verify(token, { ipKey, userAgent: headerValue(headers, 'user-agent') }, { consume: false });
219
+ if (!checked.ok) return refuse(403, `token_${checked.reason}`);
220
+ const at = now();
221
+ if (!limiter.wouldAdmit(ipKey, at)) return refuse(429, 'burst_limit');
222
+ if (!ceiling.wouldAdmit('all', at)) return refuse(429, 'global_ceiling');
223
+ limiter.admit(ipKey, at);
224
+ ceiling.admit('all', at);
225
+ tokens.consume(checked.claims);
226
+ return {
227
+ ok: true,
228
+ status: 200,
229
+ reason: null,
230
+ humanClick: { admitted: true, metadata: buildClickMetadata({ headers, claims: checked.claims }) },
231
+ };
232
+ }
233
+
234
+ return { issueToken, admit, tokens, limiter, ceiling };
235
+ }
236
+
237
+ module.exports = {
238
+ TOKEN_TTL_MS,
239
+ BURST_MAX,
240
+ BURST_WINDOW_MS,
241
+ GLOBAL_MAX,
242
+ clientIpKey,
243
+ classifyUserAgentClass,
244
+ createTokenService,
245
+ createBurstLimiter,
246
+ buildClickMetadata,
247
+ createHumanGate,
248
+ };
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Checkout starts without crawlers.
6
+ *
7
+ * Stripe's own session list counts every session ever created, and until 2026-11-18 (the human-click
8
+ * gate, scripts/checkout-human-gate.js) a crawler opening a payment link created one. Sessions made
9
+ * since then carry `metadata.uaClass` (browser | bot | unknown), set from the click's user agent.
10
+ *
11
+ * human uaClass = browser -> the only bucket counted as a real start
12
+ * bot uaClass = bot -> excluded
13
+ * unknownUa uaClass = unknown -> excluded (no user agent sent)
14
+ * unclassified no uaClass -> excluded: created before the gate, user agent not recorded,
15
+ * cannot be told apart from a crawler session
16
+ * internal owner email, or metadata.source = internal_audit -> excluded
17
+ *
18
+ * Read-only. Needs STRIPE_SECRET_KEY in the environment (run under `railway run`); never prints it.
19
+ *
20
+ * Usage: node scripts/checkout-session-count.js [--days 7] [--json]
21
+ */
22
+
23
+ const { getOwnerEmails } = require('./bot-detection');
24
+
25
+ // When the human-click gate went live: 2026-11-18 7:04 PM ET. Sessions created before it carry no user-agent class.
26
+ const BOT_CHECK_BEGAN_AT = '2026-11-19T00:04:00.000Z';
27
+ const BOT_CHECK_BEGAN_LABEL = '18 Nov 2026, 7:04 PM ET';
28
+
29
+ function classifySession(session, { ownerEmails = [] } = {}) {
30
+ const metadata = (session && session.metadata) || {};
31
+ if (metadata.source === 'internal_audit') return 'internal';
32
+ const email = String((session && (session.customer_email || (session.customer_details && session.customer_details.email))) || '').toLowerCase();
33
+ if (email && ownerEmails.some((owner) => email.includes(owner))) return 'internal';
34
+ if (metadata.uaClass === 'browser') return 'human';
35
+ if (metadata.uaClass === 'bot') return 'bot';
36
+ if (metadata.uaClass === 'unknown') return 'unknownUa';
37
+ return 'unclassified';
38
+ }
39
+
40
+ function countSessions(sessions, { ownerEmails = getOwnerEmails() } = {}) {
41
+ const excluded = { bot: 0, unknownUa: 0, unclassified: 0, internal: 0 };
42
+ let human = 0;
43
+ let completed = 0;
44
+ let humanCompleted = 0;
45
+ let humanPaid = 0;
46
+ const list = Array.isArray(sessions) ? sessions : [];
47
+ for (const session of list) {
48
+ const kind = classifySession(session, { ownerEmails });
49
+ const isComplete = session && session.status === 'complete';
50
+ if (isComplete) completed += 1;
51
+ if (kind === 'human') {
52
+ human += 1;
53
+ if (isComplete) humanCompleted += 1;
54
+ if (session.payment_status === 'paid') humanPaid += 1;
55
+ } else {
56
+ excluded[kind] += 1;
57
+ }
58
+ }
59
+ return {
60
+ started: list.length,
61
+ nonCrawlerStarted: human,
62
+ nonCrawlerCompleted: humanCompleted,
63
+ nonCrawlerPaid: humanPaid,
64
+ completedAll: completed,
65
+ excluded,
66
+ };
67
+ }
68
+
69
+ async function listSessions({ days = 7, stripe, nowMs = Date.now() } = {}) {
70
+ const since = Math.floor(nowMs / 1000) - days * 86400;
71
+ const rows = [];
72
+ for await (const session of stripe.checkout.sessions.list({ created: { gte: since }, limit: 100 })) {
73
+ // Only this product's sessions, same filter the daily audit uses.
74
+ if (/thumbgate/i.test(String(session.success_url || ''))) rows.push(session);
75
+ }
76
+ return rows;
77
+ }
78
+
79
+ function parseArgs(argv) {
80
+ const options = { days: 7, json: false };
81
+ for (let i = 0; i < argv.length; i += 1) {
82
+ if (argv[i] === '--json') options.json = true;
83
+ else if (argv[i] === '--days') options.days = Number(argv[++i]) || 7;
84
+ }
85
+ return options;
86
+ }
87
+
88
+ async function main(argv = process.argv.slice(2)) {
89
+ const options = parseArgs(argv);
90
+ if (!process.env.STRIPE_SECRET_KEY) {
91
+ process.stderr.write('STRIPE_SECRET_KEY is not set. Run under: railway run -s thumbgate -- node scripts/checkout-session-count.js\n');
92
+ process.exit(2);
93
+ }
94
+ const Stripe = require('stripe');
95
+ const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
96
+ const sessions = await listSessions({ days: options.days, stripe });
97
+ const counts = countSessions(sessions);
98
+ const report = { at: new Date().toISOString(), days: options.days, ...counts };
99
+ if (options.json) {
100
+ process.stdout.write(`${JSON.stringify(report)}\n`);
101
+ return;
102
+ }
103
+ const ex = counts.excluded;
104
+ process.stdout.write(
105
+ `Checkout starts, last ${options.days} days: ${counts.nonCrawlerStarted} from real browsers `
106
+ + `(${counts.started} sessions in Stripe; excluded: ${ex.unclassified} before the human-click gate, `
107
+ + `${ex.bot} bot, ${ex.unknownUa} no user agent, ${ex.internal} internal). `
108
+ + `Completed: ${counts.nonCrawlerCompleted} real, ${counts.completedAll} all. Paid: ${counts.nonCrawlerPaid} real.\n`,
109
+ );
110
+ }
111
+
112
+ if (require.main === module) {
113
+ main().catch((err) => {
114
+ process.stderr.write(`checkout-session-count error: ${err.message}\n`);
115
+ process.exit(1);
116
+ });
117
+ }
118
+
119
+ module.exports = { classifySession, countSessions, listSessions, parseArgs, BOT_CHECK_BEGAN_AT, BOT_CHECK_BEGAN_LABEL };
@@ -19,7 +19,9 @@ const { refreshStatuslineCache } = require('./hook-thumbgate-cache-updater');
19
19
  const SYNC_STATE_FILE = 'claude-feedback-sync-state.json';
20
20
  const DEFAULT_RECENT_FEEDBACK_LIMIT = 1000;
21
21
  const DEFAULT_PROCESSED_ID_LIMIT = 4096;
22
- const DUPLICATE_WINDOW_MS = 5 * 60 * 1000;
22
+ // Same typed prompt seen by the live hook and by this history sync: event
23
+ // timestamps are seconds apart. A repeat later than this is a new thumbs-down.
24
+ const DUPLICATE_WINDOW_MS = 30 * 1000;
23
25
  // At this length, identical text + signal is a re-surfaced prompt, not a
24
26
  // repeated sentiment; shorter bare signals stay window-bound.
25
27
  const IDENTICAL_TEXT_DEDUP_MIN_LENGTH = 20;
@@ -229,7 +231,7 @@ function hasMatchingFeedbackEntry(candidate, feedbackEntries) {
229
231
  return true;
230
232
  }
231
233
 
232
- const feedbackTimestamp = Date.parse(entry.timestamp || '');
234
+ const feedbackTimestamp = Date.parse((entry.sourceEvent && entry.sourceEvent.timestamp) || entry.timestamp || '');
233
235
  if (!Number.isFinite(feedbackTimestamp) || !Number.isFinite(candidate.timestampMs)) {
234
236
  return true;
235
237
  }
@@ -61,6 +61,12 @@ const {
61
61
 
62
62
  const AUDIT_TRAIL_TAG = 'audit-trail';
63
63
  const FEEDBACK_EVENT_DEDUPE_WINDOW_MS = 5 * 60 * 1000;
64
+ // Two deliveries of the SAME typed thumbs event (live hook plus Claude history
65
+ // sync) carry event timestamps seconds apart. A typed "thumbs down" that
66
+ // arrives later than this is a new prompt and must count, even when the text
67
+ // and session match. (22 Nov 2026: repeats 2 and 4 minutes after the first were
68
+ // swallowed as duplicates and the status-bar counter stayed at 1.)
69
+ const FEEDBACK_EVENT_REPEAT_GAP_MS = 30 * 1000;
64
70
  const FEEDBACK_EVENT_CLAIM_STALE_MS = 60 * 1000;
65
71
  const FEEDBACK_EVENT_CLAIM_WAIT_MS = 15 * 1000;
66
72
  const FEEDBACK_EVENT_CLAIM_POLL_MS = 25;
@@ -259,6 +265,22 @@ function updateStatuslineWithLesson({ accepted, signal, memoryId, feedbackId, le
259
265
  } catch { /* statusline update is best-effort */ }
260
266
  }
261
267
 
268
+ /**
269
+ * Re-count the status-bar thumbs after a capture that was logged but not
270
+ * promoted (lifecycle block, schema failure). The signal is in the feedback
271
+ * log, so the counter must include it; without this the cache kept its old
272
+ * counts until the next accepted capture.
273
+ */
274
+ function refreshStatuslineCounts() {
275
+ try {
276
+ const cachePath = path.join(getFeedbackPaths().FEEDBACK_DIR, 'statusline_cache.json');
277
+ const { refreshStatuslineCache } = require('./hook-thumbgate-cache-updater');
278
+ refreshStatuslineCache(analyzeFeedback(undefined, { humanOnly: true }), cachePath);
279
+ } catch {
280
+ /* statusline refresh is best-effort */
281
+ }
282
+ }
283
+
262
284
  function getFeedbackPaths(options = {}) {
263
285
  return resolveFeedbackPaths(options);
264
286
  }
@@ -937,7 +959,7 @@ function isDuplicateFeedbackEntry(entry, identity) {
937
959
  if (identity.promptIdHash && sourceEvent.promptIdHash === identity.promptIdHash) return true;
938
960
 
939
961
  const timestamp = parseFeedbackSourceTimestamp(sourceEvent.timestamp || entry.timestamp);
940
- return Math.abs(identity.eventTimestampMs - timestamp) <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS;
962
+ return Math.abs(identity.eventTimestampMs - timestamp) <= FEEDBACK_EVENT_REPEAT_GAP_MS;
941
963
  }
942
964
 
943
965
  function receiptFromFeedbackEntry(entry, paths) {
@@ -976,10 +998,17 @@ function tryCreateFeedbackClaim(claimPath) {
976
998
  function existingClaimResult(state, identity, paths) {
977
999
  const stateTimestamp = Number(state?.completedAtMs || state?.startedAtMs || 0);
978
1000
  const ageMs = stateTimestamp > 0 ? Date.now() - stateTimestamp : 0;
979
- if (state?.status === 'complete'
980
- && (identity.promptIdHash || ageMs <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS)) {
1001
+ if (state?.status === 'complete' && identity.promptIdHash) {
981
1002
  return duplicateCaptureResult(state, paths);
982
1003
  }
1004
+ if (state?.status === 'complete') {
1005
+ // Compare when the prompts were typed, not when the first capture finished.
1006
+ // Claims written before eventTimestampMs existed fall back to capture age.
1007
+ const sameEvent = Number.isFinite(state.eventTimestampMs)
1008
+ ? Math.abs(identity.eventTimestampMs - state.eventTimestampMs) <= FEEDBACK_EVENT_REPEAT_GAP_MS
1009
+ : ageMs <= FEEDBACK_EVENT_DEDUPE_WINDOW_MS;
1010
+ if (sameEvent) return duplicateCaptureResult(state, paths);
1011
+ }
983
1012
  if (state?.status === 'pending' && ageMs <= FEEDBACK_EVENT_CLAIM_STALE_MS) {
984
1013
  return duplicateCaptureResult(state, paths, { pending: true });
985
1014
  }
@@ -1010,10 +1039,11 @@ function acquireFeedbackEventClaim(identity, paths) {
1010
1039
  };
1011
1040
  }
1012
1041
 
1013
- function finalizeFeedbackEventClaim(claim, result) {
1042
+ function finalizeFeedbackEventClaim(claim, result, identity) {
1014
1043
  if (!claim?.owned) return;
1015
1044
  writeClaimState(claim.claimPath, {
1016
1045
  status: 'complete',
1046
+ eventTimestampMs: identity?.eventTimestampMs ?? null,
1017
1047
  startedAtMs: Date.now(),
1018
1048
  completedAtMs: Date.now(),
1019
1049
  accepted: Boolean(result?.accepted),
@@ -1719,6 +1749,7 @@ function captureFeedback(params, options = {}) {
1719
1749
  };
1720
1750
  appendJSONL(FEEDBACK_LOG_PATH, blockedEvent);
1721
1751
  emitAnonymousFeedbackPing(signal);
1752
+ refreshStatuslineCounts();
1722
1753
  return {
1723
1754
  accepted: true,
1724
1755
  captured: true,
@@ -1751,6 +1782,7 @@ function captureFeedback(params, options = {}) {
1751
1782
  validationIssues: prepared.issues,
1752
1783
  });
1753
1784
  emitAnonymousFeedbackPing(signal);
1785
+ refreshStatuslineCounts();
1754
1786
  try { appendRejectionLedger(feedbackEvent, `Schema validation failed: ${prepared.issues.join('; ')}`, options); } catch { /* non-critical */ }
1755
1787
  try {
1756
1788
  appendSequence(historyEntries, feedbackEvent, getFeedbackPaths(options), { accepted: false });
@@ -2079,6 +2111,10 @@ function captureFeedback(params, options = {}) {
2079
2111
  try {
2080
2112
  const autoPromote = require('./auto-promote-gates');
2081
2113
  const promoteResult = autoPromote.promote(FEEDBACK_LOG_PATH, { gateAction: feedbackEvent.gateAction });
2114
+ // Free tier: a 4th learned rule is stored but not enforced. Say so once, in one line.
2115
+ if (promoteResult && promoteResult.upgradeLine && !tenantDataScope()) {
2116
+ process.stderr.write(`${promoteResult.upgradeLine}\n`);
2117
+ }
2082
2118
  // First-rule activation telemetry: anonymous ping the first time
2083
2119
  // a prevention rule auto-promotes for this install. Idempotent —
2084
2120
  // see scripts/activation-tracker.js. Critical for activation funnel
@@ -2180,7 +2216,7 @@ function captureFeedbackIdempotent(params = {}, options = {}) {
2180
2216
 
2181
2217
  try {
2182
2218
  const result = captureFeedback({ ...params, sourceEvent: identity }, options);
2183
- finalizeFeedbackEventClaim(claim, result);
2219
+ finalizeFeedbackEventClaim(claim, result, identity);
2184
2220
  return result;
2185
2221
  } catch (error) {
2186
2222
  releaseFeedbackEventClaim(claim);
@@ -0,0 +1,187 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * One plain upgrade line right after a user's FIRST real block, then at most once per 7 days.
5
+ *
6
+ * Shape: "ThumbGate just stopped <what>. Pro adds <feature> - thumbgate.ai/pricing?utm_source=cli&utm_medium=first_block"
7
+ *
8
+ * Channel: a PreToolUse hook is never a TTY (stdin and stdout are pipes), so the line is not printed.
9
+ * It rides in the hook JSON's top-level `systemMessage`, which the host shows to the person and
10
+ * never feeds to the model. `permissionDecisionReason` (what the model reads) is left unchanged.
11
+ * Nothing in this module writes to stdout or stderr.
12
+ *
13
+ * Never shown: in CI, with THUMBGATE_NO_UPSELL=1, to a paying or licensed install, to the owner's
14
+ * own machine, or when the once-per-7-days state cannot be written.
15
+ * What was stopped is a fixed phrase per gate id, never the command, so no secret can leak into it.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ const COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000;
22
+ const PRICING_URL = 'thumbgate.ai/pricing?utm_source=cli&utm_medium=first_block';
23
+ const STATE_FILE = 'first-block-upsell.json';
24
+ const CI_VARS = ['CI', 'GITHUB_ACTIONS', 'TRAVIS', 'CIRCLECI', 'JENKINS_URL', 'GITLAB_CI', 'CODEBUILD_BUILD_ID'];
25
+
26
+ const STOPPED_PHRASES = {
27
+ 'secret-exfiltration': 'a secret being sent out of your machine',
28
+ 'force-push': 'a force push',
29
+ 'git-reset-hard': 'a hard reset that would discard your work',
30
+ 'git-clean-force': 'a forced clean that would delete untracked files',
31
+ 'rm-rf-home-or-root': 'a recursive delete of your home or root folder',
32
+ 'db-drop-table-production': 'a production table drop',
33
+ 'security-vuln-scan': 'code with a critical security finding',
34
+ 'slopsquat-guard': 'an install of a package name that looks made up',
35
+ 'learned-lesson': 'a repeat of a mistake you told ThumbGate about',
36
+ };
37
+ const DEFAULT_PHRASE = 'a risky tool call';
38
+
39
+ function stoppedPhrase(gateId) {
40
+ return STOPPED_PHRASES[gateId] || DEFAULT_PHRASE;
41
+ }
42
+
43
+ function proFeature() {
44
+ let cap = 3;
45
+ try { cap = require('./rate-limiter').FREE_TIER_MAX_GATES || cap; } catch { /* keep default */ }
46
+ return `enforcement of every rule you learn (Free enforces ${cap})`;
47
+ }
48
+
49
+ function buildLine(gateId) {
50
+ return `ThumbGate just stopped ${stoppedPhrase(gateId)}. Pro adds ${proFeature()} - ${PRICING_URL}`;
51
+ }
52
+
53
+ // A paying, licensed, creator or owner install never sees the line. The 7-day trial is NOT exempt:
54
+ // the first block almost always lands inside it, and that is exactly when this line should show.
55
+ function defaultExempt(env) {
56
+ if (env.THUMBGATE_API_KEY) return 'paid';
57
+ if (env.THUMBGATE_NO_RATE_LIMIT === '1') return 'paid';
58
+ try { if (require('./pro-local-dashboard').isCreatorDev()) return 'creator'; } catch { /* unavailable */ }
59
+ try { if (require('./license').isProLicensed()) return 'paid'; } catch { /* unavailable */ }
60
+ try { if (require('./cli-telemetry').classifyInstall() === 'owner') return 'owner'; } catch { /* unavailable */ }
61
+ return null;
62
+ }
63
+
64
+ function resolveStateDir(env, stateDir) {
65
+ if (stateDir) return stateDir;
66
+ if (env.THUMBGATE_STATE_DIR) return env.THUMBGATE_STATE_DIR;
67
+ try { return path.dirname(require('./cli-telemetry').INSTALL_ID_PATH); } catch { return null; }
68
+ }
69
+
70
+ function readState(file) {
71
+ try {
72
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
73
+ return parsed && typeof parsed === 'object' ? parsed : { corrupt: true };
74
+ } catch (err) {
75
+ return err && (err.code === 'ENOENT' || err.code === 'ENOTDIR') ? null : { corrupt: true };
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Decide whether to show the line for a real block, and record it when shown.
81
+ * @returns {{ show: boolean, line?: string, reason?: string }}
82
+ */
83
+ function maybeUpsell({ gate, env = process.env, now = Date.now(), stateDir, exempt = defaultExempt } = {}) {
84
+ try {
85
+ if (env.THUMBGATE_NO_UPSELL === '1') return { show: false, reason: 'opt-out' };
86
+ if (CI_VARS.some((name) => env[name])) return { show: false, reason: 'ci' };
87
+ if (env.THUMBGATE_SANDBOX_EVAL === '1') return { show: false, reason: 'sandbox' };
88
+ const exemptReason = exempt(env);
89
+ if (exemptReason) return { show: false, reason: exemptReason };
90
+
91
+ const dir = resolveStateDir(env, stateDir);
92
+ if (!dir) return { show: false, reason: 'no-state-dir' };
93
+ const file = path.join(dir, STATE_FILE);
94
+ const record = { firstShownAt: new Date(now).toISOString(), lastShownAt: now, shownCount: 1 };
95
+ const state = readState(file);
96
+
97
+ if (state === null) {
98
+ // First ever: claim with an exclusive create so two parallel hooks cannot both show it.
99
+ try {
100
+ fs.mkdirSync(dir, { recursive: true });
101
+ fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx' });
102
+ } catch (err) {
103
+ return { show: false, reason: err && err.code === 'EEXIST' ? 'claimed-elsewhere' : 'state-unwritable' };
104
+ }
105
+ return { show: true, line: buildLine(gate) };
106
+ }
107
+
108
+ if (state.corrupt) {
109
+ // Unreadable state: stay quiet now and restart the 7-day clock so it heals.
110
+ try { fs.writeFileSync(file, JSON.stringify({ ...record, firstShownAt: null, shownCount: 0 })); } catch { /* ignore */ }
111
+ return { show: false, reason: 'state-corrupt' };
112
+ }
113
+
114
+ const last = Number(state.lastShownAt);
115
+ if (Number.isFinite(last) && now - last < COOLDOWN_MS) return { show: false, reason: 'cooldown' };
116
+
117
+ const next = {
118
+ firstShownAt: state.firstShownAt || record.firstShownAt,
119
+ lastShownAt: now,
120
+ shownCount: (Number(state.shownCount) || 0) + 1,
121
+ };
122
+ const tmp = `${file}.${process.pid}.tmp`;
123
+ try {
124
+ fs.writeFileSync(tmp, JSON.stringify(next));
125
+ fs.renameSync(tmp, file);
126
+ } catch {
127
+ return { show: false, reason: 'state-unwritable' };
128
+ }
129
+ return { show: true, line: buildLine(gate) };
130
+ } catch {
131
+ return { show: false, reason: 'error' };
132
+ }
133
+ }
134
+
135
+ function gateIdFromReason(reason) {
136
+ const match = /^\[GATE:([^\]]+)\]/.exec(String(reason || ''));
137
+ return match ? match[1] : null;
138
+ }
139
+
140
+ /**
141
+ * Add `systemMessage` to a hook response object when it is a real deny and the line is due.
142
+ * Returns the same object (mutated) or an untouched one; never throws.
143
+ * `gateOverride` names a block that carries no [GATE:id] prefix (a learned-lesson block).
144
+ */
145
+ function attachUpsell(response, options = {}) {
146
+ try {
147
+ if (!response || typeof response !== 'object' || response.systemMessage) return response;
148
+ const hook = response.hookSpecificOutput || {};
149
+ const reason = String(hook.permissionDecisionReason || response.reason || '');
150
+ if (hook.permissionDecision !== 'deny') return response;
151
+ if (/APPROVAL REQUIRED/.test(reason)) return response;
152
+ const gate = options.gateOverride || gateIdFromReason(reason);
153
+ if (!gate || gate === 'financial-control') return response;
154
+ const result = maybeUpsell({ ...options, gate });
155
+ if (result.show) response.systemMessage = result.line;
156
+ return response;
157
+ } catch {
158
+ return response;
159
+ }
160
+ }
161
+
162
+ /** String form for the gate engine's hook output. */
163
+ function withFirstBlockUpsell(output, options = {}) {
164
+ try {
165
+ if (typeof output !== 'string') return output;
166
+ let parsed;
167
+ try { parsed = JSON.parse(output); } catch { return output; }
168
+ const before = parsed && parsed.systemMessage;
169
+ const after = attachUpsell(parsed, options);
170
+ return after && after.systemMessage && after.systemMessage !== before ? JSON.stringify(after) : output;
171
+ } catch {
172
+ return output;
173
+ }
174
+ }
175
+
176
+ module.exports = {
177
+ COOLDOWN_MS,
178
+ PRICING_URL,
179
+ STATE_FILE,
180
+ STOPPED_PHRASES,
181
+ stoppedPhrase,
182
+ buildLine,
183
+ maybeUpsell,
184
+ attachUpsell,
185
+ withFirstBlockUpsell,
186
+ gateIdFromReason,
187
+ };