thumbgate 1.39.1 → 1.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -45,6 +45,14 @@ function pkgVersion() {
45
45
  // deps.runGate(input) -> Promise<rawJsonString>
46
46
  // deps.captureFeedback(params)
47
47
  // deps.trackEvent(name, props)
48
+ function loadFirstBlockRecorder() {
49
+ try {
50
+ return require(path.join(PKG_ROOT, 'scripts', 'activation-tracker')).recordFirstBlockedToolCall;
51
+ } catch { /* optional in stripped shell */
52
+ return () => {};
53
+ }
54
+ }
55
+
48
56
  async function runActivationFlow({ ask, out, isTTY, deps = {} }) {
49
57
  // Hard safety gate: never prompt or hang in non-interactive contexts.
50
58
  if (!isTTY) {
@@ -67,7 +75,7 @@ async function runActivationFlow({ ask, out, isTTY, deps = {} }) {
67
75
  }
68
76
  }
69
77
  const trackEvent = deps.trackEvent || (() => {});
70
-
78
+ const recordFirstBlock = deps.recordFirstBlock ?? loadFirstBlockRecorder();
71
79
  out('');
72
80
  out(`thumbgate quickstart v${pkgVersion()}`);
73
81
  out('');
@@ -146,6 +154,9 @@ async function runActivationFlow({ ask, out, isTTY, deps = {} }) {
146
154
  out('');
147
155
 
148
156
  try { trackEvent('cli_quickstart_activated', { command: 'quickstart', blocked }); } catch { /* telemetry best-effort */ }
157
+ if (blocked && typeof recordFirstBlock === 'function') {
158
+ try { recordFirstBlock({ gateId: promotion.gateId, source: 'cli_quickstart' }); } catch { /* best-effort */ }
159
+ }
149
160
 
150
161
  return {
151
162
  interactive: true,
@@ -166,18 +177,19 @@ function quickstart() {
166
177
  const trackEvent = (() => {
167
178
  try { return require(path.join(PKG_ROOT, 'scripts', 'cli-telemetry')).trackEvent; } catch { return () => {}; }
168
179
  })();
180
+ const recordFirstBlock = loadFirstBlockRecorder();
169
181
 
170
182
  if (!isTTY) {
171
183
  // Mirror the non-interactive branch without opening readline (which would
172
184
  // otherwise keep the process alive waiting for input that never comes).
173
- return runActivationFlow({ ask: async () => '', out, isTTY: false, deps: { trackEvent } });
185
+ return runActivationFlow({ ask: async () => '', out, isTTY: false, deps: { trackEvent, recordFirstBlock } });
174
186
  }
175
187
 
176
188
  const readline = require('node:readline');
177
189
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
178
190
  const ask = (q) => new Promise((resolve) => rl.question(q, resolve));
179
191
 
180
- return runActivationFlow({ ask, out, isTTY: true, deps: { trackEvent } })
192
+ return runActivationFlow({ ask, out, isTTY: true, deps: { trackEvent, recordFirstBlock } })
181
193
  .catch((err) => {
182
194
  console.error(`quickstart error: ${err?.message ?? err}`);
183
195
  process.exitCode = 1;
@@ -25,12 +25,20 @@
25
25
  */
26
26
 
27
27
  const fs = require('node:fs');
28
+ const { spawn } = require('node:child_process');
29
+ const http = require('node:http');
30
+ const https = require('node:https');
31
+ const os = require('node:os');
28
32
  const path = require('node:path');
29
33
 
30
34
  const { trackEvent, getInstallId, classifyInstall, INSTALL_ID_PATH } = require('./cli-telemetry');
31
35
 
36
+ const DEFAULT_API_HOST = 'https://thumbgate.ai';
37
+ const ACTIVATION_RECORDED_PATH = path.join(path.dirname(INSTALL_ID_PATH), 'activation-recorded.json');
38
+
32
39
  const MARKER_DIR = path.join(path.dirname(INSTALL_ID_PATH), 'activation');
33
40
  const MARKER_PATH = path.join(MARKER_DIR, 'first-rule-promoted.json');
41
+ const FIRST_BLOCK_MARKER_PATH = path.join(MARKER_DIR, 'first-blocked-call.json');
34
42
 
35
43
  function readMarker() {
36
44
  try {
@@ -66,6 +74,24 @@ function computeDaysSinceInstall() {
66
74
  }
67
75
  }
68
76
 
77
+ function computeMinutesSinceInstall() {
78
+ try {
79
+ if (!fs.existsSync(INSTALL_ID_PATH)) return null;
80
+ const installed = fs.statSync(INSTALL_ID_PATH).mtimeMs;
81
+ if (!Number.isFinite(installed) || installed <= 0) return null;
82
+ return Math.round((Math.max(0, Date.now() - installed) / 60_000) * 10) / 10;
83
+ } catch { /* ignore stat race */
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function writeFirstBlockMarker(data) {
89
+ try {
90
+ if (!fs.existsSync(MARKER_DIR)) fs.mkdirSync(MARKER_DIR, { recursive: true });
91
+ fs.writeFileSync(FIRST_BLOCK_MARKER_PATH, JSON.stringify(data, null, 2));
92
+ } catch { /* best-effort marker */ }
93
+ }
94
+
69
95
  /**
70
96
  * Fire the activation event if this is the first rule promotion for this
71
97
  * install. Returns true if an event was actually emitted, false if skipped
@@ -109,19 +135,270 @@ function recordFirstRulePromotion(metadata = {}) {
109
135
  return true;
110
136
  }
111
137
 
138
+ function readJsonSafe(filePath) {
139
+ try {
140
+ if (!fs.existsSync(filePath)) return null;
141
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
142
+ return parsed && typeof parsed === 'object' ? parsed : null;
143
+ } catch {
144
+ return null;
145
+ }
146
+ }
147
+
148
+ function writeJsonSafe(filePath, data) {
149
+ try {
150
+ const dir = path.dirname(filePath);
151
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
152
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
153
+ } catch { }
154
+ }
155
+
156
+ function resolveActivationAccountAuth(options = {}) {
157
+ const env = options.env || process.env;
158
+ const homeDir = options.homeDir || env.HOME || env.USERPROFILE || os.homedir();
159
+ const operatorCfg = readJsonSafe(path.join(homeDir, '.config', 'thumbgate', 'operator.json'));
160
+ const signedLic = readJsonSafe(path.join(homeDir, '.config', 'thumbgate', 'license.json'));
161
+ const localLic = readJsonSafe(path.join(homeDir, '.thumbgate', 'license.json'));
162
+ const candidates = [
163
+ options.apiKey,
164
+ env.THUMBGATE_API_KEY,
165
+ env.THUMBGATE_PRO_KEY,
166
+ env.THUMBGATE_LICENSE,
167
+ signedLic && (signedLic.license || signedLic.token || signedLic.key),
168
+ localLic && (localLic.key || localLic.license || localLic.token),
169
+ env.THUMBGATE_OPERATOR_KEY,
170
+ operatorCfg && operatorCfg.operatorKey,
171
+ ];
172
+ let apiKey = '';
173
+ for (const c of candidates) {
174
+ if (typeof c === 'string' && c.trim()) {
175
+ apiKey = c.trim();
176
+ break;
177
+ }
178
+ }
179
+ const apiBaseUrl = String(
180
+ options.apiBaseUrl
181
+ || env.THUMBGATE_API_URL
182
+ || env.THUMBGATE_BILLING_API_BASE_URL
183
+ || (operatorCfg && operatorCfg.baseUrl)
184
+ || DEFAULT_API_HOST
185
+ ).trim().replace(/\/+$/, '');
186
+ return { apiKey, apiBaseUrl };
187
+ }
188
+
189
+ function postActivationEvent(endpointUrl, apiKey, bodyObj, awaitDelivery = false) {
190
+ const payload = JSON.stringify(bodyObj);
191
+ const parsed = new URL(endpointUrl);
192
+ const transport = parsed.protocol === 'http:' ? http : https;
193
+ const headers = {
194
+ 'Content-Type': 'application/json',
195
+ 'Content-Length': Buffer.byteLength(payload),
196
+ };
197
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
198
+ const send = (resolve) => {
199
+ try {
200
+ const req = transport.request({
201
+ hostname: parsed.hostname,
202
+ port: parsed.port || (parsed.protocol === 'http:' ? 80 : 443),
203
+ path: parsed.pathname + parsed.search,
204
+ method: 'POST',
205
+ headers,
206
+ timeout: 2000,
207
+ }, (res) => {
208
+ let raw = '';
209
+ res.on('data', (chunk) => { if (raw.length < 4096) raw += chunk; });
210
+ res.on('end', () => resolve({ ok: res.statusCode >= 200 && res.statusCode < 300, statusCode: res.statusCode }));
211
+ });
212
+ req.on('error', () => resolve({ ok: false, statusCode: 0 }));
213
+ req.on('timeout', () => { req.destroy(); resolve({ ok: false, statusCode: 0 }); });
214
+ if (!awaitDelivery) req.on('socket', (s) => s.unref());
215
+ req.end(payload);
216
+ } catch {
217
+ resolve({ ok: false, statusCode: 0 });
218
+ }
219
+ };
220
+ if (awaitDelivery) return new Promise(send);
221
+ send(() => {});
222
+ return { ok: true, dispatched: true };
223
+ }
224
+
225
+ function spawnDetachedFirstBlockWorker(apiKey, apiBaseUrl, env, stateDir) {
226
+ try {
227
+ const childEnv = { ...env };
228
+ if (apiKey) childEnv.THUMBGATE_API_KEY = apiKey;
229
+ if (apiBaseUrl) childEnv.THUMBGATE_API_URL = apiBaseUrl;
230
+ if (stateDir) childEnv.THUMBGATE_STATE_DIR = stateDir;
231
+ const child = spawn(process.execPath, [__filename, '--deliver-first-block'], {
232
+ detached: true,
233
+ stdio: 'ignore',
234
+ env: childEnv,
235
+ });
236
+ child.unref();
237
+ return true;
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ function reportFirstBlockActivation(metadata = {}) {
244
+ const env = metadata.env || process.env;
245
+ const stateDir = metadata.stateDir || env.THUMBGATE_STATE_DIR || path.dirname(INSTALL_ID_PATH);
246
+ const markerPath = path.join(stateDir, 'activation-recorded.json');
247
+ const existing = readJsonSafe(markerPath) || {};
248
+ const firstBlockAt = existing.firstBlockAt || metadata.firstBlockAt || existing.blockedAt || new Date().toISOString();
249
+ const { apiKey, apiBaseUrl } = resolveActivationAccountAuth(metadata);
250
+
251
+ if (existing.firstBlockReportedAt || (!apiKey && existing.firstBlockAnonReportedAt)) {
252
+ if (!existing.firstBlockAt || existing.event !== 'first_block') {
253
+ writeJsonSafe(markerPath, { ...existing, firstBlockAt, event: 'first_block', at: existing.at || firstBlockAt });
254
+ }
255
+ return metadata.awaitDelivery
256
+ ? Promise.resolve({ reported: false, alreadyReported: true, firstBlockAt })
257
+ : { reported: false, alreadyReported: true, firstBlockAt };
258
+ }
259
+
260
+ const installId = metadata.installId || getInstallId();
261
+ const gateId = metadata.gateId || existing.gateId || undefined;
262
+ const nextMarker = {
263
+ ...existing,
264
+ at: existing.at || firstBlockAt,
265
+ firstBlockAt,
266
+ event: 'first_block',
267
+ ...(gateId ? { gateId } : {}),
268
+ };
269
+ const optedOut = env.THUMBGATE_NO_TELEMETRY === '1' || env.DO_NOT_TRACK === '1';
270
+ const inIsolatedTest = Boolean(env.NODE_TEST_CONTEXT || env.NODE_ENV === 'test')
271
+ && !metadata.apiBaseUrl
272
+ && !env.THUMBGATE_API_URL;
273
+ if (optedOut || inIsolatedTest) {
274
+ writeJsonSafe(markerPath, nextMarker);
275
+ return metadata.awaitDelivery
276
+ ? Promise.resolve({ reported: false, firstBlockAt })
277
+ : { reported: false, firstBlockAt };
278
+ }
279
+
280
+ const eventPayload = {
281
+ event: 'first_block',
282
+ eventType: 'first_block',
283
+ clientType: 'cli',
284
+ firstBlockAt,
285
+ installId,
286
+ ...(gateId ? { gateId: String(gateId).slice(0, 120) } : {}),
287
+ };
288
+
289
+ if (metadata.awaitDelivery) {
290
+ writeJsonSafe(markerPath, nextMarker);
291
+ const targetUrl = apiKey
292
+ ? `${apiBaseUrl}/v1/activation/first-block`
293
+ : `${apiBaseUrl}/v1/telemetry/ping`;
294
+ return postActivationEvent(targetUrl, apiKey, eventPayload, true).then((res) => {
295
+ if (res.ok) {
296
+ const latest = readJsonSafe(markerPath) || nextMarker;
297
+ const stamp = new Date().toISOString();
298
+ writeJsonSafe(markerPath, {
299
+ ...latest,
300
+ at: latest.at || firstBlockAt,
301
+ firstBlockAt: latest.firstBlockAt || firstBlockAt,
302
+ event: 'first_block',
303
+ ...(apiKey ? { firstBlockReportedAt: stamp } : { firstBlockAnonReportedAt: stamp }),
304
+ });
305
+ }
306
+ return { reported: Boolean(res.ok), statusCode: res.statusCode, firstBlockAt };
307
+ });
308
+ }
309
+
310
+ const lastAttemptMs = existing.firstBlockDispatchAttemptAt ? Date.parse(existing.firstBlockDispatchAttemptAt) : 0;
311
+ if (Number.isFinite(lastAttemptMs) && Date.now() - lastAttemptMs < 10_000) {
312
+ return { reported: false, inFlight: true, firstBlockAt };
313
+ }
314
+ nextMarker.firstBlockDispatchAttemptAt = new Date().toISOString();
315
+ writeJsonSafe(markerPath, nextMarker);
316
+ const spawned = spawnDetachedFirstBlockWorker(apiKey, apiBaseUrl, env, stateDir);
317
+ return { reported: spawned, dispatched: spawned, firstBlockAt };
318
+ }
319
+ function recordFirstBlockedToolCall(metadata = {}) {
320
+ try { reportFirstBlockActivation({ ...metadata, firstBlockAt: new Date().toISOString() }); } catch { /* best-effort */ }
321
+ try {
322
+ if (fs.existsSync(FIRST_BLOCK_MARKER_PATH)) return false;
323
+ } catch { /* ignore fs error */
324
+ return false;
325
+ }
326
+ const installId = getInstallId();
327
+ const minutesSinceInstall = computeMinutesSinceInstall();
328
+ const visitorType = classifyInstall();
329
+ const optedOut = process.env.THUMBGATE_NO_TELEMETRY === '1' || process.env.DO_NOT_TRACK === '1';
330
+ writeFirstBlockMarker({
331
+ installId,
332
+ blockedAt: new Date().toISOString(),
333
+ minutesSinceInstall,
334
+ ...(optedOut ? { telemetryOptOut: true } : { visitorType, ...metadata }),
335
+ });
336
+ if (optedOut) return false;
337
+ trackEvent('first_blocked_tool_call', { minutesSinceInstall, visitorType, ...metadata });
338
+ return true;
339
+ }
340
+
341
+ function extractEntryBlockMinutes(e) {
342
+ if (typeof e.minutesSinceInstall === 'number' && Number.isFinite(e.minutesSinceInstall)) return e.minutesSinceInstall;
343
+ if (typeof e.minutesToFirstBlock === 'number' && Number.isFinite(e.minutesToFirstBlock)) return e.minutesToFirstBlock;
344
+ const ms = typeof e.signupToFirstBlockMs === 'number' && Number.isFinite(e.signupToFirstBlockMs)
345
+ ? e.signupToFirstBlockMs
346
+ : e.elapsedSinceOpenMs;
347
+ return typeof ms === 'number' && Number.isFinite(ms) ? Math.round((ms / 60_000) * 10) / 10 : null;
348
+ }
349
+
350
+ function summarizeFirstBlockEvents(entries = []) {
351
+ if (!Array.isArray(entries) || entries.length === 0) {
352
+ return { count: 0, medianMinutes: null, under5MinutesCount: 0 };
353
+ }
354
+ let count = 0;
355
+ const minutesList = [];
356
+ 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;
360
+ const m = extractEntryBlockMinutes(e);
361
+ if (m !== null && m >= 0) minutesList.push(m);
362
+ }
363
+ if (count === 0 || minutesList.length === 0) {
364
+ return { count, medianMinutes: null, under5MinutesCount: 0 };
365
+ }
366
+ minutesList.sort((a, b) => a - b);
367
+ const mid = Math.floor(minutesList.length / 2);
368
+ const rawMedian = minutesList.length % 2 === 0
369
+ ? (minutesList[mid - 1] + minutesList[mid]) / 2
370
+ : minutesList[mid];
371
+ return {
372
+ count,
373
+ medianMinutes: Math.round(rawMedian * 10) / 10,
374
+ under5MinutesCount: minutesList.filter((v) => v <= 5).length,
375
+ };
376
+ }
377
+
112
378
  function resetForTesting() {
113
- // Test-only helper. Removes the marker so a subsequent recordFirstRulePromotion
114
- // call re-fires. Never used in production code paths.
115
379
  try {
116
380
  if (fs.existsSync(MARKER_PATH)) fs.unlinkSync(MARKER_PATH);
117
- } catch {}
381
+ if (fs.existsSync(FIRST_BLOCK_MARKER_PATH)) fs.unlinkSync(FIRST_BLOCK_MARKER_PATH);
382
+ if (fs.existsSync(ACTIVATION_RECORDED_PATH)) fs.unlinkSync(ACTIVATION_RECORDED_PATH);
383
+ } catch { /* test cleanup */ }
118
384
  }
119
385
 
120
386
  module.exports = {
121
387
  recordFirstRulePromotion,
388
+ recordFirstBlockedToolCall,
389
+ reportFirstBlockActivation,
390
+ resolveActivationAccountAuth,
391
+ summarizeFirstBlockEvents,
122
392
  computeDaysSinceInstall,
393
+ computeMinutesSinceInstall,
123
394
  readMarker,
124
395
  writeMarker,
125
396
  MARKER_PATH,
397
+ FIRST_BLOCK_MARKER_PATH,
398
+ ACTIVATION_RECORDED_PATH,
126
399
  resetForTesting,
127
400
  };
401
+
402
+ if (require.main === module && process.argv[2] === '--deliver-first-block') {
403
+ reportFirstBlockActivation({ awaitDelivery: true }).catch(() => {});
404
+ }