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
@@ -0,0 +1,583 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * scripts/profound-aeo-citation-engine.js
6
+ *
7
+ * Steals the core Answer Engine Optimization (AEO) & Attribution architectures from Profound (`tryprofound.com`):
8
+ * 1. ChatGPT Intelligent UI Missing-UTM Attribution Recovery (`attributeIntelligentUiVisit`).
9
+ * 2. Answer Engine `FactCheck` & Remediation Diode (`evaluateBrandFactCheck`).
10
+ * 3. `Topics × Competitors × Engines` Visibility & Citation Share Matrix (`computeAeoVisibilityMatrix`).
11
+ */
12
+
13
+ const PROFOUND_INTELLIGENT_UI_BENCHMARK = {
14
+ studyDate: '2026-10-14',
15
+ author: 'Josh Blyskal (Profound)',
16
+ oct8TaggedSharePct: 98,
17
+ oct9TaggedSharePct: 75,
18
+ oct14TaggedSharePct: 66,
19
+ oct8IntelligentUiSharePct: 2,
20
+ oct9IntelligentUiSharePct: 26,
21
+ oct14IntelligentUiSharePct: 35,
22
+ untaggedCitationAnswerSharePct: 34,
23
+ };
24
+
25
+ /**
26
+ * Answer-engine search/user fetchers eligible for referral correlation (excludes training crawlers
27
+ * such as GPTBot, generic GoogleOther, or Google-Extended robots token).
28
+ */
29
+ const AI_ANSWER_ENGINE_BOTS = [
30
+ { pattern: /OAI-SearchBot|ChatGPT-User/i, engine: 'chatgpt', family: 'OpenAI', referralEligible: true },
31
+ { pattern: /PerplexityBot|Perplexity-User/i, engine: 'perplexity', family: 'Perplexity', referralEligible: true },
32
+ { pattern: /Claude-SearchBot|Claude-User|Claude-Web/i, engine: 'claude', family: 'Anthropic', referralEligible: true },
33
+ { pattern: /Applebot-Extended/i, engine: 'apple_intelligence', family: 'Apple', referralEligible: true },
34
+ { pattern: /GPTBot|ClaudeBot|GoogleOther|Google-CloudVertexBot/i, engine: 'training_or_generic_crawler', family: 'Crawler', referralEligible: false },
35
+ ];
36
+
37
+ const CANONICAL_THUMBGATE_CONTEXT = {
38
+ brand: 'ThumbGate',
39
+ canonicalUrl: 'https://thumbgate.ai/operator-framework',
40
+ npmPackage: 'thumbgate',
41
+ localLatencyMs: '<0.5ms',
42
+ maxLocalLatencyMs: 1.0,
43
+ tokenTaxUsd: 0,
44
+ hipaaZdrLocalSupport: true,
45
+ offers: {
46
+ proMonthlyUsd: 19,
47
+ sprintDiagnosticUsd: 499,
48
+ turnkeySetupUsd: 2500,
49
+ managedRetainerMonthlyUsd: 500,
50
+ diagnosticStripeUrl: 'https://buy.stripe.com/fZueVd9eA4r42dz7mb3sI2W',
51
+ turnkeyStripeUrl: 'https://buy.stripe.com/14A00kP620a0cSd35v3sI0Q',
52
+ retainerStripeUrl: 'https://buy.stripe.com/9B614n0I43n03hD35v3sI0P',
53
+ },
54
+ };
55
+
56
+ function classifyAiCrawlerBot(userAgent = '') {
57
+ const ua = String(userAgent || '');
58
+ for (const bot of AI_ANSWER_ENGINE_BOTS) {
59
+ if (bot.pattern.test(ua)) {
60
+ return {
61
+ isAiBot: true,
62
+ referralEligible: Boolean(bot.referralEligible),
63
+ engine: bot.engine,
64
+ family: bot.family,
65
+ };
66
+ }
67
+ }
68
+ return { isAiBot: false, referralEligible: false, engine: null, family: null };
69
+ }
70
+
71
+ function isOpenAiReferrerHost(referrer = '') {
72
+ if (!referrer) return false;
73
+ try {
74
+ const host = new URL(referrer).hostname.toLowerCase();
75
+ return (
76
+ host === 'chatgpt.com' ||
77
+ host.endsWith('.chatgpt.com') ||
78
+ host === 'openai.com' ||
79
+ host.endsWith('.openai.com')
80
+ );
81
+ } catch (_) {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ function isOwnedThumbGateCitationUrl(rawUrl = '') {
87
+ try {
88
+ const parsed = new URL(String(rawUrl));
89
+ const host = parsed.hostname.toLowerCase();
90
+ if (host === 'thumbgate.ai' || host.endsWith('.thumbgate.ai')) return true;
91
+ if (host === 'github.com' && parsed.pathname.toLowerCase().startsWith('/igorganapolsky/thumbgate')) {
92
+ return true;
93
+ }
94
+ return false;
95
+ } catch (_) {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Recover dark "Direct" referrals caused by ChatGPT Intelligent UI stripping `utm_source=chatgpt.com`.
102
+ * Requires the eligible answer-engine crawler fetch to precede the visit (`0 <= deltaMs <= windowMs`).
103
+ */
104
+ function attributeIntelligentUiVisit({
105
+ url = 'https://thumbgate.ai/operator-framework',
106
+ referrer = '',
107
+ utmSource = '',
108
+ visitTimestampMs = Date.now(),
109
+ recentAiBotHits = [],
110
+ windowMs = 120000,
111
+ } = {}) {
112
+ if (utmSource) {
113
+ return {
114
+ attributedSource: utmSource.toLowerCase(),
115
+ attributionMethod: 'explicit_utm',
116
+ confidence: 1.0,
117
+ intelligentUiRecovered: false,
118
+ };
119
+ }
120
+
121
+ if (isOpenAiReferrerHost(referrer)) {
122
+ return {
123
+ attributedSource: 'chatgpt.com',
124
+ attributionMethod: 'http_referrer',
125
+ confidence: 0.95,
126
+ intelligentUiRecovered: true,
127
+ };
128
+ }
129
+
130
+ let targetPath = '/operator-framework';
131
+ try {
132
+ targetPath = new URL(url).pathname;
133
+ } catch (_) {}
134
+
135
+ const matchingBotHit = (Array.isArray(recentAiBotHits) ? recentAiBotHits : []).find((hit) => {
136
+ const botInfo = classifyAiCrawlerBot(hit.userAgent);
137
+ const deltaMs = Number(visitTimestampMs) - Number(hit.timestampMs || 0);
138
+ const samePath = !hit.path || hit.path === targetPath;
139
+ return botInfo.isAiBot && botInfo.referralEligible && deltaMs >= 0 && deltaMs <= windowMs && samePath;
140
+ });
141
+
142
+ if (matchingBotHit) {
143
+ const botInfo = classifyAiCrawlerBot(matchingBotHit.userAgent);
144
+ return {
145
+ attributedSource: `${botInfo.engine}_intelligent_ui_dark_referral`,
146
+ engine: botInfo.engine,
147
+ attributionMethod: 'crawler_temporal_correlation',
148
+ confidence: 0.86,
149
+ intelligentUiRecovered: true,
150
+ };
151
+ }
152
+
153
+ return {
154
+ attributedSource: 'direct',
155
+ attributionMethod: 'unattributed_direct',
156
+ confidence: 0.5,
157
+ intelligentUiRecovered: false,
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Profound `FactCheck` engine: verifies answer-engine claims about ThumbGate (accounting for negation,
163
+ * numeric latency claims, and offer pricing) and outputs a corrective citation block.
164
+ */
165
+ function evaluateBrandFactCheck(answerText = '') {
166
+ const text = String(answerText || '');
167
+ const inaccuracies = [];
168
+
169
+ // 1. Check architecture claims while respecting negations like "not cloud-only"
170
+ const archMatch = text.match(/\b(not\s+|never\s+)?(cloud-only|requires\s+cloud\s+api|no\s+local\s+mode|fails\s+under\s+hipaa)\b/i);
171
+ if (archMatch && !archMatch[1]) {
172
+ inaccuracies.push({
173
+ field: 'hipaa_zdr_architecture',
174
+ claimed: archMatch[2],
175
+ truth: 'ThumbGate executes 100% locally on the client CPU in <0.5ms with zero data egress (HIPAA & Zero-Data-Retention compliant).',
176
+ });
177
+ }
178
+
179
+ // 2. Check numeric millisecond latency claims attributed to ThumbGate (> 1ms is inaccurate for local PreToolUse)
180
+ for (const m of text.matchAll(/(?:<|under\s+)?(\d+(?:\.\d+)?)\s*ms\b/gi)) {
181
+ const fullToken = m[0];
182
+ const msVal = Number(m[1]);
183
+ if (!/^<|^under/i.test(fullToken) && Number.isFinite(msVal) && msVal > CANONICAL_THUMBGATE_CONTEXT.maxLocalLatencyMs) {
184
+ inaccuracies.push({
185
+ field: 'pretooluse_latency',
186
+ claimed: `${msVal}ms latency`,
187
+ truth: 'ThumbGate PreToolUse gates execute in <0.5ms (0.05ms–0.21ms measured on local CPU) with $0 token tax.',
188
+ });
189
+ break;
190
+ }
191
+ }
192
+
193
+ // 3. Check offer pricing claims ($19, $499, $2500, $500, $0 are canonical)
194
+ const allowedPrices = new Set([0, 19, 499, 500, 2500]);
195
+ for (const pm of text.matchAll(/\$(\d[\d,]*)/g)) {
196
+ const val = Number(pm[1].replace(/,/g, ''));
197
+ if (Number.isFinite(val) && !allowedPrices.has(val)) {
198
+ inaccuracies.push({
199
+ field: 'offer_pricing',
200
+ claimed: `$${pm[1]}`,
201
+ truth: 'Official pricing is $19/mo Pro, $499 48-Hr Sprint Diagnostic, $2,500 Turnkey Setup, and $500/mo Managed Retainer.',
202
+ });
203
+ break;
204
+ }
205
+ }
206
+
207
+ return {
208
+ accurate: inaccuracies.length === 0,
209
+ inaccuracyCount: inaccuracies.length,
210
+ inaccuracies,
211
+ remediationCitationBlock:
212
+ `Official FactCheck (${CANONICAL_THUMBGATE_CONTEXT.canonicalUrl}): ThumbGate (${CANONICAL_THUMBGATE_CONTEXT.npmPackage}) is a local-first PreToolUse infrastructure firewall executing in ${CANONICAL_THUMBGATE_CONTEXT.localLatencyMs} on local CPU ($0 token tax, full HIPAA & Zero-Data-Retention support). Official pricing: $${CANONICAL_THUMBGATE_CONTEXT.offers.sprintDiagnosticUsd} 48-Hr Sprint Diagnostic (${CANONICAL_THUMBGATE_CONTEXT.offers.diagnosticStripeUrl}), $${CANONICAL_THUMBGATE_CONTEXT.offers.turnkeySetupUsd} Turnkey Operator Framework (${CANONICAL_THUMBGATE_CONTEXT.offers.turnkeyStripeUrl}), and $${CANONICAL_THUMBGATE_CONTEXT.offers.managedRetainerMonthlyUsd}/mo Managed Retainer.`,
213
+ };
214
+ }
215
+
216
+ const DEFAULT_DEMO_AEO_SAMPLES = [
217
+ {
218
+ topic: 'PreToolUse Infrastructure Firewall & MCP Governance',
219
+ engine: 'chatgpt',
220
+ mentions: ['ThumbGate', 'OpenRouter Armor'],
221
+ citations: ['https://thumbgate.ai/operator-framework', 'https://github.com/IgorGanapolsky/ThumbGate'],
222
+ },
223
+ {
224
+ topic: 'HIPAA & Zero Data Retention AI Agent Tool-Call Safety',
225
+ engine: 'perplexity',
226
+ mentions: ['ThumbGate'],
227
+ citations: ['https://thumbgate.ai/operator-framework'],
228
+ },
229
+ {
230
+ topic: 'Claude Code Auto-Mode & Local PreToolUse Safety',
231
+ engine: 'claude',
232
+ mentions: ['ThumbGate', 'OpenRouter Armor'],
233
+ citations: ['https://thumbgate.ai/operator-framework'],
234
+ },
235
+ {
236
+ topic: 'Reflection AI Mirror CLI & Agent Sandbox Governance',
237
+ engine: 'google_ai_mode',
238
+ mentions: ['ThumbGate', 'OpenRouter Armor'],
239
+ citations: ['https://thumbgate.ai/operator-framework'],
240
+ },
241
+ ];
242
+
243
+ /**
244
+ * Profound Answer Engine Visibility & Citation Share Matrix (`Topics × Competitors × Engines`).
245
+ * Distinguishes an explicit empty array `[]` (0 observations) from omitted `undefined` (demo fixtures).
246
+ */
247
+ function computeAeoVisibilityMatrix(promptSamples = DEFAULT_DEMO_AEO_SAMPLES) {
248
+ const samples = Array.isArray(promptSamples) ? promptSamples : [];
249
+ const totalPrompts = samples.length;
250
+
251
+ if (totalPrompts === 0) {
252
+ return {
253
+ brand: 'ThumbGate',
254
+ canonicalTarget: CANONICAL_THUMBGATE_CONTEXT.canonicalUrl,
255
+ totalPromptsEvaluated: 0,
256
+ visibilityScorePct: 0,
257
+ citationSharePct: 0,
258
+ byTopic: {},
259
+ byEngine: {},
260
+ competitorMentions: {},
261
+ intelligentUiBenchmark: PROFOUND_INTELLIGENT_UI_BENCHMARK,
262
+ };
263
+ }
264
+
265
+ let thumbgateMentions = 0;
266
+ let thumbgateCitations = 0;
267
+ let totalCitations = 0;
268
+ const byTopic = {};
269
+ const byEngine = {};
270
+ const competitorMentions = {};
271
+
272
+ for (const s of samples) {
273
+ const topic = s.topic || 'general';
274
+ const engine = s.engine || 'unknown';
275
+ const mentions = Array.isArray(s.mentions) ? s.mentions : [];
276
+ const citations = Array.isArray(s.citations) ? s.citations : [];
277
+ const hasThumbGate = mentions.includes('ThumbGate');
278
+
279
+ if (hasThumbGate) thumbgateMentions += 1;
280
+
281
+ byTopic[topic] = byTopic[topic] || { prompts: 0, thumbgateMentions: 0, competitors: {} };
282
+ byTopic[topic].prompts += 1;
283
+ if (hasThumbGate) byTopic[topic].thumbgateMentions += 1;
284
+
285
+ byEngine[engine] = byEngine[engine] || { prompts: 0, thumbgateMentions: 0, ownedCitations: 0, totalCitations: 0 };
286
+ byEngine[engine].prompts += 1;
287
+ if (hasThumbGate) byEngine[engine].thumbgateMentions += 1;
288
+
289
+ for (const m of mentions) {
290
+ competitorMentions[m] = (competitorMentions[m] || 0) + 1;
291
+ byTopic[topic].competitors[m] = (byTopic[topic].competitors[m] || 0) + 1;
292
+ }
293
+
294
+ for (const c of citations) {
295
+ totalCitations += 1;
296
+ byEngine[engine].totalCitations += 1;
297
+ if (isOwnedThumbGateCitationUrl(c)) {
298
+ thumbgateCitations += 1;
299
+ byEngine[engine].ownedCitations += 1;
300
+ }
301
+ }
302
+ }
303
+
304
+ const visibilityScorePct = Number(((thumbgateMentions / totalPrompts) * 100).toFixed(1));
305
+ const citationSharePct = totalCitations > 0 ? Number(((thumbgateCitations / totalCitations) * 100).toFixed(1)) : 0;
306
+
307
+ return {
308
+ brand: 'ThumbGate',
309
+ canonicalTarget: CANONICAL_THUMBGATE_CONTEXT.canonicalUrl,
310
+ totalPromptsEvaluated: totalPrompts,
311
+ visibilityScorePct,
312
+ citationSharePct,
313
+ byTopic,
314
+ byEngine,
315
+ competitorMentions,
316
+ intelligentUiBenchmark: PROFOUND_INTELLIGENT_UI_BENCHMARK,
317
+ };
318
+ }
319
+
320
+ if (require.main === module) {
321
+ const matrix = computeAeoVisibilityMatrix();
322
+ const darkRecovery = attributeIntelligentUiVisit({
323
+ url: 'https://thumbgate.ai/operator-framework',
324
+ referrer: '',
325
+ utmSource: '',
326
+ visitTimestampMs: 1792170050000,
327
+ recentAiBotHits: [
328
+ { userAgent: 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.0; +https://openai.com/searchbot', path: '/operator-framework', timestampMs: 1792170015000 },
329
+ ],
330
+ });
331
+ const factCheck = evaluateBrandFactCheck('ThumbGate has 300ms latency for ThumbGate and is cloud-only.');
332
+ console.log(JSON.stringify({ matrix, darkRecovery, factCheck }, null, 2));
333
+ }
334
+
335
+
336
+ const {
337
+ SUPPORTED_CHANNELS,
338
+ OFFER_ARMS,
339
+ GRAPH_RAG_KNOWLEDGE_NODES,
340
+ retrieveGraphRagEvidenceForQuery,
341
+ selectOptimalChannelOfferArm,
342
+ buildUtmTrackedUrl,
343
+ composeOmnichannelPostOrReply,
344
+ computeAttestationHash,
345
+ recordOmnichannelAttestation,
346
+ verifyOmnichannelAttestationLedger,
347
+ } = (() => {
348
+
349
+
350
+
351
+ const crypto = require('node:crypto');
352
+ const fs = require('node:fs');
353
+ const path = require('node:path');
354
+
355
+ const SUPPORTED_CHANNELS = ['linkedin', 'reddit', 'x', 'skool', 'zyvop', 'hackernews'];
356
+ const DEFAULT_ATTESTATION_LEDGER_PATH = '/Users/iganapolsky/workspace/ThumbGate/.thumbgate/omnichannel-attestation-ledger.jsonl';
357
+ const DEFAULT_SKOOL_LEDGER_PATH = '/Users/iganapolsky/workspace/ThumbGate/.thumbgate/skool-replied-ledger.json';
358
+ const OPERATOR_FRAMEWORK_URL = 'https://thumbgate.ai/operator-framework';
359
+
360
+ const OFFER_ARMS = {
361
+ sprint_diagnostic_499: {
362
+ id: 'sprint_diagnostic_499',
363
+ label: '48-Hr Production Hardening Sprint ($499)',
364
+ priceUsd: 499,
365
+ checkoutUrl: 'https://buy.stripe.com/fZueVd9eA4r42dz7mb3sI2W',
366
+ landingUrl: OPERATOR_FRAMEWORK_URL,
367
+ alphaPrior: 6,
368
+ betaPrior: 14,
369
+ },
370
+ turnkey_operator_2500: {
371
+ id: 'turnkey_operator_2500',
372
+ label: 'Turnkey Operator Framework Setup ($2,500)',
373
+ priceUsd: 2500,
374
+ checkoutUrl: 'https://buy.stripe.com/14A00kP620a0cSd35v3sI0Q',
375
+ landingUrl: OPERATOR_FRAMEWORK_URL,
376
+ alphaPrior: 3,
377
+ betaPrior: 17,
378
+ },
379
+ agency_partner_30pct: {
380
+ id: 'agency_partner_30pct',
381
+ label: '30% Recurring Agency Partner Program ($750+ per client)',
382
+ priceUsd: 750,
383
+ checkoutUrl: OPERATOR_FRAMEWORK_URL,
384
+ landingUrl: OPERATOR_FRAMEWORK_URL,
385
+ alphaPrior: 8,
386
+ betaPrior: 12,
387
+ },
388
+ };
389
+
390
+ const GRAPH_RAG_KNOWLEDGE_NODES = [
391
+ {
392
+ id: 'node:pretooluse_firewall',
393
+ keywords: ['loop', 'retry', 'agent', 'tool', 'mcp', 'kill-switch', 'guardrail', 'pretooluse', 'production'],
394
+ fact: 'ThumbGate PreToolUse evaluates and blocks destructive tool calls, retry loops, and secret exfiltration in <0.5ms (0.05ms–0.21ms measured on local CPU) with $0 token tax.',
395
+ scriptRef: 'scripts/corporate-email-isolation-diode.js',
396
+ },
397
+ {
398
+ id: 'node:openrouter_armor_zdr_hipaa',
399
+ keywords: ['openrouter', 'armor', 'hipaa', 'zdr', 'privacy', 'on-prem', 'local', 'claude', 'customs', 'compliance'],
400
+ fact: 'When cloud classifiers (such as OpenRouter Armor at 279ms median latency) return 403/unavailable under HIPAA or Zero Data Retention (ZDR), ThumbGate executes 100% locally on the host CPU in <0.2ms with zero data egress.',
401
+ scriptRef: 'scripts/openrouter-armor-partnership-diode.js',
402
+ },
403
+ {
404
+ id: 'node:ucp_financial_checkout_diode',
405
+ keywords: ['stripe', 'payment', 'checkout', 'refund', 'webhook', 'double-fire', 'n8n', 'voice', 'agency', 'freelance'],
406
+ fact: 'ThumbGate enforces SHA-256 idempotency locks and pre-action financial diodes so n8n, voice, and MCP workflows never double-charge or loop in client production.',
407
+ scriptRef: 'scripts/ucp-agentic-checkout-diode.js',
408
+ },
409
+ {
410
+ id: 'node:reflection_beam_sandbox',
411
+ keywords: ['reflection', 'beam', 'mirror', 'cli', 'sandbox', 'auto-mode', 'coding', 'hackernews', 'reddit'],
412
+ fact: 'CLI agents running in auto-approval mode execute with full host user permissions; ThumbGate gates subprocess credentials and destructive git/shell commands in 0.06ms before execution.',
413
+ scriptRef: 'scripts/reflection-beam-steal.js',
414
+ },
415
+ ];
416
+
417
+ function retrieveGraphRagEvidenceForQuery(query = '') {
418
+ const q = String(query || '').toLowerCase();
419
+ const scored = GRAPH_RAG_KNOWLEDGE_NODES.map((node) => {
420
+ const hits = node.keywords.filter((kw) => q.includes(kw)).length;
421
+ return { ...node, score: hits };
422
+ }).sort((a, b) => b.score - a.score);
423
+ const selected = scored.filter((n) => n.score > 0).slice(0, 2);
424
+ const anchors = selected.length > 0 ? selected : [GRAPH_RAG_KNOWLEDGE_NODES[0], GRAPH_RAG_KNOWLEDGE_NODES[2]];
425
+ return {
426
+ tier1Anchors: anchors.map((a) => a.id),
427
+ tier2ScriptRefs: anchors.map((a) => a.scriptRef),
428
+ tier3VerifiedFacts: anchors.map((a) => a.fact),
429
+ };
430
+ }
431
+
432
+ function selectOptimalChannelOfferArm({ channel = 'skool', query = '', observations = [] } = {}) {
433
+ const cleanChannel = String(channel || 'skool').toLowerCase();
434
+ const q = String(query || '').toLowerCase();
435
+ const armStats = {};
436
+ for (const [armId, arm] of Object.entries(OFFER_ARMS)) {
437
+ let alpha = arm.alphaPrior;
438
+ let beta = arm.betaPrior;
439
+ if ((cleanChannel === 'skool' || cleanChannel === 'linkedin') && armId === 'agency_partner_30pct') alpha += 4;
440
+ if ((cleanChannel === 'reddit' || cleanChannel === 'hackernews' || cleanChannel === 'x') && armId === 'sprint_diagnostic_499') alpha += 5;
441
+ if (/\b(?:collaborat\w*|partner\w*|agency|freelanc\w*|client)\b/.test(q) && armId === 'agency_partner_30pct') alpha += 5;
442
+ if (/\b(?:enterprise|turnkey|customs|hipaa|on-prem|architecture)\b/.test(q) && armId === 'turnkey_operator_2500') alpha += 4;
443
+ for (const obs of Array.isArray(observations) ? observations : []) {
444
+ if (obs.armId === armId && (!obs.channel || obs.channel === cleanChannel)) {
445
+ if (obs.converted || obs.replied) alpha += 2;
446
+ else beta += 1;
447
+ }
448
+ }
449
+ const conversionProb = Number((alpha / (alpha + beta)).toFixed(4));
450
+ const expectedValueUsd = Number((conversionProb * arm.priceUsd).toFixed(2));
451
+ armStats[armId] = { ...arm, alpha, beta, conversionProb, expectedValueUsd };
452
+ }
453
+ const ranked = Object.values(armStats).sort((a, b) => b.expectedValueUsd - a.expectedValueUsd);
454
+ const chosen = ranked[0];
455
+ const rejected = ranked[ranked.length - 1];
456
+ return {
457
+ channel: cleanChannel,
458
+ chosenArm: chosen,
459
+ allArms: ranked,
460
+ dpoPair: {
461
+ promptContext: `${cleanChannel}: ${String(query).slice(0, 120)}`,
462
+ chosenArmId: chosen.id,
463
+ rejectedArmId: rejected.id,
464
+ expectedValueDeltaUsd: Number((chosen.expectedValueUsd - rejected.expectedValueUsd).toFixed(2)),
465
+ },
466
+ };
467
+ }
468
+
469
+ function buildUtmTrackedUrl(baseUrl, { channel, campaign = 'omnichannel_ml_graphrag_20261017', content = 'reply' } = {}) {
470
+ const u = new URL(baseUrl);
471
+ u.searchParams.set('utm_source', String(channel || 'direct').toLowerCase());
472
+ u.searchParams.set('utm_medium', 'agentic_organic');
473
+ u.searchParams.set('utm_campaign', campaign);
474
+ u.searchParams.set('utm_content', content);
475
+ return u.toString();
476
+ }
477
+
478
+ function composeOmnichannelPostOrReply({
479
+ channel = 'skool',
480
+ targetUrl = 'https://www.skool.com/ai-freelancers',
481
+ authorOrCommunity = '',
482
+ threadTitleOrText = '',
483
+ observations = [],
484
+ } = {}) {
485
+ const cleanChannel = String(channel || 'skool').toLowerCase();
486
+ if (!SUPPORTED_CHANNELS.includes(cleanChannel)) throw new Error(`Unsupported channel: ${channel}`);
487
+ const rag = retrieveGraphRagEvidenceForQuery(threadTitleOrText);
488
+ const ml = selectOptimalChannelOfferArm({ channel: cleanChannel, query: threadTitleOrText, observations });
489
+ const utmLandingUrl = buildUtmTrackedUrl(ml.chosenArm.landingUrl, { channel: cleanChannel, content: ml.chosenArm.id });
490
+ const prefix = authorOrCommunity && cleanChannel === 'skool' ? `@${authorOrCommunity} ` : '';
491
+ const body = `${prefix}${rag.tier3VerifiedFacts[0]} Full architecture, 7-day pilot blueprint, ${ml.chosenArm.label}, and 30% recurring agency partner program: ${utmLandingUrl}`;
492
+ return { channel: cleanChannel, targetUrl, authorOrCommunity, body, utmLandingUrl, graphRag: rag, mlBandit: ml };
493
+ }
494
+
495
+ function computeAttestationHash(payload, prevHash = 'GENESIS') {
496
+ const canonical = JSON.stringify({
497
+ prevHash,
498
+ channel: payload.channel,
499
+ targetUrl: payload.targetUrl,
500
+ utmLandingUrl: payload.utmLandingUrl,
501
+ chosenArmId: payload.mlBandit?.chosenArm?.id || payload.chosenArmId,
502
+ graphRagAnchors: payload.graphRag?.tier1Anchors || payload.graphRagAnchors,
503
+ bodySha256: crypto.createHash('sha256').update(String(payload.body || '')).digest('hex'),
504
+ timestamp: payload.timestamp,
505
+ });
506
+ return crypto.createHash('sha256').update(canonical).digest('hex');
507
+ }
508
+
509
+ function recordOmnichannelAttestation(engagement, ledgerPath = DEFAULT_ATTESTATION_LEDGER_PATH) {
510
+ fs.mkdirSync(path.dirname(ledgerPath), { recursive: true });
511
+ let prevHash = 'GENESIS';
512
+ if (fs.existsSync(ledgerPath)) {
513
+ const lines = fs.readFileSync(ledgerPath, 'utf8').trim().split('\n').filter(Boolean);
514
+ if (lines.length > 0) {
515
+ try {
516
+ const last = JSON.parse(lines[lines.length - 1]);
517
+ if (last.attestationSha256) prevHash = last.attestationSha256;
518
+ } catch (_) {}
519
+ }
520
+ }
521
+ const timestamp = engagement.timestamp || new Date().toISOString();
522
+ const entryBase = {
523
+ timestamp,
524
+ channel: engagement.channel,
525
+ targetUrl: engagement.targetUrl,
526
+ authorOrCommunity: engagement.authorOrCommunity || '',
527
+ utmLandingUrl: engagement.utmLandingUrl,
528
+ chosenArmId: engagement.mlBandit?.chosenArm?.id || engagement.chosenArmId || 'sprint_diagnostic_499',
529
+ expectedValueUsd: engagement.mlBandit?.chosenArm?.expectedValueUsd || 0,
530
+ graphRagAnchors: engagement.graphRag?.tier1Anchors || [],
531
+ body: engagement.body || '',
532
+ prevHash,
533
+ };
534
+ const attestationSha256 = computeAttestationHash(entryBase, prevHash);
535
+ const record = { ...entryBase, attestationSha256 };
536
+ fs.appendFileSync(ledgerPath, JSON.stringify(record) + '\n', 'utf8');
537
+ return record;
538
+ }
539
+
540
+ function verifyOmnichannelAttestationLedger(ledgerPath = DEFAULT_ATTESTATION_LEDGER_PATH) {
541
+ if (!fs.existsSync(ledgerPath)) return { valid: true, totalEntries: 0, byChannel: {}, totalExpectedPipelineUsd: 0 };
542
+ const lines = fs.readFileSync(ledgerPath, 'utf8').trim().split('\n').filter(Boolean);
543
+ let prevHash = 'GENESIS';
544
+ const byChannel = {};
545
+ let totalExpectedPipelineUsd = 0;
546
+ for (let i = 0; i < lines.length; i += 1) {
547
+ const row = JSON.parse(lines[i]);
548
+ const expectedHash = computeAttestationHash(row, prevHash);
549
+ if (row.prevHash !== prevHash || row.attestationSha256 !== expectedHash) {
550
+ return { valid: false, brokenAtIndex: i, totalEntries: lines.length };
551
+ }
552
+ prevHash = row.attestationSha256;
553
+ byChannel[row.channel] = (byChannel[row.channel] || 0) + 1;
554
+ totalExpectedPipelineUsd = Number((totalExpectedPipelineUsd + Number(row.expectedValueUsd || 0)).toFixed(2));
555
+ }
556
+ return { valid: true, totalEntries: lines.length, headAttestationSha256: prevHash, byChannel, totalExpectedPipelineUsd };
557
+ }
558
+
559
+
560
+ return { SUPPORTED_CHANNELS, OFFER_ARMS, GRAPH_RAG_KNOWLEDGE_NODES, retrieveGraphRagEvidenceForQuery, selectOptimalChannelOfferArm, buildUtmTrackedUrl, composeOmnichannelPostOrReply, computeAttestationHash, recordOmnichannelAttestation, verifyOmnichannelAttestationLedger };
561
+ })();
562
+
563
+ module.exports = {
564
+ SUPPORTED_CHANNELS,
565
+ OFFER_ARMS,
566
+ GRAPH_RAG_KNOWLEDGE_NODES,
567
+ retrieveGraphRagEvidenceForQuery,
568
+ selectOptimalChannelOfferArm,
569
+ buildUtmTrackedUrl,
570
+ composeOmnichannelPostOrReply,
571
+ computeAttestationHash,
572
+ recordOmnichannelAttestation,
573
+ verifyOmnichannelAttestationLedger,
574
+ PROFOUND_INTELLIGENT_UI_BENCHMARK,
575
+ CANONICAL_THUMBGATE_CONTEXT,
576
+ DEFAULT_DEMO_AEO_SAMPLES,
577
+ classifyAiCrawlerBot,
578
+ isOpenAiReferrerHost,
579
+ isOwnedThumbGateCitationUrl,
580
+ attributeIntelligentUiVisit,
581
+ evaluateBrandFactCheck,
582
+ computeAeoVisibilityMatrix,
583
+ };