thumbgate 1.40.3 → 1.40.6

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 (54) hide show
  1. package/.agents/skills/comet-session-logger/SKILL.md +8 -5
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +7 -2
  5. package/adapters/claude/.mcp.json +3 -3
  6. package/adapters/forge/forge.yaml +3 -3
  7. package/adapters/future-agi/.mcp.json +1 -1
  8. package/adapters/future-agi/config.toml +1 -1
  9. package/adapters/future-agi/opencode.json +1 -1
  10. package/adapters/herdr/herdr-plugin.toml +2 -2
  11. package/adapters/mcp/server-stdio.js +1 -1
  12. package/adapters/opencode/opencode.json +1 -1
  13. package/config/github-about.json +1 -1
  14. package/config/post-deploy-marketing-pages.json +1 -1
  15. package/package.json +35 -7
  16. package/public/about.html +2 -2
  17. package/public/admin.html +546 -50
  18. package/public/case-studies.html +1 -0
  19. package/public/dashboard.html +7 -6
  20. package/public/diagnostic.html +15 -12
  21. package/public/index.html +210 -88
  22. package/public/install.html +9 -8
  23. package/public/js/connect-panel.js +437 -0
  24. package/public/learn.html +8 -0
  25. package/public/numbers.html +2 -2
  26. package/public/preview.html +42 -0
  27. package/public/pricing.html +55 -10
  28. package/public/support.html +1 -1
  29. package/public/terms.html +1 -1
  30. package/scripts/auto-promote-gates.js +29 -4
  31. package/scripts/billing.js +189 -4
  32. package/scripts/cap-hit-counter.js +47 -0
  33. package/scripts/checkout-human-gate.js +248 -0
  34. package/scripts/checkout-session-count.js +119 -0
  35. package/scripts/claude-feedback-sync.js +4 -2
  36. package/scripts/feedback-loop.js +41 -5
  37. package/scripts/first-block-upsell.js +187 -0
  38. package/scripts/gates-engine.js +37 -108
  39. package/scripts/human-feedback.js +20 -1
  40. package/scripts/ops-log.js +91 -0
  41. package/scripts/ops-report.js +174 -0
  42. package/scripts/owner-admin.js +508 -27
  43. package/scripts/owner-telemetry.js +151 -0
  44. package/scripts/rate-limiter.js +8 -2
  45. package/scripts/statusline-human-counts.js +71 -8
  46. package/scripts/statusline.sh +15 -2
  47. package/scripts/telemetry-analytics.js +4 -0
  48. package/scripts/tool-contract-validator.js +13 -3
  49. package/scripts/tool-registry.js +1 -1
  50. package/scripts/utm-source-summary.js +88 -0
  51. package/server.json +2 -2
  52. package/skills/comet-session-logger/SKILL.md +8 -5
  53. package/src/api/server.js +649 -107
  54. package/src/mcp/email-triage-server/index.js +92 -14
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Owner-only telemetry reader. Streams the telemetry log newest-first and stops at the window edge
5
+ * or a byte cap, so a log of any size answers in bounded time and memory. Never refuses a large file:
6
+ * when the cap is hit before the window edge, the result says `partial`.
7
+ *
8
+ * Stored telemetry lines are already normalised by appendTelemetryEvent (event type, visitor, source,
9
+ * audience flags), so they are read as stored instead of being re-sanitised line by line.
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ const telemetry = require('./telemetry-analytics');
15
+
16
+ const DAY_MS = 86400000;
17
+ const CHUNK_BYTES = 1024 * 1024;
18
+ const DEFAULT_MAX_BYTES = 96 * 1024 * 1024;
19
+ const OLD_RUN_TO_STOP = 200;
20
+
21
+ function stopped(signal) {
22
+ if (signal && signal.aborted) throw Object.assign(new Error('Collection stopped'), { code: 'collection_timeout' });
23
+ }
24
+
25
+ function entryTime(entry) {
26
+ const stamp = Date.parse(entry.receivedAt || entry.timestamp || '');
27
+ return Number.isFinite(stamp) ? stamp : null;
28
+ }
29
+
30
+ // Streams one file newest-first. `onEntry(entry, time)` is called for every in-window line.
31
+ async function scanFile(filePath, { edgeMs, maxBytes, signal, onEntry }) {
32
+ const meta = { bytesRead: 0, size: 0, reachedWindowEdge: false, capped: false, lines: 0 };
33
+ let handle;
34
+ try { handle = await fs.promises.open(filePath, 'r'); } catch (error) {
35
+ if (error.code === 'ENOENT') return meta;
36
+ throw error;
37
+ }
38
+ try {
39
+ const { size } = await handle.stat();
40
+ meta.size = size;
41
+ let position = size;
42
+ let carry = Buffer.alloc(0);
43
+ let oldRun = 0;
44
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
45
+ const handleLine = (bytes) => {
46
+ if (!bytes.length) return true;
47
+ let entry;
48
+ try { entry = JSON.parse(bytes.toString('utf8')); } catch { return true; }
49
+ if (!entry || typeof entry !== 'object') return true;
50
+ meta.lines += 1;
51
+ const time = entryTime(entry);
52
+ if (time === null) return true;
53
+ if (time < edgeMs) { oldRun += 1; return oldRun < OLD_RUN_TO_STOP; }
54
+ oldRun = 0;
55
+ onEntry(entry, time);
56
+ return true;
57
+ };
58
+ while (position > 0) {
59
+ stopped(signal);
60
+ if (meta.bytesRead >= maxBytes) { meta.capped = true; return meta; }
61
+ const length = Math.min(CHUNK_BYTES, position);
62
+ position -= length;
63
+ await handle.read(buffer, 0, length, position);
64
+ meta.bytesRead += length;
65
+ const joined = carry.length ? Buffer.concat([buffer.subarray(0, length), carry]) : Buffer.from(buffer.subarray(0, length));
66
+ let end = joined.length;
67
+ let newline = joined.lastIndexOf(10, end - 1);
68
+ while (newline >= 0) {
69
+ if (!handleLine(joined.subarray(newline + 1, end))) { meta.reachedWindowEdge = true; return meta; }
70
+ end = newline;
71
+ newline = end > 0 ? joined.lastIndexOf(10, end - 1) : -1;
72
+ }
73
+ carry = Buffer.from(joined.subarray(0, end));
74
+ }
75
+ if (carry.length && !handleLine(carry)) meta.reachedWindowEdge = true;
76
+ else if (position <= 0) meta.reachedWindowEdge = true;
77
+ return meta;
78
+ } finally {
79
+ await handle.close();
80
+ }
81
+ }
82
+
83
+ function telemetryPaths(feedbackDir) {
84
+ try {
85
+ const found = telemetry.getTelemetrySourceDiagnostics(feedbackDir).activePaths;
86
+ if (found.length) return found;
87
+ } catch { /* fall through to the default location */ }
88
+ return [path.join(feedbackDir, telemetry.TELEMETRY_FILE_NAME)];
89
+ }
90
+
91
+ async function scanTelemetry({ feedbackDir, days = 30, now = Date.now(), maxBytes = DEFAULT_MAX_BYTES, signal, onEntry }) {
92
+ const edgeMs = now - days * DAY_MS;
93
+ const files = [];
94
+ for (const filePath of telemetryPaths(feedbackDir)) files.push({ file: path.basename(filePath), ...(await scanFile(filePath, { edgeMs, maxBytes, signal, onEntry })) });
95
+ const bytesRead = files.reduce((sum, file) => sum + file.bytesRead, 0);
96
+ const size = files.reduce((sum, file) => sum + file.size, 0);
97
+ const partial = files.some((file) => file.capped);
98
+ return { windowDays: days, edge: new Date(edgeMs).toISOString(), bytesRead, size, partial, empty: size === 0, files: files.map(({ file, size: fileSize, bytesRead: read, capped }) => ({ file, size: fileSize, bytesRead: read, capped })) };
99
+ }
100
+
101
+ const kind = (entry) => String(entry.eventType || entry.event || '').toLowerCase();
102
+ const isWeb = (entry) => (entry.clientType || entry.client) === 'web';
103
+ const isFlagged = (entry) => entry.isBotTraffic === true || entry.isInternal === true || entry.isTest === true;
104
+
105
+ // Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
106
+ //
107
+ // `visitors` is the number of distinct visitor identifiers seen on ANY web event (a click, a checkout step, a page view),
108
+ // so it can exceed `pageViews`, which counts landing_page_view events only. `realVisitors` leaves out identifiers that
109
+ // carried a bot, internal or test flag on any event. `pageViewers` is the identifiers with at least one landing page view.
110
+ async function readTrafficWindow(options) {
111
+ const days = new Map();
112
+ const visitors = new Set();
113
+ const flagged = new Set();
114
+ const pageViewers = new Set();
115
+ const sessions = new Set();
116
+ const startsByType = {};
117
+ const totals = { pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0, webEvents: 0 };
118
+ const dayOf = (time) => {
119
+ const key = new Date(time).toISOString().slice(0, 10);
120
+ let day = days.get(key);
121
+ if (!day) { day = { date: key, visitors: new Set(), pageViewers: new Set(), sessions: new Set(), pageViews: 0, ctaClicks: 0, checkoutStarts: 0, checkoutPaidConfirmations: 0 }; days.set(key, day); }
122
+ return day;
123
+ };
124
+ const meta = await scanTelemetry({
125
+ ...options,
126
+ onEntry(entry, time) {
127
+ if (!isWeb(entry)) return;
128
+ totals.webEvents += 1;
129
+ const day = dayOf(time);
130
+ const who = entry.visitorId || entry.installId || entry.sessionId || null;
131
+ if (who) { visitors.add(who); day.visitors.add(who); if (isFlagged(entry)) flagged.add(who); }
132
+ if (entry.sessionId) { sessions.add(entry.sessionId); day.sessions.add(entry.sessionId); }
133
+ const type = kind(entry);
134
+ if (type === 'landing_page_view') {
135
+ totals.pageViews += 1; day.pageViews += 1;
136
+ if (who) { pageViewers.add(who); day.pageViewers.add(who); }
137
+ }
138
+ if (telemetry.isMarketingClickEvent(type) && !telemetry.isDirectStripeBeacon(entry)) { totals.ctaClicks += 1; day.ctaClicks += 1; }
139
+ if (telemetry.isCheckoutStartEvent(type)) { totals.checkoutStarts += 1; day.checkoutStarts += 1; startsByType[type] = (startsByType[type] || 0) + 1; }
140
+ if (type === 'checkout_paid_confirmed') { totals.checkoutPaidConfirmations += 1; day.checkoutPaidConfirmations += 1; }
141
+ },
142
+ });
143
+ const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
144
+ return {
145
+ ...meta,
146
+ traffic: { visitors: visitors.size, realVisitors: visitors.size - flagged.size, botOrInternalVisitors: flagged.size, pageViewers: pageViewers.size, checkoutStartsByType: startsByType, sessions: sessions.size, pageViews: totals.pageViews, ctaClicks: totals.ctaClicks, checkoutStarts: totals.checkoutStarts, checkoutPaidConfirmations: totals.checkoutPaidConfirmations },
147
+ daily,
148
+ };
149
+ }
150
+
151
+ module.exports = { scanFile, scanTelemetry, readTrafficWindow, DEFAULT_MAX_BYTES };
@@ -29,7 +29,6 @@ const FREE_TIER_LIMITS = {
29
29
  };
30
30
 
31
31
  const FREE_TIER_MAX_GATES = 3; // 3 active prevention rules on free; Pro is unlimited
32
- const FREE_TIER_DAILY_BLOCKS = 2; // 3 gate blocks/day on free; after limit, deny → warn + upgrade CTA
33
32
 
34
33
  const UPGRADE_MESSAGE = `Pro: ${PRO_PRICE_LABEL} — unlimited rules, recall, lesson search, dashboard, and exports: ${PRO_MONTHLY_PAYMENT_LINK}\n Enterprise: ${ENTERPRISE_PRICE_LABEL} after workflow qualification.`;
35
34
 
@@ -242,6 +241,13 @@ function proWouldHaveBlockedSentence(mistake) {
242
241
  return `Pro would have blocked this repeat: ${clean}. ${PRO_REPEAT_URL}`;
243
242
  }
244
243
 
244
+ // One plain line shown the moment a free install learns a rule it cannot enforce (rule 4 and up).
245
+ function capUpgradeLine(rule, maxActive = FREE_TIER_MAX_GATES) {
246
+ const clean = scrubRepeatText(rule);
247
+ if (!clean) return null;
248
+ return `ThumbGate learned a ${maxActive + 1}th rule (${clean}), but Free enforces ${maxActive}. Pro enforces all of them: ${PRO_REPEAT_URL}`;
249
+ }
250
+
245
251
  function droppedRepeatFromRulesMarkdown(markdown, maxActive = FREE_TIER_MAX_GATES) {
246
252
  const mistakes = [];
247
253
  for (const section of String(markdown || '').split(/\n## /)) {
@@ -268,12 +274,12 @@ module.exports = {
268
274
  todayKey,
269
275
  FREE_TIER_LIMITS,
270
276
  FREE_TIER_MAX_GATES,
271
- FREE_TIER_DAILY_BLOCKS,
272
277
  TRIAL_DAYS,
273
278
  UPGRADE_MESSAGE,
274
279
  PAYWALL_MESSAGES,
275
280
  USAGE_FILE,
276
281
  proWouldHaveBlockedSentence,
282
+ capUpgradeLine,
277
283
  droppedRepeatFromRulesMarkdown,
278
284
  scrubRepeatText,
279
285
  };
@@ -13,7 +13,7 @@ const path = require('node:path');
13
13
  const { readProjectRows } = require('./project-catalog');
14
14
  const { resolveLocalProject, hash } = require('./project-identity');
15
15
  const { resolveProjectDir, resolveFeedbackDir, getHomeDir } = require('./feedback-paths');
16
- const { isCountedHumanFeedback } = require('./human-feedback');
16
+ const { isCountedHumanFeedback, isLegacyMcpCapture } = require('./human-feedback');
17
17
 
18
18
  function normalizeSignal(entry) {
19
19
  const raw = String(entry.signal || entry.feedback || '').toLowerCase();
@@ -22,6 +22,20 @@ function normalizeSignal(entry) {
22
22
  return null;
23
23
  }
24
24
 
25
+ // The agent records a thumb within seconds of the message that carried it.
26
+ const CORROBORATION_MS = 90 * 1000;
27
+
28
+ function rowTime(row) {
29
+ const at = Date.parse(row.timestamp || row.createdAt || '');
30
+ return Number.isFinite(at) ? at : null;
31
+ }
32
+
33
+ function isScrapedHumanThumb(row) {
34
+ if (String(row.reviewOrigin || '').toLowerCase() !== 'human') return false;
35
+ const tags = Array.isArray(row.tags) ? row.tags : [];
36
+ return tags.includes('claude-history-sync');
37
+ }
38
+
25
39
  function computeHumanCounts(options = {}) {
26
40
  const env = options.env || process.env;
27
41
  const cwd = options.cwd || process.cwd();
@@ -34,8 +48,7 @@ function computeHumanCounts(options = {}) {
34
48
  const globalDir = path.join(getHomeDir({ env }), '.thumbgate');
35
49
 
36
50
  const seen = new Set();
37
- let up = 0;
38
- let down = 0;
51
+ const mineRows = [];
39
52
  const ownDir = path.resolve(feedbackDir);
40
53
  for (const dir of new Set([ownDir, path.resolve(globalDir)])) {
41
54
  // Rows written before project tracking carry no key. In the project's own
@@ -45,17 +58,67 @@ function computeHumanCounts(options = {}) {
45
58
  const mine = row.projectKey === projectKey || row.projectKey === aliasKey
46
59
  || (ownsUnassigned && row.projectKey === 'unassigned');
47
60
  if (!mine) continue;
48
- if (!isCountedHumanFeedback(row)) continue;
49
61
  if (row.id) {
50
62
  if (seen.has(row.id)) continue;
51
63
  seen.add(row.id);
52
64
  }
53
- const signal = normalizeSignal(row);
54
- if (signal === 'up') up += 1;
55
- if (signal === 'down') down += 1;
65
+ mineRows.push(row);
56
66
  }
57
67
  }
58
- return { up, down, label: 'this project', project: projectName };
68
+
69
+ // A thumb the history sync scraped from the person's own message is evidence
70
+ // that the person gave one at that moment. An MCP capture that an older server
71
+ // labelled automated counts when such evidence sits next to it; without it the
72
+ // row is a lesson the agent logged on its own judgment.
73
+ const scraped = { up: [], down: [] };
74
+ for (const row of mineRows) {
75
+ const signal = normalizeSignal(row);
76
+ const at = rowTime(row);
77
+ if (signal && at !== null && isScrapedHumanThumb(row)) scraped[signal].push(at);
78
+ }
79
+ const corroborated = (row) => {
80
+ const signal = normalizeSignal(row);
81
+ const at = rowTime(row);
82
+ return Boolean(signal) && at !== null && scraped[signal].some((t) => Math.abs(t - at) <= CORROBORATION_MS);
83
+ };
84
+
85
+ let up = 0;
86
+ let down = 0;
87
+ let latestDown = null;
88
+ for (const row of mineRows) {
89
+ if (!(isCountedHumanFeedback(row) || (isLegacyMcpCapture(row) && corroborated(row)))) continue;
90
+ const signal = normalizeSignal(row);
91
+ if (signal === 'up') up += 1;
92
+ if (signal === 'down') {
93
+ down += 1;
94
+ const at = rowTime(row);
95
+ if (at !== null && (!latestDown || at > latestDown.at)) latestDown = { at, row };
96
+ }
97
+ }
98
+ return { up, down, label: 'this project', project: projectName, latestDown: describeLatestDown(latestDown) };
99
+ }
100
+
101
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
102
+
103
+ // The reader's own clock, 12-hour: "Nov 19, 3:37 PM". Built by hand because
104
+ // toLocaleString puts a narrow no-break space before AM/PM on newer ICU builds.
105
+ function formatStamp(ms) {
106
+ const d = new Date(ms);
107
+ const hour = d.getHours() % 12 || 12;
108
+ const minute = String(d.getMinutes()).padStart(2, '0');
109
+ return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${hour}:${minute} ${d.getHours() < 12 ? 'AM' : 'PM'}`;
110
+ }
111
+
112
+ function describeLatestDown(found) {
113
+ if (!found) return null;
114
+ const { at, row } = found;
115
+ const raw = String(row.whatWentWrong || row.whatToChange || row.context || '').replace(/\s+/g, ' ').trim();
116
+ return {
117
+ id: row.id || null,
118
+ timestamp: new Date(at).toISOString(),
119
+ label: `Latest mistake ${formatStamp(at)}`,
120
+ text: raw.length > 60 ? `${raw.slice(0, 57)}...` : raw,
121
+ };
59
122
  }
60
123
 
61
124
  if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
@@ -94,12 +94,16 @@ fi
94
94
  # caches above are global sums that include automated entries, so they feed
95
95
  # lessons and trend, never the thumbs.
96
96
  SCOPE_LABEL="this project"
97
+ LD_TS=""; LD_LABEL=""; LD_TEXT=""
97
98
  _HUMAN_JSON="${_TEST_THUMBGATE_STATUSLINE_HUMAN_JSON:-$(node "${SCRIPT_DIR}/statusline-human-counts.js" 2>/dev/null)}"
98
99
  if [ -n "$_HUMAN_JSON" ]; then
99
100
  eval "$(echo "$_HUMAN_JSON" | jq -r '
100
101
  @sh "UP=\(.up // 0)",
101
102
  @sh "DOWN=\(.down // 0)",
102
- @sh "SCOPE_LABEL=\(.label // "this project")"
103
+ @sh "SCOPE_LABEL=\(.label // "this project")",
104
+ @sh "LD_TS=\(.latestDown.timestamp // "")",
105
+ @sh "LD_LABEL=\(.latestDown.label // "")",
106
+ @sh "LD_TEXT=\(.latestDown.text // "")"
103
107
  ' 2>/dev/null)"
104
108
  else
105
109
  UP="0"; DOWN="0"
@@ -180,9 +184,18 @@ if [[ -n "$_LESSON_JSON" ]]; then
180
184
  @sh "LESSON_TEXT=\(.text // "")",
181
185
  @sh "LESSON_ID=\(.lessonId // "")",
182
186
  @sh "LESSON_LABEL=\(.label // "")",
183
- @sh "LESSON_LINK=\(.link // "")"
187
+ @sh "LESSON_LINK=\(.link // "")",
188
+ @sh "LESSON_CREATED=\(.createdAt // "")"
184
189
  ' 2>/dev/null)"
185
190
  fi
191
+ # "Latest mistake" is the newest thumbs-down a person gave this project. The
192
+ # lesson store only fills when a lesson is inferred, so it can lag far behind;
193
+ # the thumb log is the fresher record. Both are ISO UTC, so a string compare orders them.
194
+ LESSON_CREATED="${LESSON_CREATED:-}"
195
+ if [[ -n "$LD_TS" ]] && [[ -z "$LESSON_CREATED" || ! "$LD_TS" < "$LESSON_CREATED" ]]; then
196
+ LESSON_LABEL="$LD_LABEL"; LESSON_TEXT="$LD_TEXT"
197
+ if [[ "$LD_TS" != "$LESSON_CREATED" ]]; then LESSON_ID=""; LESSON_LINK=""; fi
198
+ fi
186
199
 
187
200
  # ── Colors ────────────────────────────────────────────────────────
188
201
  G='\033[32m'; R='\033[31m'; M='\033[35m'; C='\033[36m'; D='\033[90m'; BD='\033[1m'; RST='\033[0m'
@@ -1789,6 +1789,7 @@ const appendTelemetryPing = appendTelemetryEvent;
1789
1789
 
1790
1790
  module.exports = {
1791
1791
  TELEMETRY_FILE_NAME,
1792
+ CHECKOUT_START_EVENT_TYPES,
1792
1793
  sanitizeTelemetryPayload,
1793
1794
  classifyTelemetryAudience,
1794
1795
  headerHasPrivacyOptOut,
@@ -1800,4 +1801,7 @@ module.exports = {
1800
1801
  getTelemetryAnalytics,
1801
1802
  getTelemetrySummary,
1802
1803
  inferTrafficChannel,
1804
+ isMarketingClickEvent,
1805
+ isCheckoutStartEvent,
1806
+ isDirectStripeBeacon,
1803
1807
  };
@@ -119,13 +119,23 @@ function validatePropertyCount(schema, keys, path, errors) {
119
119
  }
120
120
  }
121
121
 
122
+ // Name the allowed values and any keys the caller sent that the schema does not define, so the
123
+ // caller can fix the next attempt from the error text alone (e.g. `feedback` sent for `signal`).
124
+ function missingParameterHint(schema, value, required) {
125
+ const properties = schema.properties || {};
126
+ const allowed = properties[required] && Array.isArray(properties[required].enum) ? properties[required].enum : null;
127
+ const unrecognized = Object.keys(value).filter((key) => !Object.hasOwn(properties, key));
128
+ let hint = allowed && allowed.length ? ` (allowed values: ${allowed.join(', ')})` : '';
129
+ if (unrecognized.length) hint += `. Received unrecognized: ${unrecognized.map((key) => `'${key}'`).join(', ')}.`;
130
+ return hint;
131
+ }
132
+
122
133
  function validateRequiredProperties(schema, value, path, errors) {
123
134
  for (const required of schema.required || []) {
124
135
  if (value[required] === undefined || value[required] === null || value[required] === '') {
125
136
  const requiredPath = joinPath(path, required);
126
- errors.push(path
127
- ? `Parameter '${path}': Missing required parameter: '${required}'`
128
- : `Missing required parameter: '${required}'`);
137
+ const message = `Missing required parameter: '${required}'${missingParameterHint(schema, value, required)}`;
138
+ errors.push(path ? `Parameter '${path}': ${message}` : message);
129
139
  if (path && requiredPath === path) break;
130
140
  }
131
141
  }
@@ -206,7 +206,7 @@ const MEMORY_SCOPE_SCHEMA = {
206
206
  const TOOLS = [
207
207
  destructiveTool({
208
208
  name: 'capture_feedback',
209
- description: 'Capture an up/down signal plus one line of why. Vague feedback is logged, then returned with a clarification prompt instead of memory promotion.',
209
+ description: 'Capture an up/down signal plus one line of why. Required: signal ("up" or "down"; not "feedback" or "rating"). Add context (one sentence) and, for "down", whatWentWrong and whatToChange. Example: {"signal":"down","context":"claimed deployed without a health check","whatToChange":"run curl on /health first"}. Vague feedback is logged, then returned with a clarification prompt instead of memory promotion.',
210
210
  inputSchema: {
211
211
  type: 'object',
212
212
  required: ['signal'],
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ // Visits, installs and checkout starts grouped by utm_source, for the last 7 and
4
+ // 30 days. Read-only over the telemetry ledger; counts external traffic only.
5
+
6
+ const { loadTelemetryEvents, CHECKOUT_START_EVENT_TYPES } = require('./telemetry-analytics');
7
+
8
+ const WINDOW_DAYS = [7, 30];
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+
11
+ function sourceKey(entry) {
12
+ const raw = entry.utmSource || entry.source;
13
+ const text = String(raw || '').trim().toLowerCase();
14
+ return text || 'unknown';
15
+ }
16
+
17
+ function emptyRow(source) {
18
+ return {
19
+ source,
20
+ visits: 0,
21
+ visitors: new Set(),
22
+ installIds: new Set(),
23
+ checkoutStarts: 0,
24
+ };
25
+ }
26
+
27
+ function summarizeWindow(events, days, nowMs) {
28
+ const sinceMs = nowMs - days * DAY_MS;
29
+ const rows = new Map();
30
+ const row = (source) => {
31
+ if (!rows.has(source)) rows.set(source, emptyRow(source));
32
+ return rows.get(source);
33
+ };
34
+
35
+ for (const entry of events) {
36
+ if ((entry.audience || 'external') !== 'external') continue;
37
+ const at = Date.parse(entry.receivedAt || '');
38
+ if (!Number.isFinite(at) || at < sinceMs || at > nowMs) continue;
39
+ const client = entry.clientType || entry.client;
40
+ const type = entry.eventType || entry.event;
41
+ if (client === 'web' && type === 'landing_page_view') {
42
+ const r = row(sourceKey(entry));
43
+ r.visits += 1;
44
+ const visitor = entry.visitorId || entry.sessionId;
45
+ if (visitor) r.visitors.add(visitor);
46
+ } else if (client === 'web' && CHECKOUT_START_EVENT_TYPES.has(type)) {
47
+ row(sourceKey(entry)).checkoutStarts += 1;
48
+ } else if (client === 'cli' && entry.installId && entry.installId !== 'unknown') {
49
+ row(sourceKey(entry)).installIds.add(entry.installId);
50
+ }
51
+ }
52
+
53
+ const sources = [...rows.values()]
54
+ .map((r) => ({
55
+ source: r.source,
56
+ visits: r.visits,
57
+ visitors: r.visitors.size,
58
+ installs: r.installIds.size,
59
+ checkoutStarts: r.checkoutStarts,
60
+ }))
61
+ .sort((a, b) => b.visits - a.visits || a.source.localeCompare(b.source));
62
+
63
+ const allVisitors = new Set();
64
+ const allInstalls = new Set();
65
+ for (const r of rows.values()) {
66
+ for (const v of r.visitors) allVisitors.add(v);
67
+ for (const i of r.installIds) allInstalls.add(i);
68
+ }
69
+ const totals = {
70
+ visits: sources.reduce((n, s) => n + s.visits, 0),
71
+ visitors: allVisitors.size,
72
+ installs: allInstalls.size,
73
+ checkoutStarts: sources.reduce((n, s) => n + s.checkoutStarts, 0),
74
+ };
75
+ return { days, since: new Date(sinceMs).toISOString(), sources, totals };
76
+ }
77
+
78
+ function getUtmSourceSummary(feedbackDir, options = {}) {
79
+ const now = options.now instanceof Date ? options.now : new Date();
80
+ const events = loadTelemetryEvents(feedbackDir);
81
+ return {
82
+ asOf: now.toISOString(),
83
+ note: 'External traffic only. Installs are distinct CLI install ids; a CLI ping carries a source only when the install command passed one.',
84
+ windows: WINDOW_DAYS.map((days) => summarizeWindow(events, days, now.getTime())),
85
+ };
86
+ }
87
+
88
+ module.exports = { getUtmSourceSummary, WINDOW_DAYS };
package/server.json CHANGED
@@ -8,13 +8,13 @@
8
8
  "source": "github",
9
9
  "url": "https://github.com/IgorGanapolsky/ThumbGate"
10
10
  },
11
- "version": "1.40.3",
11
+ "version": "1.40.6",
12
12
  "packages": [
13
13
  {
14
14
  "registryType": "npm",
15
15
  "registryBaseUrl": "https://registry.npmjs.org",
16
16
  "identifier": "thumbgate",
17
- "version": "1.40.3",
17
+ "version": "1.40.6",
18
18
  "runtimeHint": "npx",
19
19
  "runtimeArguments": [
20
20
  {
@@ -46,14 +46,17 @@ tell application "Comet"
46
46
  end tell'
47
47
 
48
48
  # Open or focus a specific URL in Comet
49
+ # The URL is passed as an argument (item 1 of argv), never spliced into the script text.
49
50
  open_comet_url() {
50
- local target_url="$1"
51
- osascript -e "
52
- tell application \"Comet\"
51
+ osascript - "$1" <<'APPLESCRIPT'
52
+ on run argv
53
+ tell application "Comet"
53
54
  activate
54
55
  tell front window
55
- make new tab with properties {URL:\"${target_url}\"}
56
+ make new tab with properties {URL:(item 1 of argv)}
56
57
  end tell
57
- end tell"
58
+ end tell
59
+ end run
60
+ APPLESCRIPT
58
61
  }
59
62
  ```