thumbgate 1.40.12 → 1.40.14

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.
@@ -140,7 +140,7 @@ __GA_BOOTSTRAP__
140
140
  <a class="btn-secondary" href="/diagnostic?utm_source=install_page&utm_medium=owned_page&utm_campaign=marketplace_distribution">$499 Setup Sprint (separate)</a>
141
141
  </div>
142
142
  <div class="proof-strip" aria-label="Verified live distribution surfaces">
143
- <div class="proof"><strong>npm</strong><span>thumbgate@1.40.12</span></div>
143
+ <div class="proof"><strong>npm</strong><span>thumbgate@1.40.14</span></div>
144
144
  <div class="proof"><strong>VS Code</strong><span>Marketplace version live</span></div>
145
145
  <div class="proof"><strong>Open VSX</strong><span>Antigravity-compatible path</span></div>
146
146
  <div class="proof"><strong>MCP Registry</strong><span>1.39.1 is latest</span></div>
@@ -154,12 +154,12 @@ __GA_BOOTSTRAP__
154
154
  <p class="section-lede">Use the local CLI path for immediate enforcement. Use marketplace installs where your editor supports them. Use the diagnostic path when you need a human-reviewed gate map for one risky workflow. New install: <a href="/guides/progressive-wiring">prove the pipe first</a> (doctor green, empty dashboard OK) before expecting a gate to fire.</p>
155
155
  <div class="grid">
156
156
  <article class="card" id="quickstart"><h3>First gate block in one command</h3><p>Promote your first prevention rule and watch ThumbGate stop a repeat mistake. Free includes the built-in rules and 3 learned rules, after a 7-day local Pro trial.</p><pre><code>npx thumbgate quickstart</code></pre></article>
157
- <article class="card"><h3>CLI and MCP-compatible agents</h3><p>Fastest path for Claude Code, Cursor, Codex, Gemini CLI, Amp, Cline, OpenCode, and local MCP-compatible agents.</p><pre><code>npx -y thumbgate@1.40.12 init --agent claude
158
- npx -y thumbgate@1.40.12 doctor
159
- npx -y thumbgate@1.40.12 doctor --fix</code></pre></article>
160
- <article class="card"><h3>Claude Desktop</h3><p>Use the npm-backed MCP server today. The Claude Desktop `.mcpb` directory submission packet is prepared separately.</p><pre><code>claude mcp add thumbgate -- npx --yes --package thumbgate@1.40.12 thumbgate serve</code></pre></article>
161
- <article class="card"><h3>Cursor</h3><p>The public Cursor Marketplace listing is not live yet. Use the CLI wiring while the dashboard submission is resolved.</p><pre><code>npx -y thumbgate@1.40.12 init --agent cursor</code></pre></article>
162
- <article class="card"><h3>Codex</h3><p>Use the local adapter now. Public Codex self-serve plugin publishing is not open yet, so the GitHub Release asset is the distribution proof.</p><pre><code>npx -y thumbgate@1.40.12 init --agent codex</code></pre></article>
157
+ <article class="card"><h3>CLI and MCP-compatible agents</h3><p>Fastest path for Claude Code, Cursor, Codex, Gemini CLI, Amp, Cline, OpenCode, and local MCP-compatible agents.</p><pre><code>npx -y thumbgate@1.40.14 init --agent claude
158
+ npx -y thumbgate@1.40.14 doctor
159
+ npx -y thumbgate@1.40.14 doctor --fix</code></pre></article>
160
+ <article class="card"><h3>Claude Desktop</h3><p>Use the npm-backed MCP server today. The Claude Desktop `.mcpb` directory submission packet is prepared separately.</p><pre><code>claude mcp add thumbgate -- npx --yes --package thumbgate@1.40.14 thumbgate serve</code></pre></article>
161
+ <article class="card"><h3>Cursor</h3><p>The public Cursor Marketplace listing is not live yet. Use the CLI wiring while the dashboard submission is resolved.</p><pre><code>npx -y thumbgate@1.40.14 init --agent cursor</code></pre></article>
162
+ <article class="card"><h3>Codex</h3><p>Use the local adapter now. Public Codex self-serve plugin publishing is not open yet, so the GitHub Release asset is the distribution proof.</p><pre><code>npx -y thumbgate@1.40.14 init --agent codex</code></pre></article>
163
163
  <article class="card" id="grok"><h3>Grok</h3><p>Grok Build CLI. There is no Grok store listing. This command adds the npm server. <code>npx thumbgate init</code> also writes the Claude-style config Grok reads.</p><pre><code>grok mcp add thumbgate -- npx -y thumbgate mcp</code></pre></article>
164
164
  <article class="card" id="hermes"><h3>Hermes</h3><p>Local hook for Nous Research Hermes. Merge <code>adapters/hermes/config.yaml</code> into <code>~/.hermes/config.yaml</code>. There is no Hermes directory listing.</p><pre><code>npx --yes --package thumbgate thumbgate hermes-gate</code></pre></article>
165
165
  </div>
@@ -170,7 +170,7 @@ npx -y thumbgate@1.40.12 doctor --fix</code></pre></article>
170
170
  <h2>Verified public surfaces.</h2>
171
171
  <p class="section-lede">These are the surfaces safe to claim in public copy right now. Pending surfaces are listed so buyers do not get sent to dead marketplace pages.</p>
172
172
  <div class="status-list">
173
- <div class="status"><span class="badge live">LIVE</span><div><strong><a href="https://www.npmjs.com/package/thumbgate">npm package</a></strong><span>`thumbgate@1.40.12` is the canonical runtime install.</span></div></div>
173
+ <div class="status"><span class="badge live">LIVE</span><div><strong><a href="https://www.npmjs.com/package/thumbgate">npm package</a></strong><span>`thumbgate@1.40.14` is the canonical runtime install.</span></div></div>
174
174
  <div class="status"><span class="badge live">LIVE</span><div><strong><a href="https://marketplace.visualstudio.com/items?itemName=igorganapolsky.thumbgate">VS Code Marketplace</a></strong><span>Latest Marketplace version is `1.28.1`, behind npm. For the current version, use Open VSX or the GitHub Release VSIX.</span></div></div>
175
175
  <div class="status"><span class="badge live">LIVE</span><div><strong><a href="https://open-vsx.org/extension/igorganapolsky/thumbgate">Open VSX</a></strong><span>Public registry latest version is `1.40.10`; use this path for VS Code-compatible IDEs that consume Open VSX.</span></div></div>
176
176
  <div class="status"><span class="badge live">LIVE</span><div><strong><a href="https://registry.modelcontextprotocol.io/v0/servers?search=thumbgate">MCP Registry</a></strong><span>Public search returns `io.github.IgorGanapolsky/thumbgate` version `1.39.1` as latest.</span></div></div>
package/public/learn.html CHANGED
@@ -311,6 +311,14 @@
311
311
  </div>
312
312
 
313
313
  <div class="article-grid">
314
+ <a href="/learn/ai-finops-agent-spend-guardrails" class="article-card">
315
+ <h3>AI FinOps for Coding Agents: Where a Pre-Action Gate Helps With Spend</h3>
316
+ <p>98% of FinOps survey respondents now manage AI spend. Agents add a new cost: actions that spend money on their own. What a gate covers, and what it does not.</p>
317
+ <span class="article-tag">AI FinOps</span>
318
+ <span class="article-tag">Agent Spend</span>
319
+ <span class="article-tag">Pre-Action Gates</span>
320
+ </a>
321
+
314
322
  <a href="/learn/okta-mcp-governance-per-tool-call-gates" class="article-card">
315
323
  <h3>Okta Governs the MCP Connection. Who Gates the Tool Call?</h3>
316
324
  <p>Okta for AI Agents puts agent registration and MCP servers under one policy. A connection grant still lets every tool on the server run. ThumbGate gates each call before it fires.</p>
@@ -26,7 +26,7 @@
26
26
  "alternateName": "thumbgate",
27
27
  "applicationCategory": "DeveloperApplication",
28
28
  "operatingSystem": "Cross-platform, Node.js >=18.18.0",
29
- "softwareVersion": "1.40.12",
29
+ "softwareVersion": "1.40.14",
30
30
  "url": "https://thumbgate-production.up.railway.app/numbers",
31
31
  "dateModified": "2026-11-12",
32
32
  "creator": {
@@ -201,7 +201,7 @@
201
201
  <main class="container">
202
202
  <h1>The Numbers</h1>
203
203
  <p class="subtitle">Generated first-party operational snapshot from the ThumbGate runtime. This is not customer traction, install volume, revenue, or proof that a configured gate has fired.</p>
204
- <div class="freshness">Updated: 2026-11-12 · Version 1.40.12</div>
204
+ <div class="freshness">Updated: 2026-11-12 · Version 1.40.14</div>
205
205
  <div class="truth-note"><strong>Read this first:</strong> configured checks are inventory. Recorded blocks and warnings are usage evidence. This snapshot currently reports 8,602 recorded hard-block event(s) and 2 recorded warning event(s).</div>
206
206
 
207
207
  <h2>Gate enforcement</h2>
@@ -5,6 +5,9 @@
5
5
  if (selected === 'all') selected = null;
6
6
  var selectedDir = selected ? new URL(window.location.href).searchParams.get('projectDir') : null;
7
7
  var loading = null;
8
+ // The folder this page was opened for, if the URL names one; the server judges that folder (else its own).
9
+ var pageDir = new URL(window.location.href).searchParams.get('projectDir');
10
+ var folderQuery = pageDir ? '?projectDir=' + encodeURIComponent(pageDir) : '';
8
11
  function url(input) {
9
12
  var target = new URL(input, window.location.origin);
10
13
  if (target.origin !== window.location.origin) return target.href;
@@ -49,14 +52,17 @@
49
52
  function refresh(headers) {
50
53
  mount();
51
54
  if (loading) return loading;
52
- loading = fetch('/v1/projects', { credentials: 'include', headers: headers || {} }).then(function (response) { if (!response.ok) throw new Error('Projects unavailable'); return response.json(); }).then(function (data) {
55
+ loading = fetch('/v1/projects' + folderQuery, { credentials: 'include', headers: headers || {} }).then(function (response) { if (!response.ok) throw new Error('Projects unavailable'); return response.json(); }).then(function (data) {
53
56
  var select = document.getElementById('projectSwitcher');
54
57
  while (select.options.length > 1) select.remove(1);
55
58
  var projects = Array.isArray(data.projects) ? data.projects : [];
56
59
  if (selected && !projects.some(function (project) { return project.projectKey === selected; })) projects.push({ projectKey: selected, projectName: selectedDir ? selectedDir.split('/').filter(Boolean).pop() : 'Project with no recorded activity', counts: {} });
57
60
  // Leftover identities with nothing recorded are not worth a pick: hide them and say how many.
58
61
  // A bare dashboard URL opens on a project; "All projects" is an explicit pick (project=all).
59
- if (!explicit) {
62
+ // A folder with no git remote (for example ~/workspace) is not a project: stay on All projects instead of jumping to the most recent one.
63
+ var nonProject = data.projectDirIsProject === false;
64
+ var inNonProject = nonProject && !explicit;
65
+ if (!explicit && !inNonProject) {
60
66
  var recent = projects.filter(function (project) { return isRealProject(project) && project.lastActivity; }).sort(function (a, b) { return new Date(b.lastActivity) - new Date(a.lastActivity); })[0];
61
67
  if (recent) { var next = new URL(window.location.href); next.searchParams.set('project', recent.projectKey); if (data.projectDir) next.searchParams.set('projectDir', data.projectDir); window.location.replace(next.href); return; }
62
68
  }
@@ -66,7 +72,8 @@
66
72
  select.value = selected || '';
67
73
  var current = projects.find(function (project) { return project.projectKey === selected; });
68
74
  var where = selectedDir ? selectedDir.replace(/^\/Users\/[^/]+/, '~') : '';
69
- document.getElementById('projectStatus').textContent = current ? displayName(current) + (where ? ' · ' + where : '') : 'All projects: account-wide, mixes every project. Pick a project for its own numbers.';
75
+ var folder = nonProject && data.projectDir ? String(data.projectDir).replace(/^\/Users\/[^/]+/, '~') : '';
76
+ document.getElementById('projectStatus').textContent = current ? displayName(current) + (where ? ' · ' + where : '') : folder ? 'All projects · you are in ' + folder + ' (not a project)' : 'All projects: account-wide, mixes every project. Pick a project for its own numbers.';
70
77
  document.getElementById('projectGlobalGates').textContent = (data.globalGateCount || 0) + ' global gates shared across projects';
71
78
  var cards = document.getElementById('projectCards'); cards.replaceChildren();
72
79
  if (!selected) shown.forEach(function (project) {
@@ -24,6 +24,7 @@
24
24
  * is a no-op for the lifetime of that install.
25
25
  */
26
26
 
27
+ const crypto = require('node:crypto');
27
28
  const fs = require('node:fs');
28
29
  const { spawn } = require('node:child_process');
29
30
  const http = require('node:http');
@@ -186,6 +187,11 @@ function resolveActivationAccountAuth(options = {}) {
186
187
  return { apiKey, apiBaseUrl };
187
188
  }
188
189
 
190
+ // A short one-way fingerprint, so the marker file never stores the key itself.
191
+ function hashKeyForMarker(apiKey) {
192
+ return crypto.createHash('sha256').update(String(apiKey)).digest('hex').slice(0, 16);
193
+ }
194
+
189
195
  function postActivationEvent(endpointUrl, apiKey, bodyObj, awaitDelivery = false) {
190
196
  const payload = JSON.stringify(bodyObj);
191
197
  const parsed = new URL(endpointUrl);
@@ -248,7 +254,13 @@ function reportFirstBlockActivation(metadata = {}) {
248
254
  const firstBlockAt = existing.firstBlockAt || metadata.firstBlockAt || existing.blockedAt || new Date().toISOString();
249
255
  const { apiKey, apiBaseUrl } = resolveActivationAccountAuth(metadata);
250
256
 
251
- if (existing.firstBlockReportedAt || (!apiKey && existing.firstBlockAnonReportedAt)) {
257
+ const keyAlreadyRejected = Boolean(
258
+ apiKey
259
+ && existing.firstBlockAnonReportedAt
260
+ && existing.firstBlockAuthRejectedKeyHash
261
+ && existing.firstBlockAuthRejectedKeyHash === hashKeyForMarker(apiKey)
262
+ );
263
+ if (existing.firstBlockReportedAt || (!apiKey && existing.firstBlockAnonReportedAt) || keyAlreadyRejected) {
252
264
  if (!existing.firstBlockAt || existing.event !== 'first_block') {
253
265
  writeJsonSafe(markerPath, { ...existing, firstBlockAt, event: 'first_block', at: existing.at || firstBlockAt });
254
266
  }
@@ -283,6 +295,8 @@ function reportFirstBlockActivation(metadata = {}) {
283
295
  clientType: 'cli',
284
296
  firstBlockAt,
285
297
  installId,
298
+ // Without this the server classifies the event by User-Agent (node sends none) as a bot.
299
+ visitorType: (() => { try { return classifyInstall(); } catch { return undefined; } })(),
286
300
  ...(gateId ? { gateId: String(gateId).slice(0, 120) } : {}),
287
301
  };
288
302
 
@@ -292,6 +306,27 @@ function reportFirstBlockActivation(metadata = {}) {
292
306
  ? `${apiBaseUrl}/v1/activation/first-block`
293
307
  : `${apiBaseUrl}/v1/telemetry/ping`;
294
308
  return postActivationEvent(targetUrl, apiKey, eventPayload, true).then((res) => {
309
+ if (!res.ok && apiKey && (res.statusCode === 401 || res.statusCode === 403)) {
310
+ // The stored key no longer authenticates (rotated operator key, expired
311
+ // trial, wrong host). Don't lose the activation: report it anonymously,
312
+ // and remember the rejected key so every later gate firing stops retrying
313
+ // the account route with it.
314
+ const rejectedKeyHash = hashKeyForMarker(apiKey);
315
+ return postActivationEvent(`${apiBaseUrl}/v1/telemetry/ping`, '', eventPayload, true).then((anon) => {
316
+ const latest = readJsonSafe(markerPath) || nextMarker;
317
+ const stamp = new Date().toISOString();
318
+ writeJsonSafe(markerPath, {
319
+ ...latest,
320
+ at: latest.at || firstBlockAt,
321
+ firstBlockAt: latest.firstBlockAt || firstBlockAt,
322
+ event: 'first_block',
323
+ firstBlockAuthRejectedKeyHash: rejectedKeyHash,
324
+ firstBlockAuthRejectedAt: stamp,
325
+ ...(anon.ok ? { firstBlockAnonReportedAt: stamp } : {}),
326
+ });
327
+ return { reported: Boolean(anon.ok), statusCode: res.statusCode, fallback: 'anonymous', firstBlockAt };
328
+ });
329
+ }
295
330
  if (res.ok) {
296
331
  const latest = readJsonSafe(markerPath) || nextMarker;
297
332
  const stamp = new Date().toISOString();
@@ -347,19 +382,84 @@ function extractEntryBlockMinutes(e) {
347
382
  return typeof ms === 'number' && Number.isFinite(ms) ? Math.round((ms / 60_000) * 10) / 10 : null;
348
383
  }
349
384
 
385
+ const FIRST_BLOCK_EVENT_NAMES = new Set(['first_block', 'first_blocked_tool_call']);
386
+ const CHECKOUT_VIEW_EVENTS = new Set(['checkout_interstitial_view']);
387
+ const CHECKOUT_CLICK_EVENTS = new Set(['checkout_interstitial_cta_clicked', 'stripe_redirect_started', 'checkout_start']);
388
+ const CHECKOUT_PAID_EVENTS = new Set(['checkout_success_page_view']);
389
+
390
+ function isInternalEntry(e) {
391
+ return e.visitorType === 'bot' || e.visitorType === 'ci' || e.visitorType === 'owner';
392
+ }
393
+
394
+ function isCliAttributed(e) {
395
+ const source = String(e.utmSource || e.source || '').toLowerCase();
396
+ return source === 'cli' || source.startsWith('cli_');
397
+ }
398
+
399
+ /**
400
+ * The activated -> upgrade-shown -> checkout funnel, counted per install (CLI stages) and per
401
+ * event (web stages that carry utm_source=cli). See docs/decisions/2026-11-24-revenue-funnel-activation.md.
402
+ */
403
+ function summarizeActivationFunnel(entries = []) {
404
+ const installs = new Set();
405
+ const activated = new Set();
406
+ const upsellShown = new Set();
407
+ const limitHit = new Set();
408
+ const funnel = { cliCheckoutViews: 0, cliCheckoutClicks: 0, cliCheckoutPaidPageViews: 0, firstBlockCheckoutViews: 0 };
409
+ for (const e of Array.isArray(entries) ? entries : []) {
410
+ if (!e || isInternalEntry(e)) continue;
411
+ const type = e.eventType || e.event || '';
412
+ if (e.installId && (e.clientType === 'cli' || e.client === 'cli')) installs.add(e.installId);
413
+ if (e.installId && FIRST_BLOCK_EVENT_NAMES.has(type)) activated.add(e.installId);
414
+ if (e.installId && type === 'first_block_upsell_shown') upsellShown.add(e.installId);
415
+ if (e.installId && type === 'cli_limit_hit') limitHit.add(e.installId);
416
+ if (!isCliAttributed(e)) continue;
417
+ if (CHECKOUT_VIEW_EVENTS.has(type)) {
418
+ funnel.cliCheckoutViews += 1;
419
+ if (String(e.utmMedium || '').toLowerCase() === 'first_block') funnel.firstBlockCheckoutViews += 1;
420
+ }
421
+ if (CHECKOUT_CLICK_EVENTS.has(type)) funnel.cliCheckoutClicks += 1;
422
+ if (CHECKOUT_PAID_EVENTS.has(type)) funnel.cliCheckoutPaidPageViews += 1;
423
+ }
424
+ return {
425
+ cliInstalls: installs.size,
426
+ activatedInstalls: activated.size,
427
+ upsellShownInstalls: upsellShown.size,
428
+ limitHitInstalls: limitHit.size,
429
+ ...funnel,
430
+ };
431
+ }
432
+
350
433
  function summarizeFirstBlockEvents(entries = []) {
351
434
  if (!Array.isArray(entries) || entries.length === 0) {
352
435
  return { count: 0, medianMinutes: null, under5MinutesCount: 0 };
353
436
  }
354
437
  let count = 0;
355
438
  const minutesList = [];
439
+ // installId -> its timing sample (null until an event for it carries one). The count is per
440
+ // install, but the timing may arrive on a later event of the same install (first_block carries
441
+ // none; first_blocked_tool_call carries minutesSinceInstall), so pick it independently.
442
+ const installTiming = new Map();
356
443
  for (const e of entries) {
357
- if ((e?.eventType || e?.event) !== 'first_blocked_tool_call') continue;
358
- if (e.visitorType === 'bot' || e.visitorType === 'ci') continue;
359
- count += 1;
444
+ // Production CLIs report the activation as `first_block` (reportFirstBlockActivation);
445
+ // older builds sent `first_blocked_tool_call`. Count either, once per install.
446
+ if (!FIRST_BLOCK_EVENT_NAMES.has(e?.eventType || e?.event)) continue;
447
+ if (e.visitorType === 'bot' || e.visitorType === 'ci' || e.visitorType === 'owner') continue;
360
448
  const m = extractEntryBlockMinutes(e);
361
- if (m !== null && m >= 0) minutesList.push(m);
449
+ const sample = m !== null && m >= 0 ? m : null;
450
+ if (e.installId) {
451
+ if (!installTiming.has(e.installId)) {
452
+ installTiming.set(e.installId, sample);
453
+ count += 1;
454
+ } else if (installTiming.get(e.installId) === null && sample !== null) {
455
+ installTiming.set(e.installId, sample);
456
+ }
457
+ continue;
458
+ }
459
+ count += 1;
460
+ if (sample !== null) minutesList.push(sample);
362
461
  }
462
+ for (const sample of installTiming.values()) if (sample !== null) minutesList.push(sample);
363
463
  if (count === 0 || minutesList.length === 0) {
364
464
  return { count, medianMinutes: null, under5MinutesCount: 0 };
365
465
  }
@@ -389,6 +489,7 @@ module.exports = {
389
489
  reportFirstBlockActivation,
390
490
  resolveActivationAccountAuth,
391
491
  summarizeFirstBlockEvents,
492
+ summarizeActivationFunnel,
392
493
  computeDaysSinceInstall,
393
494
  computeMinutesSinceInstall,
394
495
  readMarker,
@@ -4,7 +4,8 @@
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
  const https = require('https');
7
- const { execSync } = require('child_process');
7
+ const os = require('os');
8
+ const { execSync, execFileSync } = require('child_process');
8
9
 
9
10
  const PROJECT_ROOT = path.join(__dirname, '..');
10
11
  const GITHUB_REPO = 'IgorGanapolsky/ThumbGate';
@@ -196,6 +197,104 @@ async function checkUpdate(options = {}) {
196
197
  }
197
198
  }
198
199
 
200
+ // Hook runtime version skew: hooks run the cached ~/.thumbgate/runtime, which never
201
+ // auto-upgrades by design. Detect and report only; never install.
202
+ // See docs/decisions/2026-11-24-revenue-funnel-activation.md (loop 2).
203
+
204
+ const SKEW_REPORT_INTERVAL_MS = 24 * 60 * 60 * 1000;
205
+ const STATE_FILE = 'runtime-skew-reported.json';
206
+ const UPDATE_COMMAND = 'npx thumbgate@latest self-update';
207
+
208
+ function runtimeDir(env = process.env) {
209
+ const home = env.HOME || env.USERPROFILE || os.homedir();
210
+ return path.join(home, '.thumbgate', 'runtime');
211
+ }
212
+
213
+ function readRuntimeVersion(dir = runtimeDir()) {
214
+ try {
215
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', 'thumbgate', 'package.json'), 'utf8'));
216
+ return typeof pkg.version === 'string' ? pkg.version : null;
217
+ } catch {
218
+ return null;
219
+ }
220
+ }
221
+
222
+ function parse(v) {
223
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(String(v || ''));
224
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
225
+ }
226
+
227
+ function isOlder(a, b) {
228
+ const pa = parse(a);
229
+ const pb = parse(b);
230
+ if (!pa || !pb) return false;
231
+ for (let i = 0; i < 3; i += 1) {
232
+ if (pa[i] !== pb[i]) return pa[i] < pb[i];
233
+ }
234
+ return false;
235
+ }
236
+
237
+ /** @returns {{ skewed: boolean, runtimeVersion: string|null, currentVersion: string }} */
238
+ function detectSkew({ currentVersion, dir } = {}) {
239
+ const runtimeVersion = readRuntimeVersion(dir);
240
+ return { skewed: Boolean(runtimeVersion && isOlder(runtimeVersion, currentVersion)), runtimeVersion, currentVersion };
241
+ }
242
+
243
+ function buildSkewNotice(runtimeVersion, currentVersion) {
244
+ return `ThumbGate's hooks on this machine run v${runtimeVersion}, but v${currentVersion} is installed for the MCP server, `
245
+ + `so fixes since v${runtimeVersion} are not active in the hooks. If the person asks about ThumbGate or its gates, `
246
+ + `tell them once that \`${UPDATE_COMMAND}\` updates the hooks.`;
247
+ }
248
+
249
+ /**
250
+ * Send one `runtime_version_skew` ping per 24h per machine. Never throws, never blocks.
251
+ * `track` defaults to cli-telemetry.trackEvent and is skipped under the node test runner.
252
+ */
253
+ function reportSkewOnce({ skew, env = process.env, now = Date.now(), stateDir, track } = {}) {
254
+ try {
255
+ if (!skew || !skew.skewed) return false;
256
+ if (env.THUMBGATE_NO_TELEMETRY === '1' || env.DO_NOT_TRACK === '1') return false;
257
+ const send = track || ((eventType, metadata) => {
258
+ if (env.NODE_TEST_CONTEXT || process.env.NODE_TEST_CONTEXT) return;
259
+ require('./cli-telemetry').trackEvent(eventType, metadata);
260
+ });
261
+ const dir = stateDir || path.join(path.dirname(runtimeDir(env)));
262
+ const file = path.join(dir, STATE_FILE);
263
+ let last = 0;
264
+ try { last = Number(JSON.parse(fs.readFileSync(file, 'utf8')).at) || 0; } catch { /* first time */ }
265
+ if (now - last < SKEW_REPORT_INTERVAL_MS) return false;
266
+ fs.mkdirSync(dir, { recursive: true });
267
+ fs.writeFileSync(file, JSON.stringify({ at: now, runtimeVersion: skew.runtimeVersion, currentVersion: skew.currentVersion }));
268
+ send('runtime_version_skew', { runtimeVersion: skew.runtimeVersion, currentVersion: skew.currentVersion });
269
+ return true;
270
+ } catch {
271
+ return false;
272
+ }
273
+ }
274
+
275
+ // npm.cmd needs cmd.exe, which expands %VARS% even inside quotes, so on Windows run npm-cli.js with node.
276
+ function npmRunner(platform = process.platform, nodePath = process.execPath) {
277
+ if (platform !== 'win32') return (cmd, args) => execFileSync(cmd, args, { stdio: 'inherit' });
278
+ const cli = path.join(path.dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
279
+ return (cmd, args) => execFileSync(nodePath, [cli, ...args], { stdio: 'inherit' });
280
+ }
281
+
282
+ // Hooks run the cached runtime first (published-cli.js), so self-update refreshes it too. Never throws.
283
+ function refreshHookRuntime(options = {}) {
284
+ const dir = options.dir || runtimeDir();
285
+ if (!fs.existsSync(dir)) return { refreshed: false, reason: 'no-runtime' };
286
+ const before = readRuntimeVersion(dir);
287
+ const run = options.run || npmRunner();
288
+ try {
289
+ console.log(`Updating hook runtime in ${dir} (was ${before ? `v${before}` : 'unknown'})`);
290
+ run('npm', ['install', '--prefix', dir, '--no-save', '--omit=dev', '--no-audit', '--no-fund', 'thumbgate@latest']);
291
+ return { refreshed: true, before, after: readRuntimeVersion(dir) };
292
+ } catch (err) {
293
+ console.error(`⚠️ Hook runtime update failed: ${err.message}. Run: npm install --prefix "${dir}" thumbgate@latest`);
294
+ return { refreshed: false, reason: 'install-failed', before };
295
+ }
296
+ }
297
+
199
298
  function selfUpdate() {
200
299
  const current = getLocalVersion();
201
300
  console.log(`Attempting self-update for ThumbGate...`);
@@ -209,6 +308,12 @@ function selfUpdate() {
209
308
  try {
210
309
  console.log('Running: npm install -g thumbgate@latest');
211
310
  execSync('npm install -g thumbgate@latest', { stdio: 'inherit' });
311
+ // Hooks run from the cached runtime, not the global install, so update it too.
312
+ const runtime = refreshHookRuntime();
313
+ if (runtime.reason === 'install-failed') {
314
+ console.error('❌ Self-update incomplete: hooks still run the old runtime.');
315
+ return false;
316
+ }
212
317
  console.log('✨ Self-update complete! Run `thumbgate version` to verify.');
213
318
  return true;
214
319
  } catch (err) {
@@ -221,6 +326,16 @@ function selfUpdate() {
221
326
  module.exports = {
222
327
  checkUpdate,
223
328
  selfUpdate,
329
+ refreshHookRuntime,
330
+ npmRunner,
331
+ runtimeDir,
332
+ readRuntimeVersion,
333
+ isOlder,
334
+ detectSkew,
335
+ buildSkewNotice,
336
+ reportSkewOnce,
337
+ RUNTIME_SKEW_STATE_FILE: STATE_FILE,
338
+ UPDATE_COMMAND,
224
339
  getLocalVersion,
225
340
  isNewer,
226
341
  };
@@ -13,7 +13,8 @@
13
13
  * node scripts/cli-feedback.js down "what went wrong"
14
14
  */
15
15
 
16
- const { captureFeedback, analyzeFeedback } = require('./feedback-loop');
16
+ const { captureFeedback } = require('./feedback-loop');
17
+ const { computeHumanCounts } = require('./statusline-human-counts');
17
18
  const { loadOptionalModule } = require('./private-core-boundary');
18
19
  // Keep the optional distiller from breaking the public package.
19
20
  const { distillFromHistory } = loadOptionalModule('./history-distiller', () => ({
@@ -73,14 +74,14 @@ function processInlineFeedback({ signal, context, chatHistory, whatWentWrong, wh
73
74
  // 3. Get the most recent lesson and stats
74
75
  const recentLesson = getRecentLesson();
75
76
  const lessonStats = getLessonStats();
76
- const feedbackStats = analyzeFeedback(undefined, { humanOnly: true });
77
+ // The same counter the status line and the dashboard headline use, so the three surfaces cannot disagree.
78
+ const counts = computeHumanCounts({ cwd: process.cwd() });
77
79
  const stats = {
78
80
  ...lessonStats,
79
- total: feedbackStats.total,
80
- positive: feedbackStats.totalPositive,
81
- negative: feedbackStats.totalNegative,
82
- rawTotal: feedbackStats.rawTotal,
83
- excludedTotal: feedbackStats.excludedTotal,
81
+ total: counts.up + counts.down,
82
+ positive: counts.up,
83
+ negative: counts.down,
84
+ notCounted: counts.notCounted,
84
85
  };
85
86
 
86
87
  // 4. If the user wrote an explicit "never …" / "always …" directive, surface
@@ -0,0 +1,161 @@
1
+ 'use strict';
2
+
3
+ // Cost meter: what it costs to run ThumbGate's hosted service, measured from inside the container for free.
4
+ //
5
+ // Railway bills each service by the minute for the vCPU and memory it uses. This meter samples the container's own
6
+ // cgroup counters once a minute (falling back to this Node process when the cgroup files are not readable), keeps
7
+ // one row per UTC day for 35 days in <feedbackDir>/cost-meter.json, and counts emails the mailer sent. Nothing here
8
+ // calls a paid API, and no address, subject or customer identity is stored: only daily totals.
9
+ //
10
+ // The owner console turns these totals into dollars with the list rates in config/unit-costs.json.
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const FILE = 'cost-meter.json';
16
+ const KEEP_DAYS = 35;
17
+ const MAX_FILE_BYTES = 256 * 1024;
18
+ const state = { feedbackDir: null, days: {}, loaded: false, last: null, timer: null };
19
+
20
+ const dayKey = (ms) => new Date(ms).toISOString().slice(0, 10);
21
+ const finite = (n) => (Number.isFinite(n) && n >= 0 ? n : 0);
22
+
23
+ function readFileSafe(file) {
24
+ try {
25
+ const stat = fs.statSync(file);
26
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return null;
27
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
28
+ } catch { return null; }
29
+ }
30
+
31
+ function cleanDays(raw) {
32
+ const out = {};
33
+ for (const [key, row] of Object.entries(raw && typeof raw === 'object' ? raw : {})) {
34
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || !row || typeof row !== 'object') continue;
35
+ out[key] = { sampledSeconds: finite(row.sampledSeconds), cpuSeconds: finite(row.cpuSeconds), memoryGbSeconds: finite(row.memoryGbSeconds), emails: Math.floor(finite(row.emails)), source: typeof row.source === 'string' ? row.source.slice(0, 16) : null };
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function prune(days, nowMs) {
41
+ const oldest = dayKey(nowMs - KEEP_DAYS * 86400000);
42
+ for (const key of Object.keys(days)) if (key < oldest) delete days[key];
43
+ return days;
44
+ }
45
+
46
+ function load() {
47
+ if (state.loaded || !state.feedbackDir) return;
48
+ state.loaded = true;
49
+ const saved = readFileSafe(path.join(state.feedbackDir, FILE));
50
+ // Counts made before the file was read (for example an email sent during start-up) are added to what was saved.
51
+ const saved_days = cleanDays(saved?.days);
52
+ for (const [key, row] of Object.entries(state.days)) {
53
+ const into = saved_days[key] || (saved_days[key] = { sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, source: row.source });
54
+ into.sampledSeconds += row.sampledSeconds; into.cpuSeconds += row.cpuSeconds; into.memoryGbSeconds += row.memoryGbSeconds; into.emails += row.emails;
55
+ }
56
+ state.days = saved_days;
57
+ }
58
+
59
+ function flush(nowMs = Date.now()) {
60
+ if (!state.feedbackDir) return false;
61
+ load();
62
+ prune(state.days, nowMs);
63
+ const file = path.join(state.feedbackDir, FILE);
64
+ const tmp = `${file}.${process.pid}.tmp`;
65
+ try {
66
+ fs.mkdirSync(state.feedbackDir, { recursive: true });
67
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, updatedAt: new Date(nowMs).toISOString(), days: state.days }));
68
+ fs.renameSync(tmp, file);
69
+ return true;
70
+ } catch {
71
+ try { fs.rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
72
+ return false;
73
+ }
74
+ }
75
+
76
+ function row(nowMs, source) {
77
+ const key = dayKey(nowMs);
78
+ return state.days[key] || (state.days[key] = { sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, source });
79
+ }
80
+
81
+ // Container counters when Railway's cgroup v2 files are readable, else this process. Returns null when nothing is readable.
82
+ function readCounters({ cgroupRoot = '/sys/fs/cgroup', proc = process } = {}) {
83
+ try {
84
+ const stat = fs.readFileSync(path.join(cgroupRoot, 'cpu.stat'), 'utf8');
85
+ const usage = /usage_usec\s+(\d+)/.exec(stat);
86
+ const memory = Number(fs.readFileSync(path.join(cgroupRoot, 'memory.current'), 'utf8').trim());
87
+ if (usage && Number.isFinite(memory)) return { source: 'container', cpuSeconds: Number(usage[1]) / 1e6, memoryBytes: memory };
88
+ } catch { /* not a cgroup v2 container */ }
89
+ try {
90
+ const cpu = proc.cpuUsage();
91
+ return { source: 'process', cpuSeconds: (cpu.user + cpu.system) / 1e6, memoryBytes: proc.memoryUsage().rss };
92
+ } catch { return null; }
93
+ }
94
+
95
+ // One sample: CPU used since the last sample, and memory held for the time between them.
96
+ function sample({ nowMs = Date.now(), counters = readCounters() } = {}) {
97
+ if (!counters) return null;
98
+ const last = state.last;
99
+ state.last = { at: nowMs, ...counters };
100
+ if (!last || last.source !== counters.source) return null;
101
+ const seconds = (nowMs - last.at) / 1000;
102
+ const cpu = counters.cpuSeconds - last.cpuSeconds;
103
+ // A restart, a clock jump or a counter reset gives a gap or a negative step: skip it rather than guess.
104
+ if (!(seconds > 0 && seconds <= 600) || !(cpu >= 0)) return null;
105
+ load();
106
+ const into = row(nowMs, counters.source);
107
+ into.sampledSeconds += seconds;
108
+ into.cpuSeconds += cpu;
109
+ into.memoryGbSeconds += ((last.memoryBytes + counters.memoryBytes) / 2 / 1e9) * seconds;
110
+ into.source = counters.source;
111
+ return { seconds, cpuSeconds: cpu };
112
+ }
113
+
114
+ function recordEmailSend({ nowMs = Date.now(), count = 1 } = {}) {
115
+ if (!Number.isInteger(count) || count < 1) return;
116
+ load();
117
+ row(nowMs, state.last?.source || null).emails += count;
118
+ }
119
+
120
+ function configure({ feedbackDir } = {}) {
121
+ if (feedbackDir && feedbackDir !== state.feedbackDir) { state.feedbackDir = feedbackDir; state.loaded = false; }
122
+ return state.feedbackDir;
123
+ }
124
+
125
+ function start({ feedbackDir, intervalMs = 60000 } = {}) {
126
+ configure({ feedbackDir });
127
+ if (state.timer) return state.timer;
128
+ sample();
129
+ state.timer = setInterval(() => { sample(); flush(); }, intervalMs);
130
+ state.timer.unref?.();
131
+ return state.timer;
132
+ }
133
+
134
+ function stop() { if (state.timer) clearInterval(state.timer); state.timer = null; }
135
+
136
+ function reset() { stop(); state.feedbackDir = null; state.days = {}; state.loaded = false; state.last = null; }
137
+
138
+ // Totals for the last `days` UTC days, today included, read from disk plus anything not yet written.
139
+ function readWindow({ feedbackDir = state.feedbackDir, days = 30, nowMs = Date.now() } = {}) {
140
+ let rows = {};
141
+ if (feedbackDir && feedbackDir === state.feedbackDir) { load(); rows = state.days; }
142
+ else if (feedbackDir) rows = cleanDays(readFileSafe(path.join(feedbackDir, FILE))?.days);
143
+ const oldest = dayKey(nowMs - (days - 1) * 86400000);
144
+ const total = { days, daysWithSamples: 0, sampledSeconds: 0, cpuSeconds: 0, memoryGbSeconds: 0, emails: 0, sources: [] };
145
+ const sources = new Set();
146
+ for (const [key, entry] of Object.entries(rows)) {
147
+ if (key < oldest || key > dayKey(nowMs)) continue;
148
+ if (entry.sampledSeconds > 0) total.daysWithSamples += 1;
149
+ total.sampledSeconds += entry.sampledSeconds;
150
+ total.cpuSeconds += entry.cpuSeconds;
151
+ total.memoryGbSeconds += entry.memoryGbSeconds;
152
+ total.emails += entry.emails;
153
+ if (entry.source) sources.add(entry.source);
154
+ }
155
+ total.sources = [...sources].sort();
156
+ total.windowSeconds = days * 86400;
157
+ total.coverage = Math.min(1, total.sampledSeconds / total.windowSeconds);
158
+ return total;
159
+ }
160
+
161
+ module.exports = { configure, start, stop, reset, sample, flush, recordEmailSend, readWindow, readCounters, FILE };