thumbgate 1.4.1 → 1.4.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 (60) hide show
  1. package/.claude-plugin/README.md +45 -34
  2. package/.claude-plugin/marketplace.json +3 -3
  3. package/.claude-plugin/plugin.json +3 -3
  4. package/.well-known/llms.txt +1 -1
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +26 -2
  7. package/adapters/README.md +4 -1
  8. package/adapters/chatgpt/INSTALL.md +39 -19
  9. package/adapters/claude/.mcp.json +2 -2
  10. package/adapters/codex/config.toml +2 -2
  11. package/adapters/mcp/server-stdio.js +10 -4
  12. package/adapters/opencode/opencode.json +1 -1
  13. package/adapters/perplexity/.mcp.json +36 -0
  14. package/adapters/perplexity/config.toml +16 -0
  15. package/adapters/perplexity/opencode.json +29 -0
  16. package/bin/cli.js +246 -90
  17. package/config/mcp-allowlists.json +11 -3
  18. package/package.json +28 -13
  19. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +1 -1
  20. package/plugins/claude-codex-bridge/.mcp.json +1 -1
  21. package/plugins/codex-profile/.codex-plugin/plugin.json +1 -1
  22. package/plugins/codex-profile/.mcp.json +1 -1
  23. package/plugins/codex-profile/INSTALL.md +1 -1
  24. package/plugins/codex-profile/README.md +1 -1
  25. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +1 -1
  26. package/plugins/opencode-profile/INSTALL.md +1 -1
  27. package/public/index.html +121 -24
  28. package/public/llm-context.md +17 -1
  29. package/scripts/ai-search-visibility.js +10 -36
  30. package/scripts/audit-trail.js +25 -15
  31. package/scripts/auto-wire-hooks.js +127 -0
  32. package/scripts/cli-demo.js +102 -0
  33. package/scripts/cli-schema.js +285 -0
  34. package/scripts/cli-status.js +166 -0
  35. package/scripts/cross-encoder-reranker.js +235 -0
  36. package/scripts/explore-subcommands.js +277 -0
  37. package/scripts/explore.js +569 -0
  38. package/scripts/feedback-loop.js +20 -6
  39. package/scripts/lesson-inference.js +27 -2
  40. package/scripts/lesson-reranker.js +263 -0
  41. package/scripts/lesson-retrieval.js +34 -17
  42. package/scripts/lesson-search.js +69 -0
  43. package/scripts/perplexity-client.js +210 -0
  44. package/scripts/perplexity-command-center.js +644 -0
  45. package/scripts/perplexity-marketing.js +17 -29
  46. package/scripts/prove-packaged-runtime.js +5 -4
  47. package/scripts/ralph-mode-ci.js +122 -19
  48. package/scripts/reflector-agent.js +2 -2
  49. package/scripts/session-analyzer.js +533 -0
  50. package/scripts/social-analytics/db/marketing-db.js +179 -0
  51. package/scripts/social-analytics/db/schema.sql +23 -0
  52. package/scripts/social-analytics/generate-instagram-card.js +31 -5
  53. package/scripts/social-analytics/generate-slides.js +268 -0
  54. package/scripts/social-analytics/post-video.js +316 -0
  55. package/scripts/social-analytics/publishers/zernio.js +52 -23
  56. package/scripts/statusline-local-stats.js +3 -1
  57. package/scripts/statusline.sh +15 -10
  58. package/scripts/thumbgate-bench.js +494 -0
  59. package/src/api/server.js +65 -1
  60. package/scripts/social-analytics/db/analytics.sqlite +0 -0
@@ -30,3 +30,26 @@ CREATE TABLE IF NOT EXISTS follower_snapshots (
30
30
 
31
31
  CREATE INDEX IF NOT EXISTS idx_metrics_platform_date ON engagement_metrics(platform, metric_date);
32
32
  CREATE INDEX IF NOT EXISTS idx_metrics_published ON engagement_metrics(published_at);
33
+
34
+ -- Marketing posts: tracks every post, video, and article published to any platform.
35
+ -- Used to prevent double-posting and to measure marketing effort over time.
36
+ CREATE TABLE IF NOT EXISTS marketing_posts (
37
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
38
+ type TEXT NOT NULL CHECK(type IN ('post','video','article','reply','thread')),
39
+ platform TEXT NOT NULL,
40
+ account_id TEXT,
41
+ post_id TEXT,
42
+ post_url TEXT,
43
+ title TEXT,
44
+ content_hash TEXT NOT NULL,
45
+ published_at TEXT NOT NULL,
46
+ status TEXT NOT NULL DEFAULT 'published' CHECK(status IN ('published','failed','skipped','draft')),
47
+ tags TEXT, -- JSON array
48
+ campaign TEXT, -- e.g. 'v1.4.1-launch', 'weekly-stats'
49
+ extra_json TEXT, -- arbitrary metadata
50
+ UNIQUE(platform, content_hash)
51
+ );
52
+
53
+ CREATE INDEX IF NOT EXISTS idx_mktg_platform_published ON marketing_posts(platform, published_at);
54
+ CREATE INDEX IF NOT EXISTS idx_mktg_campaign ON marketing_posts(campaign);
55
+ CREATE INDEX IF NOT EXISTS idx_mktg_type ON marketing_posts(type);
@@ -19,10 +19,36 @@ try { sharp = require('sharp'); } catch { /* optional dependency */ }
19
19
  const REPO_ROOT = path.resolve(__dirname, '../..');
20
20
  const DEFAULT_OUTPUT = path.join(REPO_ROOT, '.thumbgate', 'instagram-card.png');
21
21
 
22
- async function generateInstagramCard(outputPath = DEFAULT_OUTPUT) {
22
+ const CARD_VARIANTS = [
23
+ { headline: ['Your AI agent', 'has amnesia.'], sub: ['Give it memory that', 'survives restarts.'] },
24
+ { headline: ['CLAUDE.md is', 'a wish list.'], sub: ['ThumbGate is', 'enforcement.'] },
25
+ { headline: ['One thumbs-down.', 'Never again.'], sub: ['Mistakes become', 'prevention rules.'] },
26
+ { headline: ['33 pre-action', 'gates.'], sub: ['Block before execution.', 'Not after damage.'] },
27
+ { headline: ['AI agent broke', 'production?'], sub: ['That exact pattern', 'is now blocked forever.'] },
28
+ { headline: ['Fight AI', 'with AI.'], sub: ['Self-tuning gates.', 'Thompson Sampling.'] },
29
+ { headline: ['Your agent can\'t', 'disable this.'], sub: ['Self-protection gates.', '4 layers deep.'] },
30
+ { headline: ['NIST. SOC2.', 'OWASP. CWE.'], sub: ['Compliance tags on', 'every gate rule.'] },
31
+ { headline: ['500 actions.', '2.5 hours.'], sub: ['Budget enforcement.', 'No runaway agents.'] },
32
+ { headline: ['First AI-agent', 'cyberattack confirmed.'], sub: ['PreToolUse hooks', 'block before execution.'] },
33
+ ];
34
+
35
+ async function generateInstagramCard(outputPath = DEFAULT_OUTPUT, options = {}) {
23
36
  const width = 1080;
24
37
  const height = 1080;
25
38
 
39
+ // Pick a variant: explicit, random, or rotate based on day
40
+ let variant;
41
+ if (options.variantIndex !== undefined) {
42
+ variant = CARD_VARIANTS[options.variantIndex % CARD_VARIANTS.length];
43
+ } else {
44
+ const dayOfYear = Math.floor((Date.now() - new Date(new Date().getFullYear(), 0, 0).getTime()) / 86400000);
45
+ const hourSlot = Math.floor(new Date().getHours() / 8); // 3 slots per day
46
+ variant = CARD_VARIANTS[(dayOfYear * 3 + hourSlot) % CARD_VARIANTS.length];
47
+ }
48
+
49
+ const h1 = options.headline || variant.headline;
50
+ const sub = options.sub || variant.sub;
51
+
26
52
  // Create SVG markup for the card
27
53
  const svg = `
28
54
  <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
@@ -31,18 +57,18 @@ async function generateInstagramCard(outputPath = DEFAULT_OUTPUT) {
31
57
 
32
58
  <!-- Main heading -->
33
59
  <text x="${width / 2}" y="400" font-size="72" font-weight="bold" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif">
34
- Your AI agent
60
+ ${h1[0]}
35
61
  </text>
36
62
  <text x="${width / 2}" y="490" font-size="72" font-weight="bold" text-anchor="middle" fill="#ffffff" font-family="Arial, sans-serif">
37
- has amnesia.
63
+ ${h1[1]}
38
64
  </text>
39
65
 
40
66
  <!-- Subheading -->
41
67
  <text x="${width / 2}" y="620" font-size="48" text-anchor="middle" fill="#888888" font-family="Arial, sans-serif">
42
- Give it memory that
68
+ ${sub[0]}
43
69
  </text>
44
70
  <text x="${width / 2}" y="680" font-size="48" text-anchor="middle" fill="#888888" font-family="Arial, sans-serif">
45
- survives restarts.
71
+ ${sub[1]}
46
72
  </text>
47
73
 
48
74
  <!-- Brand -->
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * generate-slides.js
6
+ * Generates PNG slide frames for ThumbGate marketing short videos.
7
+ *
8
+ * 6 rotating templates — each tells a different story about the product.
9
+ * Templates are rotated by the post-scheduler so CI never reposts the
10
+ * same content within the configured cooldown window.
11
+ *
12
+ * Output: slide_01.png … slide_NN.png + manifest.json
13
+ * ffmpeg stitches them into MP4 via the video-autopilot CI workflow.
14
+ *
15
+ * Usage:
16
+ * node scripts/social-analytics/generate-slides.js
17
+ * node scripts/social-analytics/generate-slides.js --template=2
18
+ * node scripts/social-analytics/generate-slides.js --template=auto --out=/tmp
19
+ */
20
+
21
+ const { execSync } = require('node:child_process');
22
+ const path = require('node:path');
23
+ const fs = require('node:fs');
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Templates — 6 distinct story arcs, each 28-35 seconds
27
+ // Edit content here; rendering logic is unchanged.
28
+ // ---------------------------------------------------------------------------
29
+
30
+ const TEMPLATES = {
31
+
32
+ // 1 — Force-push wipes PRs
33
+ 1: {
34
+ name: 'force-push',
35
+ slides: [
36
+ { holdSeconds: 4, title: ['Your AI agent', 'just force-pushed', 'to main.'], subtitle: 'It wiped 3 open PRs.', lines: [], cta: null },
37
+ { holdSeconds: 4, title: ['You told it not to.', 'It did it again.'], subtitle: 'Prompts are suggestions — not constraints.', lines: [], cta: null },
38
+ { holdSeconds: 6, title: ['ThumbGate blocks it:'], subtitle: null, lines: ['→ Agent: git push --force origin main', '→ PreToolUse hook fires', '→ Gate #4: force-push to main', '✗ BLOCKED — rule auto-promoted', ' after 1 previous failure.'], cta: null },
39
+ { holdSeconds: 5, title: ['The feedback loop:'], subtitle: null, lines: ['👎 bad action captured', '→ lesson written to SQLite DB', '→ prevention rule generated', '→ PreToolUse gate activated', '✓ same mistake: blocked forever'], cta: null },
40
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'Live GPT + local gates', lines: [], cta: { line1: 'Try the GPT →', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
41
+ ],
42
+ },
43
+
44
+ // 2 — Deleted prod config
45
+ 2: {
46
+ name: 'deleted-config',
47
+ slides: [
48
+ { holdSeconds: 4, title: ['AI agent deleted', 'your prod config.'], subtitle: '"It looked unused."', lines: [], cta: null },
49
+ { holdSeconds: 4, title: ['2 hours of rollback.', 'For a file it', '"cleaned up".'], subtitle: null, lines: [], cta: null },
50
+ { holdSeconds: 6, title: ['Gate auto-created', 'after 1 failure:'], subtitle: null, lines: ['→ Agent: rm config/prod.json', '→ PreToolUse hook fires', '→ Pattern: rm config/*.json', '✗ BLOCKED — protected path', ' Add to .thumbgate/allowlist', ' to override explicitly.'], cta: null },
51
+ { holdSeconds: 5, title: ['Every 👎 becomes', 'a permanent gate.'], subtitle: null, lines: ['1 failure → warn gate', '3 failures → hard block', 'No config change required.', 'Automatic.'], cta: null },
52
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'npx thumbgate serve', lines: [], cta: { line1: 'Try the GPT →', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
53
+ ],
54
+ },
55
+
56
+ // 3 — Session amnesia
57
+ 3: {
58
+ name: 'session-amnesia',
59
+ slides: [
60
+ { holdSeconds: 4, title: ['Every new session,', 'your AI agent', 'forgets everything.'], subtitle: null, lines: [], cta: null },
61
+ { holdSeconds: 5, title: ['You re-explain.', 'It breaks the', 'same thing.', 'You fix it again.'], subtitle: 'Sound familiar?', lines: [], cta: null },
62
+ { holdSeconds: 6, title: ['ThumbGate gives it', 'persistent memory:'], subtitle: null, lines: ['→ 👎 on bad action', '→ lesson stored in SQLite+FTS5', '→ retrieved next session', '→ gate blocks same mistake', '✓ learning that persists'], cta: null },
63
+ { holdSeconds: 5, title: ['Session 1 vs 50:'], subtitle: null, lines: ['Session 1: same mistakes', 'Session 10: fewer mistakes', 'Session 50: gates block them', ' before you even see them.', 'Compounding prevention.'], cta: null },
64
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'Works with ChatGPT, Claude Code, Cursor, Codex CLI', lines: [], cta: { line1: 'Open the GPT →', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
65
+ ],
66
+ },
67
+
68
+ // 4 — Thompson Sampling (technical)
69
+ 4: {
70
+ name: 'thompson-sampling',
71
+ slides: [
72
+ { holdSeconds: 4, title: ['How do gates decide', 'which lessons', 'matter most?'], subtitle: 'Thompson Sampling.', lines: [], cta: null },
73
+ { holdSeconds: 6, title: ['Each gate has a', 'Beta distribution:'], subtitle: null, lines: ['Gate starts: Beta(1,1) = uniform', '👎 on trigger: alpha += 1', '👍 no issue: beta += 1', '→ High alpha = high-priority gate', '→ Rarely triggered = auto-demoted'], cta: null },
74
+ { holdSeconds: 5, title: ['After ~20 cycles,', 'gates self-sort:'], subtitle: null, lines: ['force-push → Beta(18,2) HIGH', 'rm config → Beta(12,3) HIGH', 'npm audit → Beta(2,15) demoted', '✓ signal rises, noise falls'], cta: null },
75
+ { holdSeconds: 5, title: ['No tuning.', 'No config.', 'Self-correcting.'], subtitle: 'The gate ranking adapts to your codebase.', lines: [], cta: null },
76
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'Thompson Sampling + LanceDB vector search', lines: [], cta: { line1: 'Try the GPT →', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
77
+ ],
78
+ },
79
+
80
+ // 5 — 30-second install demo
81
+ 5: {
82
+ name: 'install-demo',
83
+ slides: [
84
+ { holdSeconds: 4, title: ['Stop your AI agent', 'from making the', 'same mistakes.'], subtitle: 'Install in 30 seconds.', lines: [], cta: null },
85
+ { holdSeconds: 5, title: ['Step 1:'], subtitle: null, lines: ['npx thumbgate serve', '', '✓ MCP server running on :3001', '✓ SQLite lesson DB initialised', '✓ PreToolUse hook active'], cta: null },
86
+ { holdSeconds: 5, title: ['Step 2:'], subtitle: null, lines: ['Give a thumbs-down:', 'thumbgate feedback --down \\', ' "agent deleted prod config"', '', '→ Lesson captured + indexed'], cta: null },
87
+ { holdSeconds: 5, title: ['Step 3:', '(automatic)'], subtitle: null, lines: ['→ Prevention rule generated', '→ Gate created: rm config/*', '→ Next time agent tries it:', '✗ BLOCKED before execution'], cta: null },
88
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'Free. Open source. No sign-up.', lines: [], cta: { line1: 'Open the GPT first', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
89
+ ],
90
+ },
91
+
92
+ // 6 — Before/After comparison
93
+ 6: {
94
+ name: 'before-after',
95
+ slides: [
96
+ { holdSeconds: 4, title: ['Before ThumbGate:'], subtitle: null, lines: ['Agent runs dangerous command', 'You notice after deploy', 'You write a rule in CLAUDE.md', 'Agent ignores it next session', 'Repeat forever.'], cta: null },
97
+ { holdSeconds: 4, title: ['After ThumbGate:'], subtitle: null, lines: ['Agent tries dangerous command', '✗ BLOCKED by PreToolUse gate', 'Gate was promoted from your 👎', '✓ Never reaches production'], cta: null },
98
+ { holdSeconds: 5, title: ['The difference:'], subtitle: null, lines: ['CLAUDE.md = suggestion', 'ThumbGate = enforcement', '', 'Rules in files get ignored.', 'Gates cannot be ignored.'], cta: null },
99
+ { holdSeconds: 5, title: ['What changes:'], subtitle: null, lines: ['→ mistakes blocked pre-execution', '→ lessons persist across sessions', '→ gates auto-promote from failures', '→ DPO export for fine-tuning', '✓ compounding safety over time'], cta: null },
100
+ { holdSeconds: 6, title: ['ThumbGate', 'v1.4.1'], subtitle: 'Free + Open Source', lines: [], cta: { line1: 'Try the GPT →', line2: 'chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate' } },
101
+ ],
102
+ },
103
+
104
+ };
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Python renderer (unchanged — handles all templates via SLIDES var)
108
+ // ---------------------------------------------------------------------------
109
+
110
+ function buildPythonScript(slides, outDir) {
111
+ return `
112
+ import os, json as _json
113
+ from PIL import Image, ImageDraw, ImageFont
114
+
115
+ W, H = 1080, 1920
116
+ OUT_DIR = ${JSON.stringify(outDir)}
117
+ os.makedirs(OUT_DIR, exist_ok=True)
118
+
119
+ FONT_PATHS = {
120
+ 'bold': '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
121
+ 'regular': '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
122
+ 'mono': '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',
123
+ }
124
+
125
+ def font(name, size):
126
+ try: return ImageFont.truetype(FONT_PATHS.get(name, FONT_PATHS['regular']), size)
127
+ except: return ImageFont.load_default()
128
+
129
+ SLIDES = _json.loads(${JSON.stringify(JSON.stringify(slides))})
130
+
131
+ def bg():
132
+ img = Image.new('RGB', (W, H), '#0a0a0f')
133
+ d = ImageDraw.Draw(img)
134
+ for i in range(H):
135
+ r = i/H
136
+ d.line([(0,i),(W,i)], fill=(int(10+8*(1-r)), int(10+2*(1-r)), int(15+30*(1-r))))
137
+ return img, d
138
+
139
+ def draw_slide(s, idx):
140
+ img, d = bg()
141
+ d.rectangle([(0,0),(W,8)], fill='#6366f1')
142
+ d.rectangle([(0,H-8),(W,H)], fill='#6366f1')
143
+ y = 200
144
+ for tl in s.get('title', []):
145
+ d.text((80, y), tl, font=font('bold', 76), fill='#ffffff')
146
+ y += 95
147
+ y += 20
148
+ sub = s.get('subtitle')
149
+ if sub:
150
+ d.text((80, y), sub, font=font('regular', 44), fill='#8888aa')
151
+ y += 65
152
+ y += 20
153
+ lines = s.get('lines', [])
154
+ if lines:
155
+ d.rectangle([(40, y-20),(W-40, y+len(lines)*58+25)], fill='#12121e', outline='#2a2a3f', width=2)
156
+ for line in lines:
157
+ px = 70
158
+ if line.startswith('✗'):
159
+ d.text((px, y), '✗', font=font('bold', 38), fill='#ef4444')
160
+ d.text((px+40, y), line[1:], font=font('mono', 36), fill='#ffaaaa')
161
+ elif line.startswith('✓'):
162
+ d.text((px, y), '✓', font=font('bold', 38), fill='#22c55e')
163
+ d.text((px+40, y), line[1:], font=font('mono', 36), fill='#aaffaa')
164
+ elif line.startswith('→'):
165
+ d.text((px, y), '→', font=font('regular', 38), fill='#6366f1')
166
+ d.text((px+40, y), line[1:], font=font('mono', 36), fill='#d0d8f0')
167
+ elif line.startswith('👎'):
168
+ d.text((px, y), line, font=font('mono', 36), fill='#fbbf24')
169
+ else:
170
+ d.text((px, y), line, font=font('mono', 36), fill='#d0d8f0')
171
+ y += 58
172
+ cta = s.get('cta')
173
+ if cta:
174
+ cy = H - 320
175
+ d.rectangle([(60, cy),(W-60, cy+180)], fill='#6366f1')
176
+ d.text((80, cy+24), cta['line1'], font=font('bold', 56), fill='#ffffff')
177
+ d.text((80, cy+100), cta['line2'], font=font('regular', 38), fill='#e0e8ff')
178
+ img.save(os.path.join(OUT_DIR, f'slide_{idx:02d}.png'), 'PNG')
179
+ print(f' Wrote slide_{idx:02d}.png')
180
+
181
+ for i, slide in enumerate(SLIDES): draw_slide(slide, i+1)
182
+ print(f'Generated {len(SLIDES)} slides → {OUT_DIR}')
183
+ `;
184
+ }
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Template selector
188
+ // ---------------------------------------------------------------------------
189
+
190
+ /**
191
+ * Pick the next template to use, avoiding recent repeats.
192
+ * Reads marketing DB if available; falls back to round-robin by hour.
193
+ */
194
+ function pickTemplate(requestedId) {
195
+ if (requestedId && requestedId !== 'auto') {
196
+ const id = Number.parseInt(requestedId, 10);
197
+ if (!TEMPLATES[id]) { console.error(`Unknown template id: ${id}`); process.exit(1); }
198
+ return id;
199
+ }
200
+
201
+ // Try to pick least-recently-used from marketing DB
202
+ try {
203
+ const db = require('./db/marketing-db');
204
+ const recent = db.list({ type: 'video', days: 30, limit: 100 });
205
+ const usedTemplates = new Set(
206
+ recent.map(r => { try { return JSON.parse(r.extra_json || '{}').templateId; } catch { return null; } }).filter(Boolean)
207
+ );
208
+ const allIds = Object.keys(TEMPLATES).map(Number);
209
+ const unused = allIds.filter(id => !usedTemplates.has(id));
210
+ if (unused.length > 0) return unused[0]; // pick first unused
211
+ // All used — pick oldest
212
+ const templateCounts = {};
213
+ for (const r of recent) {
214
+ try { const t = JSON.parse(r.extra_json || '{}').templateId; if (t) templateCounts[t] = (templateCounts[t] || 0) + 1; } catch {}
215
+ }
216
+ const sortedIds = [...allIds];
217
+ sortedIds.sort((a, b) => (templateCounts[a] || 0) - (templateCounts[b] || 0));
218
+ return sortedIds[0];
219
+ } catch {
220
+ // Fallback: round-robin by 4-hour block
221
+ const block = Math.floor(Date.now() / (4 * 3600 * 1000));
222
+ const ids = Object.keys(TEMPLATES).map(Number);
223
+ return ids[block % ids.length];
224
+ }
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Entry point
229
+ // ---------------------------------------------------------------------------
230
+
231
+ function main() {
232
+ const args = process.argv.slice(2);
233
+ const outDir = args.find(a => a.startsWith('--out='))?.slice(6) || path.join(__dirname);
234
+ const campaign = args.find(a => a.startsWith('--campaign='))?.slice(11) || 'default';
235
+ const templateArg = args.find(a => a.startsWith('--template='))?.slice(11) || 'auto';
236
+
237
+ const templateId = pickTemplate(templateArg);
238
+ const template = TEMPLATES[templateId];
239
+
240
+ console.log(`[generate-slides] template=${templateId}(${template.name}) campaign=${campaign} out=${outDir}`);
241
+
242
+ const pyScript = buildPythonScript(template.slides, outDir);
243
+ const tmpPy = path.join(require('node:os').tmpdir(), 'thumbgate_slides.py');
244
+ fs.writeFileSync(tmpPy, pyScript);
245
+
246
+ try {
247
+ execSync(`python3 ${tmpPy}`, { stdio: 'inherit' });
248
+ } catch (err) {
249
+ console.error('[generate-slides] Python render failed:', err.message);
250
+ process.exit(1);
251
+ }
252
+
253
+ const manifest = {
254
+ templateId,
255
+ templateName: template.name,
256
+ campaign,
257
+ generatedAt: new Date().toISOString(),
258
+ slides: template.slides.map((s, i) => ({
259
+ file: `slide_${String(i + 1).padStart(2, '0')}.png`,
260
+ holdSeconds: s.holdSeconds,
261
+ })),
262
+ totalDuration: template.slides.reduce((sum, s) => sum + s.holdSeconds, 0),
263
+ };
264
+ fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
265
+ console.log(`[generate-slides] Done. template=${templateId} duration=${manifest.totalDuration}s`);
266
+ }
267
+
268
+ main();
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * post-video.js
6
+ * Generates a marketing short video and posts it to TikTok, YouTube, and
7
+ * Instagram Reels via Zernio. Tracks everything in the marketing DB to
8
+ * prevent double-posting.
9
+ *
10
+ * Usage:
11
+ * node scripts/social-analytics/post-video.js
12
+ * node scripts/social-analytics/post-video.js --campaign=v1.4.1 --dry-run
13
+ * node scripts/social-analytics/post-video.js --video=/path/to/custom.mp4
14
+ *
15
+ * Required env:
16
+ * ZERNIO_API_KEY
17
+ * Optional env (overrides hardcoded account IDs):
18
+ * ZERNIO_TIKTOK_ACCOUNT_ID
19
+ * ZERNIO_YOUTUBE_ACCOUNT_ID
20
+ * ZERNIO_INSTAGRAM_ACCOUNT_ID
21
+ */
22
+
23
+ const { execFileSync, execSync } = require('node:child_process');
24
+ const fs = require('node:fs');
25
+ const path = require('node:path');
26
+ const os = require('node:os');
27
+ const { loadLocalEnv } = require('./load-env');
28
+
29
+ loadLocalEnv();
30
+
31
+ const { hashContent, isDuplicate, record } = require('./db/marketing-db');
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Config
35
+ // ---------------------------------------------------------------------------
36
+
37
+ const ZERNIO_BASE = 'https://zernio.com/api/v1';
38
+
39
+ const ACCOUNTS = {
40
+ tiktok: process.env.ZERNIO_TIKTOK_ACCOUNT_ID || '69bee0fd6cb7b8cf4c8b2425',
41
+ youtube: process.env.ZERNIO_YOUTUBE_ACCOUNT_ID || '69c14dc36cb7b8cf4c91c1e4',
42
+ instagram: process.env.ZERNIO_INSTAGRAM_ACCOUNT_ID || '69bed6ad6cb7b8cf4c8b0865',
43
+ };
44
+
45
+ // Per-platform cooldown in hours — prevents over-posting even when CI fires every 4h
46
+ const PLATFORM_COOLDOWN_HOURS = {
47
+ tiktok: 4, // up to 6 videos/day — TikTok rewards frequency
48
+ instagram: 8, // up to 3 Reels/day
49
+ youtube: 12, // 1-2 Shorts/day
50
+ };
51
+
52
+ const CAPTIONS = {
53
+ tiktok: `Your AI agent deleted prod config because it "looked unused" 😬
54
+
55
+ ThumbGate v1.4.1 intercepts BEFORE the action runs. Checks it against lessons from past failures. Blocks it permanently.
56
+
57
+ 👎 feedback → lesson DB → prevention rule → physical gate
58
+
59
+ Not a prompt. A block.
60
+
61
+ npx thumbgate serve — free + open source
62
+ Try the live GPT first: https://chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate
63
+ github.com/IgorGanapolsky/ThumbGate
64
+
65
+ #ClaudeCode #AIAgents #DevTools #TechTok #Coding #SoftwareDev #AITools #Programming #DevTok`,
66
+
67
+ youtube: `ThumbGate v1.4.1: How to stop AI coding agents from repeating mistakes
68
+
69
+ Your agent force-pushed to main. Deleted prod config. Ran the wrong migration. You told it not to. Next session — same mistake.
70
+
71
+ ThumbGate solves this with pre-action gates: every 👎 becomes a lesson, every lesson becomes a gate, every gate is enforced via PreToolUse hooks.
72
+
73
+ v1.4.1: Thompson Sampling · LanceDB vector search · SQLite+FTS5 lesson DB
74
+
75
+ Live GPT demo: https://chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate
76
+ Free + open source: https://github.com/IgorGanapolsky/ThumbGate
77
+ npx thumbgate serve
78
+
79
+ #ClaudeCode #AIAgents #DevTools #Shorts`,
80
+
81
+ instagram: `AI agent deleted prod config because it "looked unused" 😬
82
+
83
+ ThumbGate v1.4.1: pre-action safety gates that physically block known-bad patterns before they run.
84
+
85
+ 👎 → lesson DB → prevention rule → blocked forever
86
+
87
+ Live GPT demo: chatgpt.com/g/g-69dcfd1cd5f881918ae31874631d6f08-thumbgate
88
+ Free + open source. Link in bio 👆
89
+
90
+ #AIAgents #ClaudeCode #DevTools #Coding #TechTok #SoftwareDev #AITools #MachineLearning #BuildInPublic`,
91
+ };
92
+
93
+ const YT_TITLE = 'ThumbGate v1.4.1: Stop AI Agents From Repeating Mistakes #shorts';
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Helpers
97
+ // ---------------------------------------------------------------------------
98
+
99
+ function parseArgs(argv) {
100
+ const opts = { dryRun: false, campaign: 'default', videoPath: null, platforms: null, template: 'auto' };
101
+ for (const arg of argv) {
102
+ if (arg === '--dry-run') opts.dryRun = true;
103
+ else if (arg.startsWith('--campaign=')) opts.campaign = arg.slice(11);
104
+ else if (arg.startsWith('--video=')) opts.videoPath = arg.slice(8);
105
+ else if (arg.startsWith('--platforms=')) opts.platforms = arg.slice(12).split(',');
106
+ else if (arg.startsWith('--template=')) opts.template = arg.slice(11);
107
+ }
108
+ return opts;
109
+ }
110
+
111
+ function requireKey() {
112
+ const k = process.env.ZERNIO_API_KEY;
113
+ if (!k) throw new Error('ZERNIO_API_KEY env var is required');
114
+ return k;
115
+ }
116
+
117
+ async function zernioUpload(apiKey, filePath) {
118
+ const out = execFileSync('curl', [
119
+ '-s',
120
+ '-X', 'POST',
121
+ `${ZERNIO_BASE}/media`,
122
+ '-H', `Authorization: Bearer ${apiKey}`,
123
+ '-F', `files=@${filePath}`,
124
+ ], { maxBuffer: 10 * 1024 * 1024 }).toString();
125
+
126
+ const data = JSON.parse(out);
127
+ const files = data.files || [];
128
+ if (!files.length) throw new Error(`Zernio upload failed: ${out}`);
129
+ return files[0].url;
130
+ }
131
+
132
+ async function zernioPost(apiKey, { platform, accountId, title, content, mediaUrl, mediaType = 'video' }) {
133
+ const body = {
134
+ content,
135
+ mediaItems: [{ url: mediaUrl, type: mediaType }],
136
+ platforms: [{ platform, accountId }],
137
+ publishNow: true,
138
+ };
139
+ if (title) body.title = title;
140
+
141
+ const out = execFileSync('curl', [
142
+ '-s',
143
+ '-X', 'POST',
144
+ `${ZERNIO_BASE}/posts`,
145
+ '-H', `Authorization: Bearer ${apiKey}`,
146
+ '-H', 'Content-Type: application/json',
147
+ '-d', JSON.stringify(body),
148
+ ], { maxBuffer: 5 * 1024 * 1024 }).toString();
149
+
150
+ return JSON.parse(out);
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Video generation
155
+ // ---------------------------------------------------------------------------
156
+
157
+ function generateVideo(outDir, template = 'auto', campaign = 'default') {
158
+ const slidesScript = path.join(__dirname, 'generate-slides.js');
159
+ const concatFile = path.join(outDir, 'concat.txt');
160
+ const videoOut = path.join(outDir, 'thumbgate-short.mp4');
161
+
162
+ console.log('[post-video] Generating slides...');
163
+ execFileSync(process.execPath, [
164
+ slidesScript,
165
+ `--out=${outDir}`,
166
+ `--template=${template}`,
167
+ `--campaign=${campaign}`,
168
+ ], { stdio: 'inherit' });
169
+
170
+ // Build ffmpeg concat file from manifest
171
+ const manifest = JSON.parse(fs.readFileSync(path.join(outDir, 'manifest.json'), 'utf8'));
172
+ const concatLines = manifest.slides.map(s => `file '${path.join(outDir, s.file)}'\nduration ${s.holdSeconds}`);
173
+ const lastSlide = manifest.slides[manifest.slides.length - 1];
174
+ concatLines.push(`file '${path.join(outDir, lastSlide.file)}'`);
175
+ fs.writeFileSync(concatFile, concatLines.join('\n'));
176
+
177
+ console.log('[post-video] Rendering video...');
178
+ execSync(
179
+ `ffmpeg -y -f concat -safe 0 -i "${concatFile}" \
180
+ -vf "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1" \
181
+ -c:v libx264 -r 30 -pix_fmt yuv420p -movflags +faststart \
182
+ "${videoOut}"`,
183
+ { stdio: 'pipe' }
184
+ );
185
+
186
+ const size = (fs.statSync(videoOut).size / 1024).toFixed(0);
187
+ console.log(`[post-video] Video ready: ${videoOut} (${size} KB, ${manifest.totalDuration}s)`);
188
+ return videoOut;
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // Main
193
+ // ---------------------------------------------------------------------------
194
+
195
+ function prepareVideo(opts) {
196
+ let videoPath = opts.videoPath;
197
+ let templateId = opts.template;
198
+ if (!videoPath) {
199
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'thumbgate-video-'));
200
+ videoPath = generateVideo(tmpDir, opts.template, opts.campaign);
201
+ // Read back the chosen template id from manifest
202
+ try {
203
+ const manifest = JSON.parse(fs.readFileSync(path.join(tmpDir, 'manifest.json'), 'utf8'));
204
+ templateId = String(manifest.templateId || opts.template);
205
+ } catch {}
206
+ }
207
+ return { videoPath, templateId };
208
+ }
209
+
210
+ function buildPlatformPlan(platform, baseHash) {
211
+ const caption = CAPTIONS[platform];
212
+ if (!caption) {
213
+ console.warn(`[post-video] No caption for platform: ${platform} — skipping`);
214
+ return null;
215
+ }
216
+
217
+ const contentHash = hashContent(`${baseHash}::${platform}`);
218
+ const cooldownHours = PLATFORM_COOLDOWN_HOURS[platform] || 4;
219
+ return { platform, caption, contentHash, cooldownDays: cooldownHours / 24 };
220
+ }
221
+
222
+ function duplicateResult(plan) {
223
+ const existing = isDuplicate(plan.platform, plan.contentHash, plan.cooldownDays);
224
+ if (!existing) return null;
225
+ console.log(`[post-video] SKIP ${plan.platform} — already posted (${existing.published_at}): ${existing.post_url}`);
226
+ return { platform: plan.platform, status: 'skipped', reason: 'duplicate', existing };
227
+ }
228
+
229
+ function recordPostOutcome({ plan, status, postUrl, error, campaign, mediaUrl, templateId, response }) {
230
+ if (status === 'published') {
231
+ console.log(`[post-video] ✓ ${plan.platform}: ${postUrl}`);
232
+ record({ type: 'video', platform: plan.platform, contentHash: plan.contentHash, postUrl, campaign,
233
+ tags: ['v1.4.1', 'short', campaign],
234
+ extra: { mediaUrl, templateId, zernioPostId: response.post?._id } });
235
+ return;
236
+ }
237
+
238
+ console.error(`[post-video] ✗ ${plan.platform}: ${error}`);
239
+ record({ type: 'video', platform: plan.platform, contentHash: plan.contentHash, status: 'failed', campaign,
240
+ extra: { error } });
241
+ }
242
+
243
+ async function processPlatform(plan, context) {
244
+ const duplicate = duplicateResult(plan);
245
+ if (duplicate) return duplicate;
246
+
247
+ if (context.dryRun) {
248
+ console.log(`[post-video] DRY-RUN ${plan.platform} — would post video`);
249
+ return { platform: plan.platform, status: 'dry-run' };
250
+ }
251
+
252
+ try {
253
+ if (!context.mediaUrl) {
254
+ console.log(`[post-video] Uploading video to Zernio...`);
255
+ context.mediaUrl = await zernioUpload(context.apiKey, context.videoPath);
256
+ console.log(`[post-video] Uploaded: ${context.mediaUrl}`);
257
+ }
258
+
259
+ console.log(`[post-video] Posting to ${plan.platform}...`);
260
+ const response = await zernioPost(context.apiKey, {
261
+ platform: plan.platform,
262
+ accountId: ACCOUNTS[plan.platform],
263
+ title: plan.platform === 'youtube' ? YT_TITLE : undefined,
264
+ content: plan.caption,
265
+ mediaUrl: context.mediaUrl,
266
+ });
267
+
268
+ const platformResult = response.post?.platforms?.[0] || {};
269
+ const status = platformResult.status || 'unknown';
270
+ const postUrl = platformResult.platformPostUrl || '';
271
+ const error = platformResult.errorMessage || response.error || '';
272
+ recordPostOutcome({ plan, status, postUrl, error, campaign: context.campaign,
273
+ mediaUrl: context.mediaUrl, templateId: context.templateId, response });
274
+ return { platform: plan.platform, status, postUrl, error };
275
+ } catch (err) {
276
+ console.error(`[post-video] ✗ ${plan.platform} error: ${err.message}`);
277
+ return { platform: plan.platform, status: 'error', error: err.message };
278
+ }
279
+ }
280
+
281
+ function statusIcon(status) {
282
+ if (status === 'published') return '✓';
283
+ if (['skipped', 'dry-run'].includes(status)) return '→';
284
+ return '✗';
285
+ }
286
+
287
+ function printSummary(results) {
288
+ console.log('\n[post-video] Summary:');
289
+ for (const r of results) {
290
+ const icon = statusIcon(r.status);
291
+ console.log(` ${icon} ${r.platform}: ${r.status}${r.postUrl ? ' — ' + r.postUrl : ''}${r.error ? ' — ' + r.error : ''}`);
292
+ }
293
+ }
294
+
295
+ async function main() {
296
+ const opts = parseArgs(process.argv.slice(2));
297
+ const apiKey = opts.dryRun ? null : requireKey();
298
+ const platforms = opts.platforms || ['tiktok', 'youtube', 'instagram'];
299
+ console.log(`[post-video] campaign=${opts.campaign} platforms=${platforms.join(',')} dryRun=${opts.dryRun}`);
300
+
301
+ const { videoPath, templateId } = prepareVideo(opts);
302
+ const baseHash = hashContent(`video::template-${templateId}::${opts.campaign}`);
303
+ const context = { apiKey, campaign: opts.campaign, dryRun: opts.dryRun, mediaUrl: null, templateId, videoPath };
304
+ const plans = platforms.map(platform => buildPlatformPlan(platform, baseHash)).filter(Boolean);
305
+ const results = [];
306
+
307
+ for (const plan of plans) {
308
+ results.push(await processPlatform(plan, context));
309
+ }
310
+
311
+ printSummary(results);
312
+
313
+ return results;
314
+ }
315
+
316
+ main().catch(err => { console.error(err.message); process.exit(1); });