thumbgate 1.40.2 → 1.40.5
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/mcp/server-card.json +1 -1
- package/README.md +2 -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 +4 -2
- 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 +30 -7
- package/public/about.html +2 -2
- package/public/admin.html +329 -47
- package/public/case-studies.html +1 -0
- package/public/dashboard.html +7 -6
- package/public/diagnostic.html +15 -12
- package/public/index.html +210 -78
- package/public/install.html +9 -8
- package/public/js/connect-panel.js +437 -0
- package/public/numbers.html +2 -2
- package/public/preview.html +42 -0
- package/public/pricing.html +55 -10
- package/scripts/auto-promote-gates.js +16 -1
- 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 +115 -0
- package/scripts/feedback-loop.js +8 -1
- package/scripts/first-block-upsell.js +187 -0
- package/scripts/gates-engine.js +37 -108
- package/scripts/human-feedback.js +42 -0
- package/scripts/ops-log.js +91 -0
- package/scripts/ops-report.js +174 -0
- package/scripts/owner-admin.js +373 -26
- package/scripts/owner-telemetry.js +142 -0
- package/scripts/rate-limiter.js +8 -2
- package/scripts/statusline-human-counts.js +132 -0
- package/scripts/statusline-links.js +13 -3
- package/scripts/statusline-local-stats.js +5 -3
- package/scripts/statusline.sh +31 -3
- 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/src/api/server.js +613 -107
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
function classifySession(session, { ownerEmails = [] } = {}) {
|
|
26
|
+
const metadata = (session && session.metadata) || {};
|
|
27
|
+
if (metadata.source === 'internal_audit') return 'internal';
|
|
28
|
+
const email = String((session && (session.customer_email || (session.customer_details && session.customer_details.email))) || '').toLowerCase();
|
|
29
|
+
if (email && ownerEmails.some((owner) => email.includes(owner))) return 'internal';
|
|
30
|
+
if (metadata.uaClass === 'browser') return 'human';
|
|
31
|
+
if (metadata.uaClass === 'bot') return 'bot';
|
|
32
|
+
if (metadata.uaClass === 'unknown') return 'unknownUa';
|
|
33
|
+
return 'unclassified';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function countSessions(sessions, { ownerEmails = getOwnerEmails() } = {}) {
|
|
37
|
+
const excluded = { bot: 0, unknownUa: 0, unclassified: 0, internal: 0 };
|
|
38
|
+
let human = 0;
|
|
39
|
+
let completed = 0;
|
|
40
|
+
let humanCompleted = 0;
|
|
41
|
+
let humanPaid = 0;
|
|
42
|
+
const list = Array.isArray(sessions) ? sessions : [];
|
|
43
|
+
for (const session of list) {
|
|
44
|
+
const kind = classifySession(session, { ownerEmails });
|
|
45
|
+
const isComplete = session && session.status === 'complete';
|
|
46
|
+
if (isComplete) completed += 1;
|
|
47
|
+
if (kind === 'human') {
|
|
48
|
+
human += 1;
|
|
49
|
+
if (isComplete) humanCompleted += 1;
|
|
50
|
+
if (session.payment_status === 'paid') humanPaid += 1;
|
|
51
|
+
} else {
|
|
52
|
+
excluded[kind] += 1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
started: list.length,
|
|
57
|
+
nonCrawlerStarted: human,
|
|
58
|
+
nonCrawlerCompleted: humanCompleted,
|
|
59
|
+
nonCrawlerPaid: humanPaid,
|
|
60
|
+
completedAll: completed,
|
|
61
|
+
excluded,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function listSessions({ days = 7, stripe, nowMs = Date.now() } = {}) {
|
|
66
|
+
const since = Math.floor(nowMs / 1000) - days * 86400;
|
|
67
|
+
const rows = [];
|
|
68
|
+
for await (const session of stripe.checkout.sessions.list({ created: { gte: since }, limit: 100 })) {
|
|
69
|
+
// Only this product's sessions, same filter the daily audit uses.
|
|
70
|
+
if (/thumbgate/i.test(String(session.success_url || ''))) rows.push(session);
|
|
71
|
+
}
|
|
72
|
+
return rows;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseArgs(argv) {
|
|
76
|
+
const options = { days: 7, json: false };
|
|
77
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
78
|
+
if (argv[i] === '--json') options.json = true;
|
|
79
|
+
else if (argv[i] === '--days') options.days = Number(argv[++i]) || 7;
|
|
80
|
+
}
|
|
81
|
+
return options;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function main(argv = process.argv.slice(2)) {
|
|
85
|
+
const options = parseArgs(argv);
|
|
86
|
+
if (!process.env.STRIPE_SECRET_KEY) {
|
|
87
|
+
process.stderr.write('STRIPE_SECRET_KEY is not set. Run under: railway run -s thumbgate -- node scripts/checkout-session-count.js\n');
|
|
88
|
+
process.exit(2);
|
|
89
|
+
}
|
|
90
|
+
const Stripe = require('stripe');
|
|
91
|
+
const stripe = Stripe(process.env.STRIPE_SECRET_KEY);
|
|
92
|
+
const sessions = await listSessions({ days: options.days, stripe });
|
|
93
|
+
const counts = countSessions(sessions);
|
|
94
|
+
const report = { at: new Date().toISOString(), days: options.days, ...counts };
|
|
95
|
+
if (options.json) {
|
|
96
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const ex = counts.excluded;
|
|
100
|
+
process.stdout.write(
|
|
101
|
+
`Checkout starts, last ${options.days} days: ${counts.nonCrawlerStarted} from real browsers `
|
|
102
|
+
+ `(${counts.started} sessions in Stripe; excluded: ${ex.unclassified} before the human-click gate, `
|
|
103
|
+
+ `${ex.bot} bot, ${ex.unknownUa} no user agent, ${ex.internal} internal). `
|
|
104
|
+
+ `Completed: ${counts.nonCrawlerCompleted} real, ${counts.completedAll} all. Paid: ${counts.nonCrawlerPaid} real.\n`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (require.main === module) {
|
|
109
|
+
main().catch((err) => {
|
|
110
|
+
process.stderr.write(`checkout-session-count error: ${err.message}\n`);
|
|
111
|
+
process.exit(1);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { classifySession, countSessions, listSessions, parseArgs };
|
package/scripts/feedback-loop.js
CHANGED
|
@@ -2079,6 +2079,10 @@ function captureFeedback(params, options = {}) {
|
|
|
2079
2079
|
try {
|
|
2080
2080
|
const autoPromote = require('./auto-promote-gates');
|
|
2081
2081
|
const promoteResult = autoPromote.promote(FEEDBACK_LOG_PATH, { gateAction: feedbackEvent.gateAction });
|
|
2082
|
+
// Free tier: a 4th learned rule is stored but not enforced. Say so once, in one line.
|
|
2083
|
+
if (promoteResult && promoteResult.upgradeLine && !tenantDataScope()) {
|
|
2084
|
+
process.stderr.write(`${promoteResult.upgradeLine}\n`);
|
|
2085
|
+
}
|
|
2082
2086
|
// First-rule activation telemetry: anonymous ping the first time
|
|
2083
2087
|
// a prevention rule auto-promotes for this install. Idempotent —
|
|
2084
2088
|
// see scripts/activation-tracker.js. Critical for activation funnel
|
|
@@ -2446,7 +2450,10 @@ function analyzeFeedback(logPath, options = {}) {
|
|
|
2446
2450
|
if (options.projectKey != null) entries = require('./project-catalog').readProjectRows(feedbackDir, 'feedback-log.jsonl', options);
|
|
2447
2451
|
const rawTotal = entries.length;
|
|
2448
2452
|
if (options.humanOnly) {
|
|
2449
|
-
|
|
2453
|
+
// strictHuman (status line) also drops entries scraped from prompt text.
|
|
2454
|
+
entries = options.strictHuman
|
|
2455
|
+
? entries.filter((entry) => require('./human-feedback').isCountedHumanFeedback(entry))
|
|
2456
|
+
: entries.filter((entry) => normalizeReviewOrigin(entry.reviewOrigin) === 'human');
|
|
2450
2457
|
}
|
|
2451
2458
|
const fallback = getSQLiteFallback(useSQLite, entries);
|
|
2452
2459
|
if (fallback) return fallback;
|
|
@@ -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
|
+
};
|
package/scripts/gates-engine.js
CHANGED
|
@@ -16,7 +16,7 @@ const crypto = require('crypto');
|
|
|
16
16
|
const { execFileSync, spawnSync } = require('child_process');
|
|
17
17
|
const { loadOptionalModule } = require('./private-core-boundary');
|
|
18
18
|
|
|
19
|
-
const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES
|
|
19
|
+
const { isProTier, isInTrialPeriod, FREE_TIER_MAX_GATES } = require('./rate-limiter');
|
|
20
20
|
const {
|
|
21
21
|
DEFAULT_BASE_BRANCH,
|
|
22
22
|
evaluateOperationalIntegrity,
|
|
@@ -186,10 +186,9 @@ const SELF_PROTECT_HARD_FLOOR_GATE_IDS = new Set([
|
|
|
186
186
|
'self-protect-hooks-disable',
|
|
187
187
|
]);
|
|
188
188
|
// An expired task-scope lease gets its OWN gate id so it can be exempted from the two downgrade
|
|
189
|
-
//
|
|
190
|
-
// cosmetic: applyEnforcementPosture turns denials into warnings by default,
|
|
191
|
-
//
|
|
192
|
-
// A lease that stops binding when you are busy or over quota is not a lease.
|
|
189
|
+
// posture downgrade without touching ordinary task-scope denials. Without this the fail-closed
|
|
190
|
+
// guarantee is cosmetic: applyEnforcementPosture turns denials into warnings by default, so an
|
|
191
|
+
// edit under a lapsed lease would execute anyway. A lease that stops binding is not a lease.
|
|
193
192
|
const TASK_SCOPE_LEASE_EXPIRED_GATE_ID = 'task-scope-lease-expired';
|
|
194
193
|
|
|
195
194
|
const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
|
|
@@ -214,19 +213,20 @@ const UNCONDITIONAL_HARD_FLOOR_GATE_IDS = new Set([
|
|
|
214
213
|
'teams-single-reply-per-message',
|
|
215
214
|
'az-repos-pr-publish-requires-cross-review',
|
|
216
215
|
'mabl-failure-honesty',
|
|
216
|
+
// Catastrophic, effectively irreversible commands (issue #2782). A default install
|
|
217
|
+
// (no THUMBGATE_* variables) must deny these, same as secret exfiltration.
|
|
218
|
+
'force-push',
|
|
219
|
+
'git-reset-hard',
|
|
220
|
+
'git-clean-force',
|
|
221
|
+
'rm-rf-home-or-root',
|
|
222
|
+
'db-drop-table-production',
|
|
217
223
|
TASK_SCOPE_LEASE_EXPIRED_GATE_ID,
|
|
218
224
|
...SELF_PROTECT_HARD_FLOOR_GATE_IDS,
|
|
219
225
|
]);
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
// A free-tier user past their daily cap could have `rm -rf ~`, a force push,
|
|
225
|
-
// `git reset --hard`, or `git clean -f` silently allowed through. These four
|
|
226
|
-
// map directly to CLAUDE.md's own hard-block list and must never be subject
|
|
227
|
-
// to the daily cap discount, regardless of tier or strict-mode setting.
|
|
228
|
-
// financial-control is included for the same reason: a daily-cap discount on
|
|
229
|
-
// checkout/subscription spends would re-open the never-spend interlock.
|
|
226
|
+
// Catastrophic, effectively irreversible commands (issue #2782): `rm -rf ~`, a
|
|
227
|
+
// force push, `git reset --hard`, `git clean -f`, spend paths. These are
|
|
228
|
+
// evaluated before posture and are never downgraded to a warning, regardless
|
|
229
|
+
// of tier or strict-mode setting.
|
|
230
230
|
const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
|
|
231
231
|
TASK_SCOPE_LEASE_EXPIRED_GATE_ID,
|
|
232
232
|
'force-push',
|
|
@@ -238,13 +238,14 @@ const CATASTROPHIC_DECLARATIVE_GATE_IDS = new Set([
|
|
|
238
238
|
'financial-control',
|
|
239
239
|
'oneshot-control',
|
|
240
240
|
'oneshot-goal-done',
|
|
241
|
-
//
|
|
241
|
+
// A denied autonomous email send is the same class as force-push.
|
|
242
242
|
'outbound-email-send',
|
|
243
243
|
'outbound-off-brand-vertical-block',
|
|
244
244
|
'swarm-claim-exit-3-write-after-loss',
|
|
245
245
|
'teams-single-reply-per-message',
|
|
246
246
|
'az-repos-pr-publish-requires-cross-review',
|
|
247
247
|
'mabl-failure-honesty',
|
|
248
|
+
'db-drop-table-production',
|
|
248
249
|
]);
|
|
249
250
|
const SELF_PROTECT_CONFIG_TARGET_PATTERN = /(?:^|\/)(?:config\/gates\/|config\/(?:budget|enforcement|mcp-allowlists)\.json$|\.thumbgate\/config\.json$|thumbgate\.json$)/i;
|
|
250
251
|
const SELF_PROTECT_HOOK_TARGET_PATTERN = /(?:^|\/)(?:\.claude\/settings(?:\.local)?\.json|\.codex\/config\.toml|scripts\/hook-[^/]+\.(?:js|sh))$/i;
|
|
@@ -285,6 +286,11 @@ function alignmentLayerForResult(result) {
|
|
|
285
286
|
return 'business';
|
|
286
287
|
}
|
|
287
288
|
|
|
289
|
+
// A downgraded gate warns and the action runs, so its text must not say "blocked".
|
|
290
|
+
function describeAsFlagged(message) {
|
|
291
|
+
return String(message || '').replace(/\bblocked\b/gi, 'flagged');
|
|
292
|
+
}
|
|
293
|
+
|
|
288
294
|
function applyEnforcementPosture(result) {
|
|
289
295
|
if (!result || (result.decision !== 'deny' && result.decision !== 'approve')) return result;
|
|
290
296
|
const mode = resolveGovernanceMode();
|
|
@@ -304,7 +310,7 @@ function applyEnforcementPosture(result) {
|
|
|
304
310
|
governanceMode: mode,
|
|
305
311
|
alignmentLayer,
|
|
306
312
|
simulated: true,
|
|
307
|
-
message: `${result.message}\n\n⚠️ ThumbGate governance mode=${mode} — flagged and logged, not blocked.`,
|
|
313
|
+
message: `${describeAsFlagged(result.message)}\n\n⚠️ ThumbGate governance mode=${mode} — flagged and logged, not blocked.`,
|
|
308
314
|
};
|
|
309
315
|
}
|
|
310
316
|
return { ...result, governanceMode: mode, alignmentLayer, simulated: true };
|
|
@@ -325,7 +331,7 @@ function applyEnforcementPosture(result) {
|
|
|
325
331
|
warnByDefault: true,
|
|
326
332
|
governanceMode: 'sidecar',
|
|
327
333
|
alignmentLayer,
|
|
328
|
-
message: `${result.message}\n\n⚠️ ThumbGate is in warn-by-default mode (sidecar) — this was flagged and logged, not blocked. Set THUMBGATE_STRICT_ENFORCEMENT=1 or THUMBGATE_GOVERNANCE_MODE=live to hard-block other flagged actions.`,
|
|
334
|
+
message: `${describeAsFlagged(result.message)}\n\n⚠️ ThumbGate is in warn-by-default mode (sidecar) — this was flagged and logged, not blocked. Set THUMBGATE_STRICT_ENFORCEMENT=1 or THUMBGATE_GOVERNANCE_MODE=live to hard-block other flagged actions.`,
|
|
329
335
|
};
|
|
330
336
|
}
|
|
331
337
|
const BREAK_GLASS_CONDITION = 'thumbgate_break_glass';
|
|
@@ -1148,75 +1154,6 @@ function recordStat(gateId, action, gate, options = {}) {
|
|
|
1148
1154
|
}
|
|
1149
1155
|
}
|
|
1150
1156
|
|
|
1151
|
-
// ---------------------------------------------------------------------------
|
|
1152
|
-
// Free-tier daily block cap
|
|
1153
|
-
// ---------------------------------------------------------------------------
|
|
1154
|
-
|
|
1155
|
-
/**
|
|
1156
|
-
* Count today's gate blocks from stats. Free tier gets FREE_TIER_DAILY_BLOCKS
|
|
1157
|
-
* blocks/day. After the limit, deny → warn + upgrade CTA so the action proceeds
|
|
1158
|
-
* but the user sees they lost protection.
|
|
1159
|
-
*/
|
|
1160
|
-
function getTodayBlockCount() {
|
|
1161
|
-
const stats = loadStats();
|
|
1162
|
-
const today = todayKey();
|
|
1163
|
-
if (!stats.dailyBlocks || !stats.dailyBlocks[today]) return 0;
|
|
1164
|
-
return stats.dailyBlocks[today];
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
function incrementTodayBlockCount() {
|
|
1168
|
-
const stats = loadStats();
|
|
1169
|
-
const today = todayKey();
|
|
1170
|
-
if (!stats.dailyBlocks) stats.dailyBlocks = {};
|
|
1171
|
-
// Clean old dates (keep only last 7 days to prevent unbounded growth)
|
|
1172
|
-
const keys = Object.keys(stats.dailyBlocks);
|
|
1173
|
-
if (keys.length > 7) {
|
|
1174
|
-
keys.sort();
|
|
1175
|
-
for (const k of keys.slice(0, keys.length - 7)) {
|
|
1176
|
-
delete stats.dailyBlocks[k];
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
stats.dailyBlocks[today] = (stats.dailyBlocks[today] || 0) + 1;
|
|
1180
|
-
saveStats(stats);
|
|
1181
|
-
return stats.dailyBlocks[today];
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
/**
|
|
1185
|
-
* If the user is free-tier and has exceeded daily block limit, downgrade
|
|
1186
|
-
* a deny result to a warn with an upgrade CTA. Returns null if no cap applies.
|
|
1187
|
-
*/
|
|
1188
|
-
function applyDailyBlockCap(denyResult) {
|
|
1189
|
-
if (process.env.THUMBGATE_SANDBOX_EVAL === '1') return null;
|
|
1190
|
-
// Catastrophic/irreversible commands (force-push, git reset --hard, git
|
|
1191
|
-
// clean -f, rm -rf on home/root) never get the free-tier daily-cap
|
|
1192
|
-
// discount — see issue #2782. Checked first, before any tier/CI shortcut,
|
|
1193
|
-
// so nothing can accidentally exempt a catastrophic gate from this floor.
|
|
1194
|
-
if (denyResult && CATASTROPHIC_DECLARATIVE_GATE_IDS.has(denyResult.gate)) return null;
|
|
1195
|
-
// Pro, trial, CI, and THUMBGATE_NO_RATE_LIMIT users are uncapped
|
|
1196
|
-
if (isProTier()) return null;
|
|
1197
|
-
if (process.env.CI || process.env.GITHUB_ACTIONS) return null;
|
|
1198
|
-
|
|
1199
|
-
const todayCount = getTodayBlockCount();
|
|
1200
|
-
if (todayCount < FREE_TIER_DAILY_BLOCKS) {
|
|
1201
|
-
// Under limit: allow the block, increment counter
|
|
1202
|
-
incrementTodayBlockCount();
|
|
1203
|
-
return null;
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
// Over limit: downgrade deny → warn with upgrade CTA
|
|
1207
|
-
const remaining = 0;
|
|
1208
|
-
return {
|
|
1209
|
-
decision: 'warn',
|
|
1210
|
-
gate: denyResult.gate,
|
|
1211
|
-
message: `⚠️ ${denyResult.message}\n\n🔓 Daily protection limit reached (${FREE_TIER_DAILY_BLOCKS}/${FREE_TIER_DAILY_BLOCKS} blocks used). This action was allowed through. Upgrade for unlimited protection: https://thumbgate.ai/go/pro`,
|
|
1212
|
-
severity: denyResult.severity,
|
|
1213
|
-
reasoning: (denyResult.reasoning || []).concat([
|
|
1214
|
-
`Free-tier daily block limit (${FREE_TIER_DAILY_BLOCKS}) exceeded — deny downgraded to warn`,
|
|
1215
|
-
]),
|
|
1216
|
-
dailyBlockCapApplied: true,
|
|
1217
|
-
};
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
1157
|
// ---------------------------------------------------------------------------
|
|
1221
1158
|
// Reasoning chain builder
|
|
1222
1159
|
// ---------------------------------------------------------------------------
|
|
@@ -2464,8 +2401,8 @@ function recordStructuralGateBlock(toolName, toolInput, result, options = {}) {
|
|
|
2464
2401
|
* Config order is useful for normal policy routing, but it must not let a broad
|
|
2465
2402
|
* rule mask a narrower irreversible-action rule. For example, the generic
|
|
2466
2403
|
* `push-without-thread-check` gate also matches `git push --force`; selecting it
|
|
2467
|
-
* first
|
|
2468
|
-
*
|
|
2404
|
+
* first let a downgrade path turn the action into a warning before the
|
|
2405
|
+
* `force-push` gate was ever evaluated.
|
|
2469
2406
|
*
|
|
2470
2407
|
* Catastrophic gates are deliberately limited to the audited allowlist above.
|
|
2471
2408
|
* Metric-backed gates are excluded because their condition is asynchronous and
|
|
@@ -3885,14 +3822,6 @@ async function evaluateGatesAsyncInner(toolName, toolInput, configPath, options
|
|
|
3885
3822
|
reasoning,
|
|
3886
3823
|
...(adminOverride ? { requiresAdminOverride: true, adminOverride } : {}),
|
|
3887
3824
|
};
|
|
3888
|
-
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
3889
|
-
const cappedResult = applyDailyBlockCap(denyResult);
|
|
3890
|
-
if (cappedResult) {
|
|
3891
|
-
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
3892
|
-
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
3893
|
-
auditToFeedback(auditRecord, execution);
|
|
3894
|
-
return cappedResult;
|
|
3895
|
-
}
|
|
3896
3825
|
recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
|
|
3897
3826
|
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
3898
3827
|
auditToFeedback(auditRecord, execution);
|
|
@@ -4206,14 +4135,6 @@ function evaluateGatesInner(toolName, toolInput, configPath, options = {}) {
|
|
|
4206
4135
|
reasoning,
|
|
4207
4136
|
...(adminOverride ? { requiresAdminOverride: true, adminOverride } : {}),
|
|
4208
4137
|
};
|
|
4209
|
-
// Free-tier daily block cap: after N blocks/day, deny → warn + upgrade CTA
|
|
4210
|
-
const cappedResult = applyDailyBlockCap(denyResult);
|
|
4211
|
-
if (cappedResult) {
|
|
4212
|
-
recordStat(gate.id, 'warn', gate, { ...execution, toolName, toolInput });
|
|
4213
|
-
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'warn', gateId: gate.id, message: cappedResult.message, severity: gate.severity, source: 'gates-engine', dailyBlockCapApplied: true });
|
|
4214
|
-
auditToFeedback(auditRecord, execution);
|
|
4215
|
-
return cappedResult;
|
|
4216
|
-
}
|
|
4217
4138
|
recordStat(gate.id, 'block', gate, { ...execution, toolName, toolInput });
|
|
4218
4139
|
const auditRecord = recordAuditEvent({ ...execution, toolName, toolInput, decision: 'deny', gateId: gate.id, message: overrideMessage, severity: gate.severity, source: 'gates-engine' });
|
|
4219
4140
|
auditToFeedback(auditRecord, execution);
|
|
@@ -5513,7 +5434,18 @@ function buildDesignSelfCorrectionContext(toolName, toolInput = {}) {
|
|
|
5513
5434
|
}
|
|
5514
5435
|
}
|
|
5515
5436
|
|
|
5437
|
+
// Hook-facing entry. The first real block (then at most once per 7 days) carries one upgrade line in
|
|
5438
|
+
// the host-shown `systemMessage`; the reason the model reads is untouched. See first-block-upsell.js.
|
|
5516
5439
|
async function runAsync(rawInput) {
|
|
5440
|
+
const output = await runAsyncCore(rawInput);
|
|
5441
|
+
try {
|
|
5442
|
+
return require('./first-block-upsell').withFirstBlockUpsell(output);
|
|
5443
|
+
} catch {
|
|
5444
|
+
return output;
|
|
5445
|
+
}
|
|
5446
|
+
}
|
|
5447
|
+
|
|
5448
|
+
async function runAsyncCore(rawInput) {
|
|
5517
5449
|
const input = canonicalizeHookInput(rawInput);
|
|
5518
5450
|
const { hardFloor, securityScan } = evaluateUnconditionalHardFloor(input);
|
|
5519
5451
|
if (hardFloor) return formatOutput(hardFloor);
|
|
@@ -6213,9 +6145,6 @@ module.exports = {
|
|
|
6213
6145
|
PR_THREAD_RESOLUTION_ACTION,
|
|
6214
6146
|
HELPER_BYPASS_ACTION,
|
|
6215
6147
|
buildBlockActionProCta,
|
|
6216
|
-
applyDailyBlockCap,
|
|
6217
|
-
getTodayBlockCount,
|
|
6218
|
-
incrementTodayBlockCount,
|
|
6219
6148
|
effectiveCommandCwd,
|
|
6220
6149
|
resolveRepoRoot,
|
|
6221
6150
|
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// A status-line thumb counts only when a person gave it. `reviewOrigin: human`
|
|
4
|
+
// alone is not enough: the Claude-history sync and the auto-capture hook write
|
|
5
|
+
// entries with that origin from text they scraped, not from a deliberate click or
|
|
6
|
+
// capture_feedback call.
|
|
7
|
+
const NON_HUMAN_TAGS = new Set([
|
|
8
|
+
'claude-history-sync',
|
|
9
|
+
'auto-capture-fallback',
|
|
10
|
+
'auto-capture',
|
|
11
|
+
'auto-hook',
|
|
12
|
+
'automated',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
function isCountedHumanFeedback(entry) {
|
|
16
|
+
if (!entry || String(entry.reviewOrigin || '').trim().toLowerCase() !== 'human') return false;
|
|
17
|
+
const tags = Array.isArray(entry.tags) ? entry.tags : [];
|
|
18
|
+
if (tags.some((tag) => NON_HUMAN_TAGS.has(String(tag).trim().toLowerCase()))) return false;
|
|
19
|
+
const source = String(entry.memorySource || entry.source || '').trim().toLowerCase();
|
|
20
|
+
return !NON_HUMAN_TAGS.has(source);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Before #5119 the MCP server stamped every capture_feedback call
|
|
24
|
+
// `reviewOrigin: automated`, so a thumb the agent recorded for the person sits in
|
|
25
|
+
// the log looking like a script's entry. Such a row is recognisable by what the
|
|
26
|
+
// capture tool writes and scripts and hooks do not: a store-learning or
|
|
27
|
+
// store-mistake action inside an agent session, with no source marker and no
|
|
28
|
+
// scraper tag. Rows from the shared store only count for the project named in
|
|
29
|
+
// scope.projectId, which the caller checks.
|
|
30
|
+
const MCP_CAPTURE_ACTIONS = new Set(['store-learning', 'store-mistake']);
|
|
31
|
+
|
|
32
|
+
function isLegacyMcpCapture(entry) {
|
|
33
|
+
if (!entry || String(entry.reviewOrigin || '').trim().toLowerCase() !== 'automated') return false;
|
|
34
|
+
if (!MCP_CAPTURE_ACTIONS.has(String(entry.actionType || ''))) return false;
|
|
35
|
+
const sessionId = entry.scope && entry.scope.sessionId;
|
|
36
|
+
if (typeof sessionId !== 'string' || !sessionId.startsWith('session_')) return false;
|
|
37
|
+
if (entry.memorySource || entry.source || entry.sourceEvent) return false;
|
|
38
|
+
const tags = Array.isArray(entry.tags) ? entry.tags : [];
|
|
39
|
+
return !tags.some((tag) => NON_HUMAN_TAGS.has(String(tag).trim().toLowerCase()));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { NON_HUMAN_TAGS, isCountedHumanFeedback, isLegacyMcpCapture };
|