thumbgate 0.9.10

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 (364) hide show
  1. package/.claude-plugin/README.md +134 -0
  2. package/.claude-plugin/bundle/icon.png +0 -0
  3. package/.claude-plugin/bundle/icon.svg +18 -0
  4. package/.claude-plugin/bundle/server/index.js +24 -0
  5. package/.claude-plugin/marketplace.json +36 -0
  6. package/.claude-plugin/plugin.json +21 -0
  7. package/.well-known/mcp/server-card.json +231 -0
  8. package/LICENSE +21 -0
  9. package/README.md +375 -0
  10. package/adapters/README.md +9 -0
  11. package/adapters/amp/skills/thumbgate-feedback/SKILL.md +22 -0
  12. package/adapters/chatgpt/INSTALL.md +83 -0
  13. package/adapters/chatgpt/openapi.yaml +1281 -0
  14. package/adapters/claude/.mcp.json +14 -0
  15. package/adapters/codex/config.toml +9 -0
  16. package/adapters/gemini/function-declarations.json +224 -0
  17. package/adapters/mcp/server-stdio.js +788 -0
  18. package/adapters/opencode/opencode.json +15 -0
  19. package/bin/cli.js +1484 -0
  20. package/bin/memory.sh +64 -0
  21. package/bin/obsidian-sync.sh +20 -0
  22. package/bin/postinstall.js +37 -0
  23. package/config/build-metadata.json +4 -0
  24. package/config/e2e-critical-flows.json +45 -0
  25. package/config/gate-templates.json +77 -0
  26. package/config/gates/claim-verification.json +29 -0
  27. package/config/gates/computer-use.json +39 -0
  28. package/config/gates/default.json +117 -0
  29. package/config/github-about.json +25 -0
  30. package/config/mcp-allowlists.json +135 -0
  31. package/config/model-tiers.json +33 -0
  32. package/config/partner-routing.json +132 -0
  33. package/config/policy-bundles/constrained-v1.json +64 -0
  34. package/config/policy-bundles/default-v1.json +91 -0
  35. package/config/rubrics/default-v1.json +52 -0
  36. package/config/skill-packs/react-testing.json +23 -0
  37. package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
  38. package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
  39. package/config/skill-specs/pr-reviewer.json +9 -0
  40. package/config/skill-specs/release-status.json +9 -0
  41. package/config/skill-specs/ticket-triage.json +9 -0
  42. package/config/subagent-profiles.json +32 -0
  43. package/config/tessl-tiles.json +29 -0
  44. package/config/thumbgate-settings.managed.json +12 -0
  45. package/openapi/openapi.yaml +1281 -0
  46. package/package.json +283 -0
  47. package/plugins/amp-skill/INSTALL.md +52 -0
  48. package/plugins/amp-skill/SKILL.md +64 -0
  49. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
  50. package/plugins/claude-codex-bridge/.mcp.json +12 -0
  51. package/plugins/claude-codex-bridge/INSTALL.md +43 -0
  52. package/plugins/claude-codex-bridge/README.md +46 -0
  53. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
  54. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
  55. package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
  56. package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
  57. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
  58. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
  59. package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
  60. package/plugins/claude-skill/INSTALL.md +55 -0
  61. package/plugins/claude-skill/SKILL.md +46 -0
  62. package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
  63. package/plugins/codex-profile/.mcp.json +12 -0
  64. package/plugins/codex-profile/AGENTS.md +20 -0
  65. package/plugins/codex-profile/INSTALL.md +66 -0
  66. package/plugins/codex-profile/README.md +37 -0
  67. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
  68. package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
  69. package/plugins/cursor-marketplace/LICENSE +21 -0
  70. package/plugins/cursor-marketplace/README.md +124 -0
  71. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
  72. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  73. package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
  74. package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
  75. package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
  76. package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
  77. package/plugins/cursor-marketplace/mcp.json +12 -0
  78. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
  79. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
  80. package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
  81. package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
  82. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
  83. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
  84. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
  85. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
  86. package/plugins/gemini-extension/INSTALL.md +92 -0
  87. package/plugins/gemini-extension/gemini_prompt.txt +14 -0
  88. package/plugins/gemini-extension/tool_contract.json +45 -0
  89. package/plugins/opencode-profile/INSTALL.md +57 -0
  90. package/public/assets/instagram-card.png +0 -0
  91. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  92. package/public/blog.html +400 -0
  93. package/public/dashboard.html +1093 -0
  94. package/public/guide.html +317 -0
  95. package/public/index.html +1014 -0
  96. package/public/learn/agent-harness-pattern.html +180 -0
  97. package/public/learn/ai-agent-persistent-memory.html +202 -0
  98. package/public/learn/learn.css +45 -0
  99. package/public/learn/mcp-pre-action-gates-explained.html +172 -0
  100. package/public/learn/stop-ai-agent-force-push.html +134 -0
  101. package/public/learn/vibe-coding-safety-net.html +142 -0
  102. package/public/learn.html +213 -0
  103. package/public/lessons.html +650 -0
  104. package/public/vercel.json +8 -0
  105. package/scripts/__pycache__/train_from_feedback.cpython-312.pyc +0 -0
  106. package/scripts/a2ui-engine.js +73 -0
  107. package/scripts/access-anomaly-detector.js +12 -0
  108. package/scripts/adk-consolidator.js +266 -0
  109. package/scripts/agent-readiness.js +220 -0
  110. package/scripts/agent-security-hardening.js +227 -0
  111. package/scripts/agentic-data-pipeline.js +847 -0
  112. package/scripts/analytics-report.js +328 -0
  113. package/scripts/analytics-window.js +158 -0
  114. package/scripts/async-job-runner.js +1001 -0
  115. package/scripts/audit-trail.js +398 -0
  116. package/scripts/auto-promote-gates.js +299 -0
  117. package/scripts/auto-wire-hooks.js +312 -0
  118. package/scripts/autonomous-sales-agent.js +39 -0
  119. package/scripts/autoresearch-runner.js +216 -0
  120. package/scripts/background-agent-governance.js +237 -0
  121. package/scripts/behavioral-extraction.js +97 -0
  122. package/scripts/belief-update.js +84 -0
  123. package/scripts/billing.js +2438 -0
  124. package/scripts/bot-detector.js +50 -0
  125. package/scripts/budget-guard.js +173 -0
  126. package/scripts/build-claude-mcpb.js +189 -0
  127. package/scripts/build-metadata.js +97 -0
  128. package/scripts/check-congruence.js +322 -0
  129. package/scripts/cli-feedback.js +135 -0
  130. package/scripts/cli-telemetry.js +87 -0
  131. package/scripts/cloudflare-dynamic-sandbox.js +315 -0
  132. package/scripts/code-reasoning.js +350 -0
  133. package/scripts/codegraph-context.js +466 -0
  134. package/scripts/commercial-offer.js +56 -0
  135. package/scripts/computer-use-firewall.js +250 -0
  136. package/scripts/context-engine.js +694 -0
  137. package/scripts/contextfs.js +1287 -0
  138. package/scripts/conversation-context.js +119 -0
  139. package/scripts/creator-campaigns.js +239 -0
  140. package/scripts/daemon-manager.js +108 -0
  141. package/scripts/daily-digest.js +11 -0
  142. package/scripts/dashboard-render-spec.js +395 -0
  143. package/scripts/dashboard.js +1058 -0
  144. package/scripts/data-governance.js +173 -0
  145. package/scripts/delegation-runtime.js +900 -0
  146. package/scripts/deploy-gcp.sh +44 -0
  147. package/scripts/deploy-policy.js +263 -0
  148. package/scripts/disagreement-mining.js +315 -0
  149. package/scripts/dispatch-brief.js +159 -0
  150. package/scripts/distribution-surfaces.js +44 -0
  151. package/scripts/dpo-optimizer.js +209 -0
  152. package/scripts/ephemeral-agent-store.js +219 -0
  153. package/scripts/eval-harness.js +56 -0
  154. package/scripts/evolution-state.js +241 -0
  155. package/scripts/experiment-tracker.js +267 -0
  156. package/scripts/export-databricks-bundle.js +242 -0
  157. package/scripts/export-dpo-pairs.js +345 -0
  158. package/scripts/export-kto-pairs.js +310 -0
  159. package/scripts/export-training.js +448 -0
  160. package/scripts/failure-diagnostics.js +558 -0
  161. package/scripts/feedback-attribution.js +313 -0
  162. package/scripts/feedback-fallback.js +111 -0
  163. package/scripts/feedback-history-distiller.js +391 -0
  164. package/scripts/feedback-inbox-read.js +162 -0
  165. package/scripts/feedback-loop.js +1887 -0
  166. package/scripts/feedback-paths.js +145 -0
  167. package/scripts/feedback-quality.js +139 -0
  168. package/scripts/feedback-root-consolidator.js +238 -0
  169. package/scripts/feedback-schema.js +426 -0
  170. package/scripts/feedback-session.js +286 -0
  171. package/scripts/feedback-to-memory.js +185 -0
  172. package/scripts/feedback-to-rules.js +163 -0
  173. package/scripts/filesystem-search.js +404 -0
  174. package/scripts/funnel-analytics.js +35 -0
  175. package/scripts/gate-satisfy.js +42 -0
  176. package/scripts/gate-stats.js +116 -0
  177. package/scripts/gate-templates.js +70 -0
  178. package/scripts/gates-engine.js +816 -0
  179. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  180. package/scripts/generate-pretool-hook.sh +40 -0
  181. package/scripts/github-about.js +350 -0
  182. package/scripts/github-outreach.js +65 -0
  183. package/scripts/gtm-revenue-loop.js +520 -0
  184. package/scripts/hallucination-detector.js +226 -0
  185. package/scripts/hf-papers.js +317 -0
  186. package/scripts/history-distiller.js +200 -0
  187. package/scripts/hook-auto-capture.sh +95 -0
  188. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  189. package/scripts/hook-stop-self-score.sh +51 -0
  190. package/scripts/hook-stop-verify-deploy.sh +31 -0
  191. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  192. package/scripts/hook-verify-before-done.sh +20 -0
  193. package/scripts/hosted-config.js +170 -0
  194. package/scripts/hybrid-feedback-context.js +676 -0
  195. package/scripts/install-mcp.js +159 -0
  196. package/scripts/intent-router.js +392 -0
  197. package/scripts/internal-agent-bootstrap.js +490 -0
  198. package/scripts/jsonl-watcher.js +155 -0
  199. package/scripts/lesson-db.js +613 -0
  200. package/scripts/lesson-inference.js +315 -0
  201. package/scripts/lesson-retrieval.js +95 -0
  202. package/scripts/lesson-rotation.js +137 -0
  203. package/scripts/lesson-search.js +644 -0
  204. package/scripts/lesson-synthesis.js +196 -0
  205. package/scripts/license.js +50 -0
  206. package/scripts/local-model-profile.js +383 -0
  207. package/scripts/markdown-escape.js +12 -0
  208. package/scripts/marketing-experiment.js +671 -0
  209. package/scripts/mcp-config.js +149 -0
  210. package/scripts/mcp-policy.js +99 -0
  211. package/scripts/memalign-recall.js +111 -0
  212. package/scripts/memory-firewall.js +222 -0
  213. package/scripts/memory-migration.js +296 -0
  214. package/scripts/meta-policy.js +194 -0
  215. package/scripts/metered-billing.js +16 -0
  216. package/scripts/model-tier-router.js +301 -0
  217. package/scripts/money-watcher.js +71 -0
  218. package/scripts/multi-hop-recall.js +240 -0
  219. package/scripts/natural-language-harness.js +330 -0
  220. package/scripts/obsidian-export.js +712 -0
  221. package/scripts/operational-dashboard.js +103 -0
  222. package/scripts/operational-summary.js +93 -0
  223. package/scripts/optimize-context.js +17 -0
  224. package/scripts/org-dashboard.js +201 -0
  225. package/scripts/partner-orchestration.js +146 -0
  226. package/scripts/per-step-scoring.js +165 -0
  227. package/scripts/perplexity-marketing.js +466 -0
  228. package/scripts/pii-scanner.js +153 -0
  229. package/scripts/plan-gate.js +154 -0
  230. package/scripts/post-everywhere.js +308 -0
  231. package/scripts/post-to-x-retry.sh +22 -0
  232. package/scripts/post-to-x.js +369 -0
  233. package/scripts/pr-manager.js +236 -0
  234. package/scripts/predictive-insights.js +356 -0
  235. package/scripts/principle-extractor.js +162 -0
  236. package/scripts/pro-features.js +40 -0
  237. package/scripts/pro-local-dashboard.js +174 -0
  238. package/scripts/problem-detail.js +53 -0
  239. package/scripts/product-feedback.js +134 -0
  240. package/scripts/profile-router.js +245 -0
  241. package/scripts/prompt-dlp.js +221 -0
  242. package/scripts/prompt-guard.js +83 -0
  243. package/scripts/prove-adapters.js +863 -0
  244. package/scripts/prove-attribution.js +365 -0
  245. package/scripts/prove-automation.js +653 -0
  246. package/scripts/prove-autoresearch.js +304 -0
  247. package/scripts/prove-claim-verification.js +277 -0
  248. package/scripts/prove-cloudflare-sandbox.js +163 -0
  249. package/scripts/prove-data-pipeline.js +410 -0
  250. package/scripts/prove-data-quality.js +227 -0
  251. package/scripts/prove-evolution.js +352 -0
  252. package/scripts/prove-harnesses.js +287 -0
  253. package/scripts/prove-intelligence.js +259 -0
  254. package/scripts/prove-lancedb.js +371 -0
  255. package/scripts/prove-local-intelligence.js +342 -0
  256. package/scripts/prove-loop-closure.js +263 -0
  257. package/scripts/prove-predictive-insights.js +357 -0
  258. package/scripts/prove-runtime.js +350 -0
  259. package/scripts/prove-seo-gsd.js +234 -0
  260. package/scripts/prove-settings.js +279 -0
  261. package/scripts/prove-subway-upgrades.js +277 -0
  262. package/scripts/prove-tessl.js +229 -0
  263. package/scripts/prove-training-export.js +327 -0
  264. package/scripts/prove-workflow-contract.js +116 -0
  265. package/scripts/prove-xmemory.js +332 -0
  266. package/scripts/publish-decision.js +133 -0
  267. package/scripts/pulse.js +80 -0
  268. package/scripts/rate-limiter.js +125 -0
  269. package/scripts/reddit-dm-outreach.js +182 -0
  270. package/scripts/reddit-monitor-cron.sh +26 -0
  271. package/scripts/reflector-agent.js +221 -0
  272. package/scripts/reminder-engine.js +132 -0
  273. package/scripts/revenue-status.js +472 -0
  274. package/scripts/risk-scorer.js +458 -0
  275. package/scripts/rlaif-self-audit.js +129 -0
  276. package/scripts/rubric-engine.js +230 -0
  277. package/scripts/schedule-manager.js +251 -0
  278. package/scripts/secret-scanner.js +414 -0
  279. package/scripts/self-heal.js +147 -0
  280. package/scripts/self-healing-check.js +188 -0
  281. package/scripts/semantic-layer.js +98 -0
  282. package/scripts/seo-gsd.js +1153 -0
  283. package/scripts/settings-hierarchy.js +214 -0
  284. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  285. package/scripts/skill-exporter.js +262 -0
  286. package/scripts/skill-generator.js +446 -0
  287. package/scripts/skill-materializer.js +134 -0
  288. package/scripts/skill-packs.js +136 -0
  289. package/scripts/skill-proposer.js +99 -0
  290. package/scripts/skill-quality-tracker.js +284 -0
  291. package/scripts/slo-alert-engine.js +14 -0
  292. package/scripts/slow-loop.js +72 -0
  293. package/scripts/social-analytics/db/schema.sql +32 -0
  294. package/scripts/social-analytics/digest.js +256 -0
  295. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  296. package/scripts/social-analytics/instagram-thumbgate-post.js +73 -0
  297. package/scripts/social-analytics/mcp-server.js +289 -0
  298. package/scripts/social-analytics/normalizer.js +580 -0
  299. package/scripts/social-analytics/notify.js +162 -0
  300. package/scripts/social-analytics/poll-all.js +107 -0
  301. package/scripts/social-analytics/pollers/github.js +195 -0
  302. package/scripts/social-analytics/pollers/instagram.js +253 -0
  303. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  304. package/scripts/social-analytics/pollers/plausible.js +247 -0
  305. package/scripts/social-analytics/pollers/reddit.js +306 -0
  306. package/scripts/social-analytics/pollers/threads.js +233 -0
  307. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  308. package/scripts/social-analytics/pollers/x.js +227 -0
  309. package/scripts/social-analytics/pollers/youtube.js +304 -0
  310. package/scripts/social-analytics/pollers/zernio.js +180 -0
  311. package/scripts/social-analytics/publish-instagram-thumbgate.js +85 -0
  312. package/scripts/social-analytics/publishers/devto.js +122 -0
  313. package/scripts/social-analytics/publishers/instagram.js +317 -0
  314. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  315. package/scripts/social-analytics/publishers/reddit.js +390 -0
  316. package/scripts/social-analytics/publishers/threads.js +275 -0
  317. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  318. package/scripts/social-analytics/publishers/x.js +259 -0
  319. package/scripts/social-analytics/publishers/youtube.js +223 -0
  320. package/scripts/social-analytics/publishers/zernio.js +209 -0
  321. package/scripts/social-analytics/run-digest.js +34 -0
  322. package/scripts/social-analytics/store.js +257 -0
  323. package/scripts/social-analytics/utm.js +143 -0
  324. package/scripts/social-pipeline.js +2628 -0
  325. package/scripts/social-quality-gate.js +18 -0
  326. package/scripts/social-reply-monitor.js +445 -0
  327. package/scripts/status-dashboard.js +155 -0
  328. package/scripts/statusline-lesson.js +16 -0
  329. package/scripts/statusline-tower.js +8 -0
  330. package/scripts/statusline.sh +116 -0
  331. package/scripts/stripe-live-status.js +115 -0
  332. package/scripts/subagent-profiles.js +79 -0
  333. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  334. package/scripts/sync-github-about.js +52 -0
  335. package/scripts/sync-version.js +451 -0
  336. package/scripts/synthetic-dpo.js +234 -0
  337. package/scripts/telemetry-analytics.js +821 -0
  338. package/scripts/tessl-export.js +371 -0
  339. package/scripts/test-coverage.js +120 -0
  340. package/scripts/thompson-sampling.js +417 -0
  341. package/scripts/thumbgate-search.js +189 -0
  342. package/scripts/tool-kpi-tracker.js +12 -0
  343. package/scripts/tool-registry.js +811 -0
  344. package/scripts/train_from_feedback.py +910 -0
  345. package/scripts/user-profile.js +78 -0
  346. package/scripts/validate-feedback.js +580 -0
  347. package/scripts/validate-workflow-contract.js +287 -0
  348. package/scripts/vector-store.js +198 -0
  349. package/scripts/verification-loop.js +291 -0
  350. package/scripts/verify-obsidian-setup.sh +269 -0
  351. package/scripts/verify-run.js +269 -0
  352. package/scripts/webhook-delivery.js +62 -0
  353. package/scripts/weekly-auto-post.js +124 -0
  354. package/scripts/workflow-runs.js +154 -0
  355. package/scripts/workflow-sprint-intake.js +475 -0
  356. package/scripts/workspace-evolver.js +374 -0
  357. package/scripts/x-autonomous-marketing.js +139 -0
  358. package/scripts/xmemory-lite.js +405 -0
  359. package/skills/agent-memory/SKILL.md +97 -0
  360. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  361. package/skills/solve-architecture-autonomy/tool.js +33 -0
  362. package/skills/thumbgate/SKILL.md +114 -0
  363. package/skills/thumbgate-feedback/SKILL.md +49 -0
  364. package/src/api/server.js +4208 -0
@@ -0,0 +1,821 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const {
7
+ filterEntriesForWindow,
8
+ resolveAnalyticsWindow,
9
+ serializeAnalyticsWindow,
10
+ } = require('./analytics-window');
11
+ const {
12
+ getLegacyFeedbackDir,
13
+ getFallbackFeedbackDir,
14
+ resolveFallbackArtifactPath,
15
+ } = require('./feedback-paths');
16
+
17
+ const TELEMETRY_FILE_NAME = 'telemetry-pings.jsonl';
18
+
19
+ function shouldIncludeLegacyTelemetry() {
20
+ if (
21
+ process.env._TEST_LEGACY_FEEDBACK_DIR ||
22
+ process.env.THUMBGATE_LEGACY_FEEDBACK_DIR ||
23
+ process.env._TEST_THUMBGATE_FALLBACK_FEEDBACK_DIR ||
24
+ process.env.THUMBGATE_FALLBACK_FEEDBACK_DIR
25
+ ) {
26
+ return true;
27
+ }
28
+ return process.env.NODE_ENV !== 'test';
29
+ }
30
+
31
+ function shouldMergeLegacyTelemetry() {
32
+ return process.env._TEST_INCLUDE_LEGACY_TELEMETRY === '1'
33
+ || process.env.THUMBGATE_INCLUDE_LEGACY_TELEMETRY === '1';
34
+ }
35
+
36
+ function normalizeText(value, maxLength = 160) {
37
+ if (value === undefined || value === null) return null;
38
+ const text = String(value).trim();
39
+ if (!text) return null;
40
+ return text.slice(0, maxLength);
41
+ }
42
+
43
+ function pickFirstText(...values) {
44
+ for (const value of values) {
45
+ const normalized = normalizeText(value);
46
+ if (normalized) return normalized;
47
+ }
48
+ return null;
49
+ }
50
+
51
+ function incrementCounter(counter, key, amount = 1) {
52
+ const resolvedKey = normalizeText(key) || 'unknown';
53
+ counter[resolvedKey] = (counter[resolvedKey] || 0) + amount;
54
+ }
55
+
56
+ function normalizeInteger(value) {
57
+ if (value === undefined || value === null || value === '') return null;
58
+ const parsed = Number(value);
59
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : null;
60
+ }
61
+
62
+ function safeRate(num, den) {
63
+ if (!den) return 0;
64
+ return Number((num / den).toFixed(4));
65
+ }
66
+
67
+ function getTelemetryPath(feedbackDir) {
68
+ return path.join(feedbackDir, TELEMETRY_FILE_NAME);
69
+ }
70
+
71
+ function getLegacyTelemetryPath(feedbackDir) {
72
+ const resolvedFallbackPath = resolveFallbackArtifactPath(TELEMETRY_FILE_NAME, {
73
+ feedbackDir,
74
+ });
75
+ if (!resolvedFallbackPath) return null;
76
+ const resolvedFeedbackDir = path.resolve(feedbackDir || '.');
77
+ if (path.resolve(path.dirname(resolvedFallbackPath)) === resolvedFeedbackDir) {
78
+ return null;
79
+ }
80
+ return resolvedFallbackPath;
81
+ }
82
+
83
+ function buildSourceWarning(code, message) {
84
+ return { code, message };
85
+ }
86
+
87
+ function getTelemetrySourceDiagnostics(feedbackDir) {
88
+ const primaryPath = getTelemetryPath(feedbackDir);
89
+ const legacyPath = shouldIncludeLegacyTelemetry() ? getLegacyTelemetryPath(feedbackDir) : null;
90
+ const primaryExists = fs.existsSync(primaryPath);
91
+ const legacyExists = Boolean(legacyPath && fs.existsSync(legacyPath));
92
+ const activePaths = [];
93
+ const warnings = [];
94
+ let activeMode = 'missing';
95
+
96
+ if (primaryExists && legacyExists && shouldMergeLegacyTelemetry()) {
97
+ activePaths.push(primaryPath, legacyPath);
98
+ activeMode = 'merged';
99
+ warnings.push(buildSourceWarning(
100
+ 'telemetry_mixed_roots',
101
+ 'Telemetry exists in both the active and legacy feedback directories; analytics merged both sources.'
102
+ ));
103
+ } else if (primaryExists) {
104
+ activePaths.push(primaryPath);
105
+ activeMode = 'primary';
106
+ } else if (legacyExists) {
107
+ activePaths.push(legacyPath);
108
+ activeMode = 'legacy_fallback';
109
+ warnings.push(buildSourceWarning(
110
+ 'telemetry_legacy_fallback',
111
+ 'Telemetry exists only in the legacy feedback directory; analytics fell back to legacy telemetry.'
112
+ ));
113
+ } else {
114
+ warnings.push(buildSourceWarning(
115
+ 'telemetry_missing',
116
+ 'Telemetry is missing from both the active and legacy feedback directories.'
117
+ ));
118
+ }
119
+
120
+ return {
121
+ fileName: TELEMETRY_FILE_NAME,
122
+ primaryPath,
123
+ legacyPath,
124
+ fallbackPath: path.join(getFallbackFeedbackDir({ feedbackDir }), TELEMETRY_FILE_NAME),
125
+ legacyFeedbackPath: path.join(getLegacyFeedbackDir({ feedbackDir }), TELEMETRY_FILE_NAME),
126
+ primaryExists,
127
+ legacyExists,
128
+ activeMode,
129
+ activePaths,
130
+ mixedRoots: activeMode === 'merged',
131
+ warnings,
132
+ };
133
+ }
134
+
135
+ function inferClientType(payload) {
136
+ const explicit = pickFirstText(payload.clientType, payload.client, payload.origin);
137
+ if (explicit) return explicit.toLowerCase();
138
+ if (pickFirstText(payload.page, payload.landingPath, payload.ctaId, payload.visitorId, payload.sessionId)) {
139
+ return 'web';
140
+ }
141
+ if (pickFirstText(payload.platform, payload.nodeVersion, payload.installId)) {
142
+ return 'cli';
143
+ }
144
+ return 'unknown';
145
+ }
146
+
147
+ function inferEventType(payload, clientType) {
148
+ const explicit = pickFirstText(payload.eventType, payload.event, payload.kind);
149
+ if (explicit) {
150
+ const normalized = explicit.toLowerCase();
151
+ if (normalized === 'checkout_cta_clicked') return 'checkout_start';
152
+ if (normalized === 'cli_ping') return 'cli_init';
153
+ return normalized;
154
+ }
155
+ if (clientType === 'web' && pickFirstText(payload.ctaId)) return 'checkout_start';
156
+ if (clientType === 'web') return 'landing_page_view';
157
+ if (clientType === 'cli') return 'cli_init';
158
+ return 'ping';
159
+ }
160
+
161
+ function parseReferrerHost(referrer) {
162
+ if (!referrer) return null;
163
+ try {
164
+ return new URL(referrer).host || null;
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+
170
+ function normalizeHostToken(value) {
171
+ const text = normalizeText(value, 255);
172
+ return text ? text.toLowerCase() : null;
173
+ }
174
+
175
+ function inferTrafficChannel(raw = {}, referrerHost = null) {
176
+ const source = normalizeHostToken(raw.source || raw.utmSource);
177
+ const medium = normalizeHostToken(raw.utmMedium);
178
+ const seoSurface = normalizeHostToken(raw.seoSurface || raw.searchSurface || raw.surface);
179
+ const host = normalizeHostToken(referrerHost);
180
+
181
+ if (source === 'producthunt') return 'producthunt';
182
+ if (source === 'reddit') return 'reddit';
183
+ if (medium === 'creator_partnership') return 'creator';
184
+ if (source === 'ai_search' || seoSurface === 'ai_search') return 'ai_search';
185
+ if (source === 'organic_search' || seoSurface === 'organic_search') return 'organic_search';
186
+ if (source === 'direct') return 'direct';
187
+ if (source === 'website' && !host) return 'direct';
188
+ if (medium === 'listing' && source === 'producthunt') return 'producthunt';
189
+ if (medium === 'organic') return 'organic_search';
190
+
191
+ const aiHosts = [
192
+ 'perplexity.ai',
193
+ 'chatgpt.com',
194
+ 'chat.openai.com',
195
+ 'claude.ai',
196
+ 'gemini.google.com',
197
+ ];
198
+ if (host && aiHosts.some((candidate) => host === candidate || host.endsWith(`.${candidate}`))) {
199
+ return 'ai_search';
200
+ }
201
+
202
+ const productHuntHosts = [
203
+ 'producthunt.com',
204
+ 'www.producthunt.com',
205
+ ];
206
+ if (host && productHuntHosts.some((candidate) => host === candidate || host.endsWith(`.${candidate}`))) {
207
+ return 'producthunt';
208
+ }
209
+
210
+ const redditHosts = [
211
+ 'reddit.com',
212
+ 'www.reddit.com',
213
+ 'old.reddit.com',
214
+ 'np.reddit.com',
215
+ 'out.reddit.com',
216
+ 'redd.it',
217
+ ];
218
+ if (host && redditHosts.some((candidate) => host === candidate || host.endsWith(`.${candidate}`))) {
219
+ return 'reddit';
220
+ }
221
+
222
+ const searchHosts = [
223
+ 'google.com',
224
+ 'bing.com',
225
+ 'duckduckgo.com',
226
+ 'search.yahoo.com',
227
+ 'search.brave.com',
228
+ 'ecosia.org',
229
+ ];
230
+ if (host && searchHosts.some((candidate) => host === candidate || host.endsWith(`.${candidate}`))) {
231
+ return 'organic_search';
232
+ }
233
+
234
+ if (!host) return 'direct';
235
+ return 'referral';
236
+ }
237
+
238
+ function sanitizeTelemetryPayload(payload = {}, headers = {}) {
239
+ const raw = payload && typeof payload === 'object' ? payload : {};
240
+ const clientType = inferClientType(raw);
241
+ const eventType = inferEventType(raw, clientType);
242
+ const source = pickFirstText(raw.source, raw.utmSource, clientType === 'cli' ? 'cli' : 'direct');
243
+ const utmSource = pickFirstText(raw.utmSource, raw.source, clientType === 'web' ? source : null);
244
+ const utmMedium = pickFirstText(raw.utmMedium, clientType === 'web' ? 'landing_page' : clientType);
245
+ const utmCampaign = pickFirstText(raw.utmCampaign, raw.campaign, clientType === 'web' ? 'organic' : null);
246
+ const referrer = pickFirstText(raw.referrer, headers.referer, headers.referrer);
247
+ const referrerHost = parseReferrerHost(referrer);
248
+ const reasonCode = pickFirstText(
249
+ raw.reasonCode,
250
+ raw.reason,
251
+ raw.cancelReason,
252
+ raw.lossReason,
253
+ raw.abandonReason
254
+ );
255
+ const entry = {
256
+ receivedAt: new Date().toISOString(),
257
+ client: clientType,
258
+ clientType,
259
+ event: eventType,
260
+ eventType,
261
+ installId: pickFirstText(raw.installId),
262
+ visitorId: pickFirstText(raw.visitorId),
263
+ sessionId: pickFirstText(raw.sessionId),
264
+ traceId: pickFirstText(raw.traceId),
265
+ acquisitionId: pickFirstText(raw.acquisitionId),
266
+ version: pickFirstText(raw.version, raw.appVersion),
267
+ platform: pickFirstText(raw.platform),
268
+ nodeVersion: pickFirstText(raw.nodeVersion),
269
+ page: pickFirstText(raw.page, raw.landingPath, raw.path),
270
+ landingPath: pickFirstText(raw.landingPath, raw.page, raw.path),
271
+ pageType: pickFirstText(raw.pageType),
272
+ contentPillar: pickFirstText(raw.contentPillar, raw.pillar),
273
+ primaryQuery: pickFirstText(raw.primaryQuery, raw.query),
274
+ referrer,
275
+ referrerHost,
276
+ source,
277
+ utmSource,
278
+ utmMedium,
279
+ utmCampaign,
280
+ utmContent: pickFirstText(raw.utmContent),
281
+ utmTerm: pickFirstText(raw.utmTerm),
282
+ creator: pickFirstText(raw.creator, raw.creatorHandle, raw.creator_handle),
283
+ campaignVariant: pickFirstText(raw.campaignVariant, raw.variant),
284
+ offerCode: pickFirstText(raw.offerCode, raw.offer, raw.coupon),
285
+ community: pickFirstText(raw.community, raw.subreddit),
286
+ postId: pickFirstText(raw.postId, raw.post_id),
287
+ commentId: pickFirstText(raw.commentId, raw.comment_id),
288
+ ctaId: pickFirstText(raw.ctaId),
289
+ ctaPlacement: pickFirstText(raw.ctaPlacement),
290
+ planId: pickFirstText(raw.planId),
291
+ pipelineStatus: pickFirstText(raw.pipelineStatus, raw.workflowSprintStatus, raw.status),
292
+ reasonCode,
293
+ reasonDetail: pickFirstText(raw.reasonDetail, raw.reasonText, raw.otherReason, raw.notes),
294
+ pricingInterest: pickFirstText(raw.pricingInterest, raw.interestLevel),
295
+ seoQuery: pickFirstText(raw.seoQuery, raw.query),
296
+ seoSurface: pickFirstText(raw.seoSurface, raw.searchSurface, raw.surface),
297
+ trafficChannel: inferTrafficChannel(raw, referrerHost),
298
+ failureCode: pickFirstText(raw.failureCode),
299
+ httpStatus: normalizeInteger(raw.httpStatus),
300
+ userAgent: pickFirstText(raw.userAgent, headers['user-agent']),
301
+ attributionTagged: Boolean(
302
+ pickFirstText(raw.utmSource, raw.utmMedium, raw.utmCampaign, raw.utmContent, raw.utmTerm)
303
+ ),
304
+ };
305
+
306
+ return entry;
307
+ }
308
+
309
+ function appendTelemetryEvent(feedbackDir, payload = {}, headers = {}) {
310
+ const entry = sanitizeTelemetryPayload(payload, headers);
311
+ const telemetryPath = getTelemetryPath(feedbackDir);
312
+ fs.mkdirSync(path.dirname(telemetryPath), { recursive: true });
313
+ fs.appendFileSync(telemetryPath, `${JSON.stringify(entry)}\n`, 'utf-8');
314
+ return entry;
315
+ }
316
+
317
+ function loadTelemetryEventsFromPath(filePath) {
318
+ if (!fs.existsSync(filePath)) return [];
319
+ const raw = fs.readFileSync(filePath, 'utf-8').trim();
320
+ if (!raw) return [];
321
+ return raw
322
+ .split('\n')
323
+ .map((line) => {
324
+ try {
325
+ const parsed = JSON.parse(line);
326
+ const normalized = sanitizeTelemetryPayload(parsed);
327
+ return {
328
+ ...normalized,
329
+ receivedAt: pickFirstText(parsed.receivedAt, parsed.timestamp) || normalized.receivedAt,
330
+ };
331
+ } catch {
332
+ return null;
333
+ }
334
+ })
335
+ .filter(Boolean);
336
+ }
337
+
338
+ function loadTelemetryEvents(feedbackDir) {
339
+ const diagnostics = getTelemetrySourceDiagnostics(feedbackDir);
340
+ const merged = [];
341
+ const seen = new Set();
342
+
343
+ for (const filePath of diagnostics.activePaths) {
344
+ const rows = loadTelemetryEventsFromPath(filePath);
345
+ for (const row of rows) {
346
+ const key = JSON.stringify(row);
347
+ if (seen.has(key)) continue;
348
+ seen.add(key);
349
+ merged.push(row);
350
+ }
351
+ }
352
+
353
+ return merged;
354
+ }
355
+
356
+ function summarizeRecentEvents(events) {
357
+ return events
358
+ .slice(-5)
359
+ .reverse()
360
+ .map((entry) => ({
361
+ receivedAt: entry.receivedAt || null,
362
+ clientType: entry.clientType || null,
363
+ eventType: entry.eventType || null,
364
+ source: entry.source || null,
365
+ utmCampaign: entry.utmCampaign || null,
366
+ ctaId: entry.ctaId || null,
367
+ page: entry.page || null,
368
+ reasonCode: entry.reasonCode || null,
369
+ creator: entry.creator || null,
370
+ community: entry.community || null,
371
+ offerCode: entry.offerCode || null,
372
+ campaignVariant: entry.campaignVariant || null,
373
+ }));
374
+ }
375
+
376
+ function getTelemetrySummary(feedbackDir, options = {}) {
377
+ const analyticsWindow = resolveAnalyticsWindow(options);
378
+ const events = filterEntriesForWindow(
379
+ loadTelemetryEvents(feedbackDir),
380
+ analyticsWindow,
381
+ (entry) => entry && (entry.receivedAt || entry.timestamp)
382
+ );
383
+ const byClientType = {};
384
+ const byEventType = {};
385
+ const webVisitors = new Set();
386
+ const webSessions = new Set();
387
+ const webCheckoutStarters = new Set();
388
+ const cliInstalls = new Set();
389
+ const pageViewsBySource = {};
390
+ const pageViewsByCampaign = {};
391
+ const pageViewsByPath = {};
392
+ const pageViewsByTrafficChannel = {};
393
+ const pageViewsByCreator = {};
394
+ const pageViewsByCommunity = {};
395
+ const pageViewsByOfferCode = {};
396
+ const pageViewsByCampaignVariant = {};
397
+ const ctaClicksBySource = {};
398
+ const ctaClicksByCampaign = {};
399
+ const ctaClicksByTrafficChannel = {};
400
+ const ctaClicksByCreator = {};
401
+ const ctaClicksByCommunity = {};
402
+ const ctaClicksByOfferCode = {};
403
+ const ctaClicksByCampaignVariant = {};
404
+ const checkoutStartsBySource = {};
405
+ const checkoutStartsByCampaign = {};
406
+ const checkoutStartsByTrafficChannel = {};
407
+ const checkoutStartsByCreator = {};
408
+ const checkoutStartsByCommunity = {};
409
+ const checkoutStartsByOfferCode = {};
410
+ const checkoutStartsByCampaignVariant = {};
411
+ const byCtaId = {};
412
+ const byReferrerHost = {};
413
+ const checkoutFailuresByCode = {};
414
+ const checkoutFailuresByStatus = {};
415
+ const sessionLookupFailuresByCode = {};
416
+ const sessionLookupFailuresByStatus = {};
417
+ const cancellationsByReason = {};
418
+ const abandonmentsByReason = {};
419
+ const buyerLossReasons = {};
420
+ const pricingInterestByLevel = {};
421
+ const seoLandingViewsBySurface = {};
422
+ const seoLandingViewsByQuery = {};
423
+ const cliByPlatform = {};
424
+ const cliByVersion = {};
425
+ let pageViews = 0;
426
+ let ctaClicks = 0;
427
+ let checkoutStarts = 0;
428
+ let checkoutFailures = 0;
429
+ let checkoutCancelled = 0;
430
+ let checkoutAbandoned = 0;
431
+ let checkoutSuccessPageViews = 0;
432
+ let checkoutCancelPageViews = 0;
433
+ let checkoutPaidConfirmations = 0;
434
+ let checkoutPending = 0;
435
+ let checkoutLookupFailures = 0;
436
+ let buyerLossSignals = 0;
437
+ let pricingInterestEvents = 0;
438
+ let seoLandingViews = 0;
439
+ let webEvents = 0;
440
+ let webEventsWithVisitorId = 0;
441
+ let webEventsWithSessionId = 0;
442
+ let webEventsWithAcquisitionId = 0;
443
+ let attributedPageViews = 0;
444
+ let attributedCheckoutStarts = 0;
445
+ let latestSeenAt = null;
446
+
447
+ for (const entry of events) {
448
+ incrementCounter(byClientType, entry.clientType || entry.client || 'unknown');
449
+ incrementCounter(byEventType, entry.eventType || entry.event || 'unknown');
450
+ if (!latestSeenAt || String(entry.receivedAt || '') > latestSeenAt) {
451
+ latestSeenAt = entry.receivedAt || null;
452
+ }
453
+
454
+ if ((entry.clientType || entry.client) === 'web') {
455
+ webEvents += 1;
456
+ const visitorKey = pickFirstText(entry.visitorId, entry.installId, entry.sessionId);
457
+ if (visitorKey) webVisitors.add(visitorKey);
458
+ if (entry.sessionId) webSessions.add(entry.sessionId);
459
+ if (entry.visitorId) webEventsWithVisitorId += 1;
460
+ if (entry.sessionId) webEventsWithSessionId += 1;
461
+ if (entry.acquisitionId) webEventsWithAcquisitionId += 1;
462
+ if (entry.referrerHost) incrementCounter(byReferrerHost, entry.referrerHost);
463
+
464
+ if ((entry.eventType || entry.event) === 'landing_page_view') {
465
+ pageViews += 1;
466
+ incrementCounter(pageViewsBySource, entry.source);
467
+ incrementCounter(pageViewsByCampaign, entry.utmCampaign);
468
+ incrementCounter(pageViewsByPath, entry.page);
469
+ incrementCounter(pageViewsByTrafficChannel, entry.trafficChannel);
470
+ incrementCounter(pageViewsByCreator, entry.creator);
471
+ incrementCounter(pageViewsByCommunity, entry.community);
472
+ incrementCounter(pageViewsByOfferCode, entry.offerCode);
473
+ incrementCounter(pageViewsByCampaignVariant, entry.campaignVariant);
474
+ if (entry.attributionTagged) attributedPageViews += 1;
475
+ }
476
+
477
+ if ((entry.eventType || entry.event) === 'cta_click' || (entry.eventType || entry.event) === 'checkout_start' || (entry.eventType || entry.event) === 'checkout_bootstrap') {
478
+ ctaClicks += 1;
479
+ incrementCounter(ctaClicksBySource, entry.source);
480
+ incrementCounter(ctaClicksByCampaign, entry.utmCampaign);
481
+ incrementCounter(ctaClicksByTrafficChannel, entry.trafficChannel);
482
+ incrementCounter(ctaClicksByCreator, entry.creator);
483
+ incrementCounter(ctaClicksByCommunity, entry.community);
484
+ incrementCounter(ctaClicksByOfferCode, entry.offerCode);
485
+ incrementCounter(ctaClicksByCampaignVariant, entry.campaignVariant);
486
+ incrementCounter(byCtaId, entry.ctaId);
487
+ }
488
+
489
+ if ((entry.eventType || entry.event) === 'checkout_start' || (entry.eventType || entry.event) === 'checkout_bootstrap') {
490
+ checkoutStarts += 1;
491
+ incrementCounter(checkoutStartsBySource, entry.source);
492
+ incrementCounter(checkoutStartsByCampaign, entry.utmCampaign);
493
+ incrementCounter(checkoutStartsByTrafficChannel, entry.trafficChannel);
494
+ incrementCounter(checkoutStartsByCreator, entry.creator);
495
+ incrementCounter(checkoutStartsByCommunity, entry.community);
496
+ incrementCounter(checkoutStartsByOfferCode, entry.offerCode);
497
+ incrementCounter(checkoutStartsByCampaignVariant, entry.campaignVariant);
498
+ const starterKey = pickFirstText(
499
+ entry.acquisitionId,
500
+ entry.visitorId,
501
+ entry.sessionId,
502
+ entry.installId,
503
+ entry.traceId
504
+ );
505
+ if (starterKey) webCheckoutStarters.add(starterKey);
506
+ if (entry.attributionTagged) attributedCheckoutStarts += 1;
507
+ }
508
+
509
+ if ((entry.eventType || entry.event) === 'checkout_api_failed') {
510
+ checkoutFailures += 1;
511
+ incrementCounter(checkoutFailuresByCode, entry.failureCode);
512
+ incrementCounter(
513
+ checkoutFailuresByStatus,
514
+ entry.httpStatus === null ? null : String(entry.httpStatus)
515
+ );
516
+ }
517
+
518
+ if ((entry.eventType || entry.event) === 'checkout_success_page_view') {
519
+ checkoutSuccessPageViews += 1;
520
+ }
521
+
522
+ if ((entry.eventType || entry.event) === 'checkout_cancel_page_view') {
523
+ checkoutCancelPageViews += 1;
524
+ }
525
+
526
+ if ((entry.eventType || entry.event) === 'checkout_paid_confirmed') {
527
+ checkoutPaidConfirmations += 1;
528
+ }
529
+
530
+ if ((entry.eventType || entry.event) === 'checkout_session_pending') {
531
+ checkoutPending += 1;
532
+ }
533
+
534
+ if ((entry.eventType || entry.event) === 'checkout_session_lookup_failed') {
535
+ checkoutLookupFailures += 1;
536
+ incrementCounter(sessionLookupFailuresByCode, entry.failureCode);
537
+ incrementCounter(
538
+ sessionLookupFailuresByStatus,
539
+ entry.httpStatus === null ? null : String(entry.httpStatus)
540
+ );
541
+ }
542
+
543
+ if ((entry.eventType || entry.event) === 'checkout_cancelled') {
544
+ checkoutCancelled += 1;
545
+ incrementCounter(cancellationsByReason, entry.reasonCode);
546
+ incrementCounter(buyerLossReasons, entry.reasonCode);
547
+ buyerLossSignals += 1;
548
+ }
549
+
550
+ if ((entry.eventType || entry.event) === 'checkout_abandoned') {
551
+ checkoutAbandoned += 1;
552
+ incrementCounter(abandonmentsByReason, entry.reasonCode);
553
+ incrementCounter(buyerLossReasons, entry.reasonCode);
554
+ buyerLossSignals += 1;
555
+ }
556
+
557
+ if ((entry.eventType || entry.event) === 'reason_not_buying') {
558
+ incrementCounter(buyerLossReasons, entry.reasonCode);
559
+ buyerLossSignals += 1;
560
+ }
561
+
562
+ if ((entry.eventType || entry.event) === 'pricing_interest') {
563
+ pricingInterestEvents += 1;
564
+ incrementCounter(pricingInterestByLevel, entry.pricingInterest);
565
+ }
566
+
567
+ if ((entry.eventType || entry.event) === 'seo_landing_view') {
568
+ seoLandingViews += 1;
569
+ incrementCounter(seoLandingViewsBySurface, entry.seoSurface);
570
+ incrementCounter(seoLandingViewsByQuery, entry.seoQuery);
571
+ }
572
+ }
573
+
574
+ if ((entry.clientType || entry.client) === 'cli') {
575
+ if (entry.installId) cliInstalls.add(entry.installId);
576
+ incrementCounter(cliByPlatform, entry.platform);
577
+ incrementCounter(cliByVersion, entry.version);
578
+ }
579
+ }
580
+
581
+ const checkoutConversionBySource = {};
582
+ for (const sourceKey of new Set([...Object.keys(pageViewsBySource), ...Object.keys(checkoutStartsBySource)])) {
583
+ checkoutConversionBySource[sourceKey] = safeRate(
584
+ checkoutStartsBySource[sourceKey] || 0,
585
+ pageViewsBySource[sourceKey] || 0
586
+ );
587
+ }
588
+
589
+ const checkoutConversionByCampaign = {};
590
+ for (const campaignKey of new Set([...Object.keys(pageViewsByCampaign), ...Object.keys(checkoutStartsByCampaign)])) {
591
+ checkoutConversionByCampaign[campaignKey] = safeRate(
592
+ checkoutStartsByCampaign[campaignKey] || 0,
593
+ pageViewsByCampaign[campaignKey] || 0
594
+ );
595
+ }
596
+
597
+ const checkoutConversionByTrafficChannel = {};
598
+ for (const channelKey of new Set([...Object.keys(pageViewsByTrafficChannel), ...Object.keys(checkoutStartsByTrafficChannel)])) {
599
+ checkoutConversionByTrafficChannel[channelKey] = safeRate(
600
+ checkoutStartsByTrafficChannel[channelKey] || 0,
601
+ pageViewsByTrafficChannel[channelKey] || 0
602
+ );
603
+ }
604
+
605
+ return {
606
+ window: serializeAnalyticsWindow(analyticsWindow),
607
+ totalEvents: events.length,
608
+ latestSeenAt,
609
+ byClientType,
610
+ byEventType,
611
+ web: {
612
+ totalEvents: webEvents,
613
+ uniqueVisitors: webVisitors.size,
614
+ uniqueSessions: webSessions.size,
615
+ uniqueCheckoutStarters: webCheckoutStarters.size,
616
+ pageViews,
617
+ ctaClicks,
618
+ checkoutStarts,
619
+ checkoutFailures,
620
+ checkoutCancelled,
621
+ checkoutAbandoned,
622
+ checkoutSuccessPageViews,
623
+ checkoutCancelPageViews,
624
+ checkoutPaidConfirmations,
625
+ checkoutPending,
626
+ checkoutLookupFailures,
627
+ buyerLossSignals,
628
+ pricingInterestEvents,
629
+ seoLandingViews,
630
+ pageViewToCheckoutRate: safeRate(checkoutStarts, pageViews),
631
+ visitorToCheckoutRate: safeRate(checkoutStarts, webVisitors.size),
632
+ visitorIdCoverageRate: safeRate(webEventsWithVisitorId, webEvents),
633
+ sessionIdCoverageRate: safeRate(webEventsWithSessionId, webEvents),
634
+ acquisitionIdCoverageRate: safeRate(webEventsWithAcquisitionId, webEvents),
635
+ attributedPageViews,
636
+ attributedCheckoutStarts,
637
+ attributionCoverageRate: safeRate(attributedPageViews, pageViews),
638
+ },
639
+ cli: {
640
+ uniqueInstalls: cliInstalls.size,
641
+ initPings: byEventType.cli_init || 0,
642
+ byPlatform: cliByPlatform,
643
+ byVersion: cliByVersion,
644
+ },
645
+ marketing: {
646
+ pageViewsBySource,
647
+ pageViewsByCampaign,
648
+ pageViewsByPath,
649
+ pageViewsByTrafficChannel,
650
+ pageViewsByCreator,
651
+ pageViewsByCommunity,
652
+ pageViewsByOfferCode,
653
+ pageViewsByCampaignVariant,
654
+ ctaClicksBySource,
655
+ ctaClicksByCampaign,
656
+ ctaClicksByTrafficChannel,
657
+ ctaClicksByCreator,
658
+ ctaClicksByCommunity,
659
+ ctaClicksByOfferCode,
660
+ ctaClicksByCampaignVariant,
661
+ checkoutStartsBySource,
662
+ checkoutStartsByCampaign,
663
+ checkoutStartsByTrafficChannel,
664
+ checkoutStartsByCreator,
665
+ checkoutStartsByCommunity,
666
+ checkoutStartsByOfferCode,
667
+ checkoutStartsByCampaignVariant,
668
+ byCtaId,
669
+ byReferrerHost,
670
+ checkoutFailuresByCode,
671
+ checkoutFailuresByStatus,
672
+ sessionLookupFailuresByCode,
673
+ sessionLookupFailuresByStatus,
674
+ cancellationsByReason,
675
+ abandonmentsByReason,
676
+ buyerLossReasons,
677
+ pricingInterestByLevel,
678
+ seoLandingViewsBySurface,
679
+ seoLandingViewsByQuery,
680
+ checkoutConversionBySource,
681
+ checkoutConversionByCampaign,
682
+ checkoutConversionByTrafficChannel,
683
+ },
684
+ recent: summarizeRecentEvents(events),
685
+ };
686
+ }
687
+
688
+ function getTopCounterEntry(counter) {
689
+ return Object.entries(counter || {})
690
+ .sort((a, b) => b[1] - a[1])[0] || null;
691
+ }
692
+
693
+ function getTelemetryAnalytics(feedbackDir, options = {}) {
694
+ const summary = getTelemetrySummary(feedbackDir, options);
695
+ const topSource = getTopCounterEntry(summary.marketing.pageViewsBySource);
696
+ const topCampaign = getTopCounterEntry(summary.marketing.pageViewsByCampaign);
697
+ const topCta = getTopCounterEntry(summary.marketing.byCtaId);
698
+ const topReferrerHost = getTopCounterEntry(summary.marketing.byReferrerHost);
699
+ const topPath = getTopCounterEntry(summary.marketing.pageViewsByPath);
700
+ const topTrafficChannel = getTopCounterEntry(summary.marketing.pageViewsByTrafficChannel);
701
+ const topCreator = getTopCounterEntry(summary.marketing.pageViewsByCreator);
702
+ const topCommunity = getTopCounterEntry(summary.marketing.pageViewsByCommunity);
703
+ const topOfferCode = getTopCounterEntry(summary.marketing.pageViewsByOfferCode);
704
+ const topCampaignVariant = getTopCounterEntry(summary.marketing.pageViewsByCampaignVariant);
705
+ const topBuyerLossReason = getTopCounterEntry(summary.marketing.buyerLossReasons);
706
+ const topSeoSurface = getTopCounterEntry(summary.marketing.seoLandingViewsBySurface);
707
+ const topSeoQuery = getTopCounterEntry(summary.marketing.seoLandingViewsByQuery);
708
+
709
+ return {
710
+ window: summary.window,
711
+ totalEvents: summary.totalEvents,
712
+ latestSeenAt: summary.latestSeenAt,
713
+ byClientType: summary.byClientType,
714
+ byEventType: summary.byEventType,
715
+ visitors: {
716
+ totalEvents: summary.web.totalEvents,
717
+ uniqueVisitors: summary.web.uniqueVisitors,
718
+ uniqueSessions: summary.web.uniqueSessions,
719
+ pageViews: summary.web.pageViews,
720
+ attributedPageViews: summary.web.attributedPageViews,
721
+ attributionCoverageRate: summary.web.attributionCoverageRate,
722
+ visitorIdCoverageRate: summary.web.visitorIdCoverageRate,
723
+ sessionIdCoverageRate: summary.web.sessionIdCoverageRate,
724
+ acquisitionIdCoverageRate: summary.web.acquisitionIdCoverageRate,
725
+ bySource: summary.marketing.pageViewsBySource,
726
+ byCampaign: summary.marketing.pageViewsByCampaign,
727
+ byPath: summary.marketing.pageViewsByPath,
728
+ byTrafficChannel: summary.marketing.pageViewsByTrafficChannel,
729
+ byCreator: summary.marketing.pageViewsByCreator,
730
+ byCommunity: summary.marketing.pageViewsByCommunity,
731
+ byOfferCode: summary.marketing.pageViewsByOfferCode,
732
+ byCampaignVariant: summary.marketing.pageViewsByCampaignVariant,
733
+ byReferrerHost: summary.marketing.byReferrerHost,
734
+ topSource: topSource ? { key: topSource[0], count: topSource[1] } : null,
735
+ topCampaign: topCampaign ? { key: topCampaign[0], count: topCampaign[1] } : null,
736
+ topPath: topPath ? { key: topPath[0], count: topPath[1] } : null,
737
+ topTrafficChannel: topTrafficChannel ? { key: topTrafficChannel[0], count: topTrafficChannel[1] } : null,
738
+ topCreator: topCreator ? { key: topCreator[0], count: topCreator[1] } : null,
739
+ topCommunity: topCommunity ? { key: topCommunity[0], count: topCommunity[1] } : null,
740
+ topOfferCode: topOfferCode ? { key: topOfferCode[0], count: topOfferCode[1] } : null,
741
+ topCampaignVariant: topCampaignVariant ? { key: topCampaignVariant[0], count: topCampaignVariant[1] } : null,
742
+ topReferrerHost: topReferrerHost ? { key: topReferrerHost[0], count: topReferrerHost[1] } : null,
743
+ },
744
+ ctas: {
745
+ totalClicks: summary.web.ctaClicks,
746
+ checkoutStarts: summary.web.checkoutStarts,
747
+ uniqueCheckoutStarters: summary.web.uniqueCheckoutStarters,
748
+ checkoutFailures: summary.web.checkoutFailures,
749
+ checkoutCancelled: summary.web.checkoutCancelled,
750
+ checkoutAbandoned: summary.web.checkoutAbandoned,
751
+ successPageViews: summary.web.checkoutSuccessPageViews,
752
+ cancelPageViews: summary.web.checkoutCancelPageViews,
753
+ paidConfirmations: summary.web.checkoutPaidConfirmations,
754
+ sessionPending: summary.web.checkoutPending,
755
+ lookupFailures: summary.web.checkoutLookupFailures,
756
+ failuresByCode: summary.marketing.checkoutFailuresByCode,
757
+ failuresByStatus: summary.marketing.checkoutFailuresByStatus,
758
+ lookupFailuresByCode: summary.marketing.sessionLookupFailuresByCode,
759
+ lookupFailuresByStatus: summary.marketing.sessionLookupFailuresByStatus,
760
+ cancellationReasons: summary.marketing.cancellationsByReason,
761
+ abandonmentReasons: summary.marketing.abandonmentsByReason,
762
+ bySource: summary.marketing.ctaClicksBySource,
763
+ byCampaign: summary.marketing.ctaClicksByCampaign,
764
+ byTrafficChannel: summary.marketing.ctaClicksByTrafficChannel,
765
+ byCreator: summary.marketing.ctaClicksByCreator,
766
+ byCommunity: summary.marketing.ctaClicksByCommunity,
767
+ byOfferCode: summary.marketing.ctaClicksByOfferCode,
768
+ byCampaignVariant: summary.marketing.ctaClicksByCampaignVariant,
769
+ checkoutStartsBySource: summary.marketing.checkoutStartsBySource,
770
+ checkoutStartsByCampaign: summary.marketing.checkoutStartsByCampaign,
771
+ checkoutStartsByTrafficChannel: summary.marketing.checkoutStartsByTrafficChannel,
772
+ checkoutStartsByCreator: summary.marketing.checkoutStartsByCreator,
773
+ checkoutStartsByCommunity: summary.marketing.checkoutStartsByCommunity,
774
+ checkoutStartsByOfferCode: summary.marketing.checkoutStartsByOfferCode,
775
+ checkoutStartsByCampaignVariant: summary.marketing.checkoutStartsByCampaignVariant,
776
+ byId: summary.marketing.byCtaId,
777
+ topCta: topCta ? { key: topCta[0], count: topCta[1] } : null,
778
+ pageViewToCheckoutRate: summary.web.pageViewToCheckoutRate,
779
+ visitorToCheckoutRate: summary.web.visitorToCheckoutRate,
780
+ clickToCheckoutRate: safeRate(summary.web.checkoutStarts, summary.web.ctaClicks),
781
+ cancellationRate: safeRate(summary.web.checkoutCancelled, summary.web.checkoutStarts),
782
+ abandonmentRate: safeRate(summary.web.checkoutAbandoned, summary.web.checkoutStarts),
783
+ paidConfirmationRate: safeRate(summary.web.checkoutPaidConfirmations, summary.web.checkoutStarts),
784
+ successPageViewRate: safeRate(summary.web.checkoutSuccessPageViews, summary.web.checkoutStarts),
785
+ conversionByTrafficChannel: summary.marketing.checkoutConversionByTrafficChannel,
786
+ },
787
+ buyerLoss: {
788
+ totalSignals: summary.web.buyerLossSignals,
789
+ reasonsByCode: summary.marketing.buyerLossReasons,
790
+ cancellationReasons: summary.marketing.cancellationsByReason,
791
+ abandonmentReasons: summary.marketing.abandonmentsByReason,
792
+ topReason: topBuyerLossReason ? { key: topBuyerLossReason[0], count: topBuyerLossReason[1] } : null,
793
+ },
794
+ pricing: {
795
+ pricingInterestEvents: summary.web.pricingInterestEvents,
796
+ interestByLevel: summary.marketing.pricingInterestByLevel,
797
+ },
798
+ seo: {
799
+ landingViews: summary.web.seoLandingViews,
800
+ bySurface: summary.marketing.seoLandingViewsBySurface,
801
+ byQuery: summary.marketing.seoLandingViewsByQuery,
802
+ topSurface: topSeoSurface ? { key: topSeoSurface[0], count: topSeoSurface[1] } : null,
803
+ topQuery: topSeoQuery ? { key: topSeoQuery[0], count: topSeoQuery[1] } : null,
804
+ },
805
+ cli: summary.cli,
806
+ recent: summary.recent,
807
+ };
808
+ }
809
+
810
+ const appendTelemetryPing = appendTelemetryEvent;
811
+
812
+ module.exports = {
813
+ TELEMETRY_FILE_NAME,
814
+ sanitizeTelemetryPayload,
815
+ appendTelemetryPing,
816
+ appendTelemetryEvent,
817
+ getTelemetrySourceDiagnostics,
818
+ loadTelemetryEvents,
819
+ getTelemetryAnalytics,
820
+ inferTrafficChannel,
821
+ };