thumbgate 1.40.1 → 1.40.3

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 (64) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/adapters/claude/.mcp.json +3 -3
  4. package/adapters/forge/forge.yaml +3 -3
  5. package/adapters/future-agi/.mcp.json +1 -1
  6. package/adapters/future-agi/config.toml +1 -1
  7. package/adapters/future-agi/opencode.json +1 -1
  8. package/adapters/herdr/herdr-plugin.toml +2 -2
  9. package/adapters/mcp/server-stdio.js +4 -2
  10. package/adapters/opencode/opencode.json +1 -1
  11. package/config/github-about.json +1 -1
  12. package/package.json +41 -6
  13. package/public/index.html +38 -152
  14. package/public/install.html +8 -8
  15. package/public/numbers.html +2 -2
  16. package/public/pricing.html +54 -335
  17. package/scripts/analytics-report.js +363 -0
  18. package/scripts/auto-context-packs.js +249 -0
  19. package/scripts/billing-setup.js +137 -0
  20. package/scripts/check-update.js +236 -0
  21. package/scripts/conversion-rate-stats.js +442 -0
  22. package/scripts/cost-cli.js +147 -0
  23. package/scripts/creator-campaigns.js +239 -0
  24. package/scripts/cuda-gate-batch.js +560 -0
  25. package/scripts/daemon-manager.js +108 -0
  26. package/scripts/dashboard.js +2 -2
  27. package/scripts/delegation-runtime.js +1036 -0
  28. package/scripts/dispatch-brief.js +159 -0
  29. package/scripts/distribution-surfaces.js +110 -0
  30. package/scripts/egm-goldfish-packet.js +95 -0
  31. package/scripts/embeddinggemma-adapter.js +407 -0
  32. package/scripts/feedback-loop.js +4 -1
  33. package/scripts/funnel-analytics.js +35 -0
  34. package/scripts/gate-semantic-layer.js +292 -0
  35. package/scripts/human-feedback.js +23 -0
  36. package/scripts/implementation-notes.js +241 -0
  37. package/scripts/intent-router.js +518 -0
  38. package/scripts/latency-budget.js +164 -0
  39. package/scripts/mcp-writeguard.js +158 -0
  40. package/scripts/model-candidates.js +414 -0
  41. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  42. package/scripts/operational-dashboard.js +172 -0
  43. package/scripts/operational-summary.js +190 -0
  44. package/scripts/operator-artifacts.js +622 -0
  45. package/scripts/optimize-context.js +17 -0
  46. package/scripts/predictive-insights.js +449 -0
  47. package/scripts/profound-aeo-citation-engine.js +583 -0
  48. package/scripts/pulse.js +80 -0
  49. package/scripts/rrsi-doctor.js +2698 -0
  50. package/scripts/session-report.js +120 -0
  51. package/scripts/statusline-human-counts.js +69 -0
  52. package/scripts/statusline-links.js +13 -3
  53. package/scripts/statusline-local-stats.js +5 -3
  54. package/scripts/statusline.sh +17 -2
  55. package/scripts/subagent-profiles.js +79 -0
  56. package/scripts/third-author-cli.js +118 -0
  57. package/scripts/third-author-governance.js +437 -0
  58. package/scripts/thumbgate-dream.js +878 -0
  59. package/server.json +2 -2
  60. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  61. package/src/api/server.js +6 -0
  62. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  63. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  64. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -0,0 +1,363 @@
1
+ 'use strict';
2
+
3
+ const https = require('https');
4
+ const { PRODUCTHUNT_URL } = require('./distribution-surfaces');
5
+ const { getOperationalBillingSummary } = require('./operational-summary');
6
+ const { summarizeCreatorPerformance } = require('./creator-campaigns');
7
+ const { getFeedbackPaths } = require('./feedback-loop');
8
+ const { buildPredictiveInsights } = require('./predictive-insights');
9
+ const { getTelemetryAnalytics } = require('./telemetry-analytics');
10
+
11
+ const NPM_PACKAGE = 'thumbgate';
12
+ const GITHUB_REPO = 'IgorGanapolsky/ThumbGate';
13
+ const PLAUSIBLE_URL = 'https://plausible.io/thumbgate-production.up.railway.app';
14
+ const LANDING_PAGE = 'https://thumbgate-production.up.railway.app';
15
+
16
+ function httpsGet(url) {
17
+ const headers = { 'User-Agent': 'thumbgate-analytics' };
18
+ let parsedUrl;
19
+ try {
20
+ parsedUrl = new URL(url);
21
+ } catch (_) {}
22
+ if (parsedUrl && parsedUrl.hostname === 'api.github.com' && process.env.GITHUB_TOKEN) {
23
+ headers['Authorization'] = `token ${process.env.GITHUB_TOKEN}`;
24
+ }
25
+ return new Promise((resolve, reject) => {
26
+ https.get(url, { headers }, (res) => {
27
+ let data = '';
28
+ res.on('data', (chunk) => { data += chunk; });
29
+ res.on('end', () => {
30
+ if (res.statusCode >= 400) {
31
+ reject(new Error(`HTTP ${res.statusCode} for ${url}: ${data}`));
32
+ return;
33
+ }
34
+ try { resolve(JSON.parse(data)); } catch (e) { reject(e); }
35
+ });
36
+ }).on('error', reject);
37
+ });
38
+ }
39
+
40
+ function sparkline(values) {
41
+ const chars = '▁▂▃▄▅▆▇█';
42
+ const max = Math.max(...values, 1);
43
+ return values.map((v) => chars[Math.min(Math.floor((v / max) * (chars.length - 1)), chars.length - 1)]).join('');
44
+ }
45
+
46
+ async function fetchNpmMonthly() {
47
+ return httpsGet(`https://api.npmjs.org/downloads/range/last-month/${NPM_PACKAGE}`);
48
+ }
49
+
50
+ async function fetchNpmWeekly() {
51
+ return httpsGet(`https://api.npmjs.org/downloads/point/last-week/${NPM_PACKAGE}`);
52
+ }
53
+
54
+ async function fetchGitHub() {
55
+ return httpsGet(`https://api.github.com/repos/${GITHUB_REPO}`);
56
+ }
57
+
58
+ async function fetchNpmVersions() {
59
+ return httpsGet(`https://registry.npmjs.org/${NPM_PACKAGE}`);
60
+ }
61
+
62
+ function loadTelemetrySnapshot() {
63
+ const { FEEDBACK_DIR } = getFeedbackPaths();
64
+ return getTelemetryAnalytics(FEEDBACK_DIR);
65
+ }
66
+
67
+ function getCounterValue(counter = {}, key) {
68
+ return Number(counter && counter[key]) || 0;
69
+ }
70
+
71
+ function mergeDimensionCounters(metricCounters = {}) {
72
+ const metrics = Object.keys(metricCounters);
73
+ const rows = new Map();
74
+
75
+ for (const metric of metrics) {
76
+ const counter = metricCounters[metric] || {};
77
+ for (const [rawKey, rawValue] of Object.entries(counter)) {
78
+ const key = String(rawKey || '').trim() || 'unknown';
79
+ const row = rows.get(key) || { key };
80
+ row[metric] = Number(rawValue || 0);
81
+ rows.set(key, row);
82
+ }
83
+ }
84
+
85
+ return Array.from(rows.values());
86
+ }
87
+
88
+ function buildPredictiveStagingModel(telemetry = {}, billingSummary = {}) {
89
+ return {
90
+ dims: {
91
+ sources: mergeDimensionCounters({
92
+ pageViews: telemetry.visitors && telemetry.visitors.bySource,
93
+ checkoutStarts: telemetry.ctas && telemetry.ctas.checkoutStartsBySource,
94
+ acquisitionLeads: billingSummary.attribution && billingSummary.attribution.acquisitionBySource,
95
+ paidCustomers: billingSummary.attribution && billingSummary.attribution.paidBySource,
96
+ bookedRevenueCents: billingSummary.attribution && billingSummary.attribution.bookedRevenueBySourceCents,
97
+ }),
98
+ creators: mergeDimensionCounters({
99
+ pageViews: telemetry.visitors && telemetry.visitors.byCreator,
100
+ checkoutStarts: telemetry.ctas && telemetry.ctas.checkoutStartsByCreator,
101
+ acquisitionLeads: billingSummary.attribution && billingSummary.attribution.acquisitionByCreator,
102
+ paidCustomers: billingSummary.attribution && billingSummary.attribution.paidByCreator,
103
+ bookedRevenueCents: billingSummary.attribution && billingSummary.attribution.bookedRevenueByCreatorCents,
104
+ workflowSprintLeads: billingSummary.pipeline && billingSummary.pipeline.workflowSprintLeads && billingSummary.pipeline.workflowSprintLeads.byCreator,
105
+ qualifiedWorkflowSprintLeads: billingSummary.pipeline && billingSummary.pipeline.qualifiedWorkflowSprintLeads && billingSummary.pipeline.qualifiedWorkflowSprintLeads.byCreator,
106
+ }),
107
+ },
108
+ };
109
+ }
110
+
111
+ function resolveProductHuntCount(primaryCounter = {}, secondaryCounter = {}) {
112
+ const primary = getCounterValue(primaryCounter, 'producthunt');
113
+ if (primary > 0) return primary;
114
+ return getCounterValue(secondaryCounter, 'producthunt');
115
+ }
116
+
117
+ async function collectAnalytics(fetchers = {}) {
118
+ const fetchMonthly = fetchers.fetchNpmMonthly || fetchNpmMonthly;
119
+ const fetchWeekly = fetchers.fetchNpmWeekly || fetchNpmWeekly;
120
+ const fetchRepo = fetchers.fetchGitHub || fetchGitHub;
121
+ const fetchVersions = fetchers.fetchNpmVersions || fetchNpmVersions;
122
+ const fetchTelemetry = fetchers.fetchTelemetry || loadTelemetrySnapshot;
123
+ const fetchBillingSummary = fetchers.fetchBillingSummary || (async () => {
124
+ const result = await getOperationalBillingSummary();
125
+ return result.summary;
126
+ });
127
+
128
+ const [monthly, weekly, github, npmMeta, telemetry, billingSummary] = await Promise.all([
129
+ fetchMonthly(),
130
+ fetchWeekly(),
131
+ fetchRepo(),
132
+ fetchVersions().catch(() => null),
133
+ Promise.resolve().then(() => fetchTelemetry()).catch(() => null),
134
+ Promise.resolve().then(() => fetchBillingSummary()).catch(() => null),
135
+ ]);
136
+
137
+ return { monthly, weekly, github, npmMeta, telemetry, billingSummary };
138
+ }
139
+
140
+ /**
141
+ * Estimate organic downloads by filtering out publish-day inflation.
142
+ * npm registry mirrors, bot crawlers (socket.dev, snyk, bundlephobia),
143
+ * and npm-stat bots all re-download on publish events.
144
+ * Weekend days with no publishes give the organic baseline.
145
+ */
146
+ function estimateOrganicDownloads(dailyDownloads, publishDates) {
147
+ const publishSet = new Set(publishDates);
148
+
149
+ let weekendNoPublishTotal = 0;
150
+ let weekendNoPublishCount = 0;
151
+ let publishDayTotal = 0;
152
+ let publishDayCount = 0;
153
+ let noPublishDayTotal = 0;
154
+ let noPublishDayCount = 0;
155
+
156
+ for (const day of dailyDownloads) {
157
+ const dt = new Date(day.day + 'T00:00:00Z');
158
+ const isWeekend = dt.getUTCDay() === 0 || dt.getUTCDay() === 6;
159
+ const isPublishDay = publishSet.has(day.day);
160
+
161
+ if (isPublishDay) {
162
+ publishDayTotal += day.downloads;
163
+ publishDayCount++;
164
+ } else {
165
+ noPublishDayTotal += day.downloads;
166
+ noPublishDayCount++;
167
+ if (isWeekend) {
168
+ weekendNoPublishTotal += day.downloads;
169
+ weekendNoPublishCount++;
170
+ }
171
+ }
172
+ }
173
+
174
+ const organicDailyBaseline = weekendNoPublishCount > 0
175
+ ? Math.round(weekendNoPublishTotal / weekendNoPublishCount)
176
+ : (noPublishDayCount > 0 ? Math.round(noPublishDayTotal / noPublishDayCount) : 0);
177
+
178
+ const totalDownloads = dailyDownloads.reduce((s, d) => s + d.downloads, 0);
179
+ const estimatedOrganic30d = organicDailyBaseline * 30;
180
+ const estimatedInflated = totalDownloads - estimatedOrganic30d;
181
+ const organicRate = totalDownloads > 0 ? (estimatedOrganic30d / totalDownloads * 100) : 0;
182
+
183
+ return {
184
+ organicDailyBaseline,
185
+ estimatedOrganic30d,
186
+ estimatedInflated: Math.max(0, estimatedInflated),
187
+ organicRate: Math.min(100, organicRate),
188
+ organicWeekly: organicDailyBaseline * 7,
189
+ publishDayAvg: publishDayCount > 0 ? Math.round(publishDayTotal / publishDayCount) : 0,
190
+ noPublishDayAvg: noPublishDayCount > 0 ? Math.round(noPublishDayTotal / noPublishDayCount) : 0,
191
+ publishDayCount,
192
+ totalDownloads,
193
+ };
194
+ }
195
+
196
+ function formatCreatorRows(telemetry = null, billingSummary = null) {
197
+ return summarizeCreatorPerformance(telemetry, billingSummary).map((entry, index) => {
198
+ const revenueDollars = (entry.bookedRevenueCents / 100).toFixed(2);
199
+ return ` ${index + 1}. ${entry.creator} — rev $${revenueDollars}, paid ${entry.paidOrders}, sprint ${entry.qualifiedSprintLeads}/${entry.sprintLeads}, checkouts ${entry.checkoutStarts}, visitors ${entry.visitors}`;
200
+ });
201
+ }
202
+
203
+ function formatReport(monthly, weekly, github, npmMeta, telemetry = null, billingSummary = null) {
204
+ const weeklyDownloads = weekly.downloads || 0;
205
+ const allDays = monthly.downloads || [];
206
+ const monthlyDownloads = allDays.reduce((sum, d) => sum + d.downloads, 0);
207
+ const dailyValues = allDays.slice(-7).map((d) => d.downloads);
208
+ const trend = sparkline(dailyValues);
209
+
210
+ // Extract publish dates from npm registry metadata
211
+ const publishDates = [];
212
+ if (npmMeta && npmMeta.time) {
213
+ for (const [version, timestamp] of Object.entries(npmMeta.time)) {
214
+ if (version !== 'created' && version !== 'modified') {
215
+ publishDates.push(timestamp.slice(0, 10));
216
+ }
217
+ }
218
+ }
219
+
220
+ const organic = estimateOrganicDownloads(allDays, publishDates);
221
+ const productHuntVisitors = telemetry
222
+ ? resolveProductHuntCount(telemetry.visitors.byTrafficChannel, telemetry.visitors.bySource)
223
+ : 0;
224
+ const productHuntCtas = telemetry
225
+ ? resolveProductHuntCount(telemetry.ctas.byTrafficChannel, telemetry.ctas.bySource)
226
+ : 0;
227
+ const productHuntCheckouts = telemetry
228
+ ? resolveProductHuntCount(telemetry.ctas.checkoutStartsByTrafficChannel, telemetry.ctas.checkoutStartsBySource)
229
+ : 0;
230
+ const telemetryWindow = telemetry && telemetry.window ? telemetry.window : 'all';
231
+ const telemetryLastSeen = telemetry && telemetry.latestSeenAt ? telemetry.latestSeenAt : 'none';
232
+ const trafficQuality = telemetry && telemetry.trafficQuality ? telemetry.trafficQuality : null;
233
+ const externalTraffic = trafficQuality && trafficQuality.external ? trafficQuality.external : null;
234
+ const exportReadiness = {
235
+ plausible: Boolean(process.env.PLAUSIBLE_API_KEY && (process.env.PLAUSIBLE_SITE_ID || process.env.PLAUSIBLE_DOMAIN)),
236
+ posthog: Boolean((process.env.POSTHOG_PERSONAL_API_KEY || process.env.POSTHOG_API_KEY) && process.env.POSTHOG_PROJECT_ID),
237
+ ga4: Boolean(process.env.GA4_PROPERTY_ID && (process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GOOGLE_CLIENT_EMAIL)),
238
+ };
239
+ const anyDashboardExportReady = exportReadiness.plausible || exportReadiness.posthog || exportReadiness.ga4;
240
+ const creatorRows = formatCreatorRows(telemetry, billingSummary);
241
+ const predictive = buildPredictiveInsights({
242
+ telemetryAnalytics: telemetry || {},
243
+ billingSummary: billingSummary || {},
244
+ stagingModel: buildPredictiveStagingModel(telemetry || {}, billingSummary || {}),
245
+ });
246
+
247
+ const lines = [
248
+ '',
249
+ '╔══════════════════════════════════════════════════════════════════╗',
250
+ '║ ThumbGate — Unified Analytics Snapshot ║',
251
+ '╚══════════════════════════════════════════════════════════════════╝',
252
+ '',
253
+ '📦 npm — thumbgate (REPORTED)',
254
+ ` Weekly downloads: ${weeklyDownloads.toLocaleString()}`,
255
+ ` Monthly downloads: ${monthlyDownloads.toLocaleString()}`,
256
+ ` Daily trend (7d): ${trend} [${dailyValues.join(', ')}]`,
257
+ '',
258
+ '🔬 npm — ORGANIC ESTIMATE (excluding publish-day + bot inflation)',
259
+ ` Organic baseline: ~${organic.organicDailyBaseline}/day → ~${organic.organicWeekly}/week → ~${organic.estimatedOrganic30d.toLocaleString()}/month`,
260
+ ` Publish-day avg: ${organic.publishDayAvg}/day (${organic.publishDayCount} publish days this period)`,
261
+ ` No-publish avg: ${organic.noPublishDayAvg}/day`,
262
+ ` Organic rate: ${organic.organicRate.toFixed(1)}% of reported downloads`,
263
+ ` Inflated by: ~${organic.estimatedInflated.toLocaleString()} downloads (registry mirrors, bots, self-installs)`,
264
+ '',
265
+ '⭐ GitHub — IgorGanapolsky/ThumbGate',
266
+ ` Stars: ${(github.stargazers_count || 0).toLocaleString()}`,
267
+ ` Forks: ${(github.forks_count || 0).toLocaleString()}`,
268
+ ` Open issues: ${(github.open_issues_count || 0).toLocaleString()}`,
269
+ ` Watchers: ${(github.subscribers_count || 0).toLocaleString()}`,
270
+ '',
271
+ '🌐 Landing Page',
272
+ ` Plausible: ${PLAUSIBLE_URL}`,
273
+ ` ⚠️ Check Plausible to exclude your own IP (Settings → filter)`,
274
+ '',
275
+ '🚀 ProductHunt',
276
+ ` Listing: ${PRODUCTHUNT_URL}`,
277
+ ` Tracked: utm_source=producthunt → traffic_channel=producthunt`,
278
+ ` Visitors: ${productHuntVisitors}`,
279
+ ` CTA clicks: ${productHuntCtas}`,
280
+ ` Checkouts: ${productHuntCheckouts}`,
281
+ ` Window: ${telemetryWindow}`,
282
+ ` Last seen: ${telemetryLastSeen}`,
283
+ '',
284
+ '🧼 First-party traffic quality',
285
+ ` Raw events: ${trafficQuality ? trafficQuality.rawEvents : 0}`,
286
+ ` External events: ${trafficQuality ? trafficQuality.externalEvents : 0}`,
287
+ ` Excluded events: ${trafficQuality ? trafficQuality.excludedEvents : 0}`,
288
+ ` Clean visitors: ${externalTraffic ? externalTraffic.uniqueVisitors : 0}`,
289
+ ` Clean page views: ${externalTraffic ? externalTraffic.pageViews : 0}`,
290
+ ` Clean checkouts: ${externalTraffic ? externalTraffic.checkoutStarts : 0}`,
291
+ ` Clean paths: ${externalTraffic && externalTraffic.visitorPaths ? externalTraffic.visitorPaths.length : 0}`,
292
+ ` Verdict: ${trafficQuality ? trafficQuality.verdict : 'missing'}`,
293
+ ...(trafficQuality && trafficQuality.topExclusionReason
294
+ ? [` Top exclusion: ${trafficQuality.topExclusionReason.key} (${trafficQuality.topExclusionReason.count}×)`]
295
+ : [' Top exclusion: none']),
296
+ '',
297
+ '📤 Dashboard-grade visitor-path exports',
298
+ ` Plausible API: ${exportReadiness.plausible ? 'configured' : 'missing PLAUSIBLE_API_KEY + site id/domain'}`,
299
+ ` PostHog API: ${exportReadiness.posthog ? 'configured' : 'missing POSTHOG_* export credentials'}`,
300
+ ` GA4 Data API: ${exportReadiness.ga4 ? 'configured' : 'missing GA4_PROPERTY_ID + Google credentials'}`,
301
+ ` Export verdict: ${anyDashboardExportReady ? 'ready for provider path pulls' : 'not dashboard-grade in this repo yet'}`,
302
+ '',
303
+ '🎥 Creator Partnerships',
304
+ ' Ranked: booked revenue → paid orders → qualified sprint leads → checkouts',
305
+ ...(creatorRows.length > 0 ? creatorRows : [' No attributed creator campaigns yet.']),
306
+ '',
307
+ '🔮 Predictive Insights',
308
+ ` Pro propensity: ${predictive.upgradePropensity.pro.band} (${predictive.upgradePropensity.pro.score})`,
309
+ ` Team propensity: ${predictive.upgradePropensity.team.band} (${predictive.upgradePropensity.team.score})`,
310
+ ` Revenue forecast: $${(predictive.revenueForecast.predictedBookedRevenueCents / 100).toFixed(2)} (+$${(predictive.revenueForecast.incrementalOpportunityCents / 100).toFixed(2)} opportunity)`,
311
+ ` Predictive alerts:${predictive.anomalySummary.count} (${predictive.anomalySummary.severity})`,
312
+ ...(predictive.topCreators[0]
313
+ ? [` Top creator opp: ${predictive.topCreators[0].key} → +$${(predictive.topCreators[0].opportunityRevenueCents / 100).toFixed(2)}`]
314
+ : [' Top creator opp: none yet']),
315
+ ...(predictive.topSources[0]
316
+ ? [` Top channel opp: ${predictive.topSources[0].key} → +$${(predictive.topSources[0].opportunityRevenueCents / 100).toFixed(2)}`]
317
+ : [' Top channel opp: none yet']),
318
+ '',
319
+ '🔗 UTM links for sharing (tracks referral source in Plausible)',
320
+ ` Twitter: ${LANDING_PAGE}?utm_source=twitter&utm_medium=social&utm_campaign=launch`,
321
+ ` LinkedIn: ${LANDING_PAGE}?utm_source=linkedin&utm_medium=social&utm_campaign=launch`,
322
+ ` Reddit: ${LANDING_PAGE}?utm_source=reddit&utm_medium=social&utm_campaign=launch`,
323
+ ` HackerNews: ${LANDING_PAGE}?utm_source=hackernews&utm_medium=social&utm_campaign=launch`,
324
+ '',
325
+ '📏 HONEST METRICS (use these, not the inflated ones)',
326
+ ` Real npm traction: ~${organic.organicWeekly} downloads/week`,
327
+ ` GitHub stars: ${(github.stargazers_count || 0)}`,
328
+ ` ProductHunt: check listing for upvotes/followers`,
329
+ ` Landing page: check Plausible (exclude your IP!)`,
330
+ '',
331
+ ];
332
+
333
+ return lines.join('\n');
334
+ }
335
+
336
+ async function run(options = {}) {
337
+ const log = options.log || console.log;
338
+ const error = options.error || console.error;
339
+ const exit = options.exit || process.exit;
340
+
341
+ try {
342
+ const { monthly, weekly, github, npmMeta, telemetry, billingSummary } = await collectAnalytics(options.fetchers);
343
+ log(formatReport(monthly, weekly, github, npmMeta, telemetry, billingSummary));
344
+ } catch (err) {
345
+ error('Analytics fetch failed:', err.message);
346
+ exit(1);
347
+ }
348
+ }
349
+
350
+ module.exports = {
351
+ run,
352
+ collectAnalytics,
353
+ formatReport,
354
+ fetchNpmMonthly,
355
+ fetchNpmWeekly,
356
+ fetchGitHub,
357
+ fetchNpmVersions,
358
+ estimateOrganicDownloads,
359
+ };
360
+
361
+ if (require.main === module) {
362
+ run();
363
+ }
@@ -0,0 +1,249 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Auto-Context Packs
6
+ *
7
+ * Automatically assembles context packs from the top recurring failure patterns.
8
+ * Reads feedback logs and gate stats, identifies the top 5 most-blocked gate IDs
9
+ * and top 5 most-common failure tags, then assembles context packs for each.
10
+ *
11
+ * Output: .claude/memory/feedback/contextfs/auto/<pack-name>.json
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const { analyzeFeedback } = require('./feedback-loop');
18
+ const { calculateStats, loadGatesFile, MANUAL_GATES_PATH } = require('./gate-stats');
19
+ const { resolveFeedbackDir } = require('./feedback-paths');
20
+ const { ensureDir } = require('./fs-utils');
21
+
22
+ const TOP_N = 5;
23
+ const MAX_FEEDBACK_ENTRIES = 10;
24
+
25
+ function getAutoPacksDir() {
26
+ if (process.env.THUMBGATE_AUTO_PACKS_DIR) return process.env.THUMBGATE_AUTO_PACKS_DIR;
27
+ const feedbackDir = resolveFeedbackDir();
28
+ return path.join(feedbackDir, 'contextfs', 'auto');
29
+ }
30
+
31
+ function loadFeedbackEntries(logPath) {
32
+ if (!logPath || !fs.existsSync(logPath)) return [];
33
+ const lines = fs.readFileSync(logPath, 'utf-8').split('\n');
34
+ const entries = [];
35
+ for (const line of lines) {
36
+ const trimmed = line.trim();
37
+ if (!trimmed) continue;
38
+ try {
39
+ entries.push(JSON.parse(trimmed));
40
+ } catch {
41
+ // skip malformed lines
42
+ }
43
+ }
44
+ return entries;
45
+ }
46
+
47
+ function loadAllGateDefinitions() {
48
+ const PROJECT_ROOT = path.join(__dirname, '..');
49
+ const manualGates = loadGatesFile(MANUAL_GATES_PATH);
50
+
51
+ // Also try to load auto-promoted gates
52
+ let autoGates = [];
53
+ try {
54
+ const { getAutoGatesPath } = require('./auto-promote-gates');
55
+ autoGates = loadGatesFile(getAutoGatesPath());
56
+ } catch {
57
+ // auto-promoted gates not available — that's fine
58
+ }
59
+
60
+ return [...manualGates, ...autoGates];
61
+ }
62
+
63
+ function getTopBlockedGateIds(stats) {
64
+ const gates = (stats.gates || []).filter(
65
+ (g) => g.action === 'block' && Number(g.occurrences || 0) > 0
66
+ );
67
+ gates.sort((a, b) => (b.occurrences || 0) - (a.occurrences || 0));
68
+ return gates.slice(0, TOP_N).map((g) => g.id).filter(Boolean);
69
+ }
70
+
71
+ function getTopFailureTags(analysis) {
72
+ const tags = analysis.tags || {};
73
+ const tagList = Object.entries(tags)
74
+ .map(([tag, counts]) => ({ tag, negative: counts.negative || 0, total: counts.total || 0 }))
75
+ .filter((t) => t.negative > 0)
76
+ .sort((a, b) => b.negative - a.negative);
77
+ return tagList.slice(0, TOP_N).map((t) => t.tag);
78
+ }
79
+
80
+ function getFeedbackForGate(entries, gateId) {
81
+ return entries
82
+ .filter((e) => {
83
+ const tags = e.tags || [];
84
+ return (
85
+ e.gateId === gateId ||
86
+ tags.includes(gateId) ||
87
+ (e.context || '').includes(gateId) ||
88
+ (e.whatWentWrong || '').includes(gateId)
89
+ );
90
+ })
91
+ .slice(-MAX_FEEDBACK_ENTRIES);
92
+ }
93
+
94
+ function getFeedbackForTag(entries, tag) {
95
+ return entries
96
+ .filter((e) => {
97
+ const tags = e.tags || [];
98
+ return tags.includes(tag);
99
+ })
100
+ .slice(-MAX_FEEDBACK_ENTRIES);
101
+ }
102
+
103
+ function extractCorrectiveAction(entry) {
104
+ return entry.whatToChange || entry.correctiveAction || entry.lesson || null;
105
+ }
106
+
107
+ function buildPackForGate(gateId, gateDef, feedbackEntries, allEntries) {
108
+ const relevantFeedback = getFeedbackForGate(allEntries, gateId);
109
+ const correctiveActions = relevantFeedback
110
+ .map(extractCorrectiveAction)
111
+ .filter(Boolean)
112
+ .slice(0, 3);
113
+
114
+ return {
115
+ type: 'gate-failure',
116
+ gateId,
117
+ generatedAt: new Date().toISOString(),
118
+ gate: gateDef || { id: gateId },
119
+ recentFeedback: relevantFeedback.map((e) => ({
120
+ signal: e.signal,
121
+ tags: e.tags || [],
122
+ context: (e.context || '').slice(0, 300),
123
+ whatWentWrong: (e.whatWentWrong || '').slice(0, 300),
124
+ timestamp: e.timestamp || null,
125
+ })),
126
+ correctiveActions,
127
+ summary: {
128
+ totalFeedbackMatched: relevantFeedback.length,
129
+ hasCorrectiveAction: correctiveActions.length > 0,
130
+ },
131
+ };
132
+ }
133
+
134
+ function buildPackForTag(tag, feedbackEntries) {
135
+ const relevantFeedback = getFeedbackForTag(feedbackEntries, tag);
136
+ const correctiveActions = relevantFeedback
137
+ .map(extractCorrectiveAction)
138
+ .filter(Boolean)
139
+ .slice(0, 3);
140
+
141
+ return {
142
+ type: 'tag-failure',
143
+ tag,
144
+ generatedAt: new Date().toISOString(),
145
+ recentFeedback: relevantFeedback.map((e) => ({
146
+ signal: e.signal,
147
+ tags: e.tags || [],
148
+ context: (e.context || '').slice(0, 300),
149
+ whatWentWrong: (e.whatWentWrong || '').slice(0, 300),
150
+ timestamp: e.timestamp || null,
151
+ })),
152
+ correctiveActions,
153
+ summary: {
154
+ totalFeedbackMatched: relevantFeedback.length,
155
+ hasCorrectiveAction: correctiveActions.length > 0,
156
+ },
157
+ };
158
+ }
159
+
160
+ function toSlug(input) {
161
+ return String(input || 'item')
162
+ .toLowerCase()
163
+ .replace(/[^a-z0-9]+/g, '-')
164
+ .replace(/^-+|-+$/g, '')
165
+ .slice(0, 60) || 'item';
166
+ }
167
+
168
+ /**
169
+ * Generate context packs from top failure patterns.
170
+ *
171
+ * @param {Object} [options]
172
+ * @param {string} [options.feedbackLogPath] - Override the feedback log path.
173
+ * @param {string} [options.outputDir] - Override the output directory.
174
+ * @returns {{ packCount: number, packs: Array<{name: string, filePath: string, type: string, id: string}> }}
175
+ */
176
+ function generateAutoContextPacks(options = {}) {
177
+ const outputDir = options.outputDir || getAutoPacksDir();
178
+ ensureDir(outputDir);
179
+
180
+ // Load analysis data — handle empty/missing gracefully
181
+ let analysis = { tags: {}, topTags: [] };
182
+ try {
183
+ analysis = analyzeFeedback(options.feedbackLogPath || undefined);
184
+ } catch {
185
+ // degrade gracefully if feedback log is missing or unreadable
186
+ }
187
+
188
+ let stats = { gates: [], totalBlocked: 0 };
189
+ try {
190
+ stats = calculateStats();
191
+ } catch {
192
+ // degrade gracefully if gate stats cannot be loaded
193
+ }
194
+
195
+ // Load raw feedback entries for context matching
196
+ const { getFeedbackPaths } = require('./feedback-loop');
197
+ const feedbackPaths = getFeedbackPaths();
198
+ const logPath = options.feedbackLogPath || feedbackPaths.FEEDBACK_LOG_PATH;
199
+ const allEntries = loadFeedbackEntries(logPath);
200
+
201
+ // Load gate definitions for enrichment
202
+ const allGates = loadAllGateDefinitions();
203
+ const gateById = {};
204
+ for (const g of allGates) {
205
+ if (g.id) gateById[g.id] = g;
206
+ }
207
+
208
+ const packs = [];
209
+
210
+ // -- Top 5 blocked gate IDs --
211
+ const topGateIds = getTopBlockedGateIds(stats);
212
+ for (const gateId of topGateIds) {
213
+ const pack = buildPackForGate(gateId, gateById[gateId] || null, [], allEntries);
214
+ const slug = `gate-${toSlug(gateId)}`;
215
+ const filePath = path.join(outputDir, `${slug}.json`);
216
+ fs.writeFileSync(filePath, JSON.stringify(pack, null, 2) + '\n');
217
+ packs.push({ name: slug, filePath, type: 'gate-failure', id: gateId });
218
+ }
219
+
220
+ // -- Top 5 failure tags --
221
+ const topTags = getTopFailureTags(analysis);
222
+ for (const tag of topTags) {
223
+ const pack = buildPackForTag(tag, allEntries);
224
+ const slug = `tag-${toSlug(tag)}`;
225
+ const filePath = path.join(outputDir, `${slug}.json`);
226
+ fs.writeFileSync(filePath, JSON.stringify(pack, null, 2) + '\n');
227
+ packs.push({ name: slug, filePath, type: 'tag-failure', id: tag });
228
+ }
229
+
230
+ return { packCount: packs.length, packs };
231
+ }
232
+
233
+ module.exports = {
234
+ generateAutoContextPacks,
235
+ getAutoPacksDir,
236
+ getTopBlockedGateIds,
237
+ getTopFailureTags,
238
+ };
239
+
240
+ if (path.resolve(process.argv[1]) === path.resolve(__filename)) {
241
+ const result = generateAutoContextPacks();
242
+ console.log(`Generated ${result.packCount} context pack(s):`);
243
+ for (const p of result.packs) {
244
+ console.log(` [${p.type}] ${p.name} -> ${p.filePath}`);
245
+ }
246
+ if (result.packCount === 0) {
247
+ console.log(' (No failure patterns found yet — capture some feedback first.)');
248
+ }
249
+ }