thumbgate 1.39.1 โ†’ 1.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -0,0 +1,232 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+
8
+ const PROOF_WINDOW_DAYS_DEFAULT = 30;
9
+ const MAX_EXAMPLE_CHARS = 160;
10
+
11
+ const CATEGORY_RULES = [
12
+ {
13
+ id: 'force_push',
14
+ label: 'Force push to a protected branch',
15
+ gateIds: ['force-push', 'force_push', 'protected-branch-force-push'],
16
+ pattern: /\bgit\s+push\b[^\n]{0,80}(--force\b|-f\b)/i,
17
+ },
18
+ {
19
+ id: 'secret_in_command',
20
+ label: 'Secret material in a command',
21
+ gateIds: ['secret-exfiltration', 'secret-guard', 'secret_in_command', 'credential-leak'],
22
+ pattern: /(secret|api[_-]?key|token|password|credential|exfiltration)/i,
23
+ },
24
+ {
25
+ id: 'destructive_shell',
26
+ label: 'Destructive shell command',
27
+ gateIds: ['destructive-delete', 'destructive-shell', 'rm-rf', 'hard-floor'],
28
+ pattern: /\brm\s+-[a-z]*r[a-z]*f|\bdrop\s+(database|table)\b|\btruncate\b/i,
29
+ },
30
+ {
31
+ id: 'repeated_mistake',
32
+ label: 'Repeated mistake the agent already corrected',
33
+ gateIds: ['repeated-mistake', 'lesson-repeat', 'recurring-block'],
34
+ pattern: /(repeat(ed)? mistake|already corrected|recurring)/i,
35
+ },
36
+ {
37
+ id: 'privilege_escalation',
38
+ label: 'Privilege escalation or unsafe sudo',
39
+ gateIds: ['privilege-escalation', 'unsafe-sudo'],
40
+ pattern: /\bsudo\b|\bchmod\s+777\b/i,
41
+ },
42
+ ];
43
+
44
+ const NOISE_SOURCE_PATTERN = /(test|cron|diagnostic|fixture)/i;
45
+ const NOISE_PATH_PATTERN = /(\/(?:tmp|var\/folders)\/|thumbgate-test|test-fixtures?|node_modules)/i;
46
+
47
+ function resolveProofPaths(env = process.env) {
48
+ const homeDir = env.HOME || os.homedir() || '/tmp';
49
+ const thumbgateDir = env.THUMBGATE_HOME || path.join(homeDir, '.thumbgate');
50
+ return {
51
+ thumbgateDir,
52
+ auditTrailPath: env.THUMBGATE_AUDIT_TRAIL_PATH || path.join(thumbgateDir, 'audit-trail.jsonl'),
53
+ };
54
+ }
55
+
56
+ function readJsonl(filePath) {
57
+ if (!filePath || !fs.existsSync(filePath)) return [];
58
+ const out = [];
59
+ for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
60
+ const trimmed = line.trim();
61
+ if (!trimmed) continue;
62
+ try {
63
+ out.push(JSON.parse(trimmed));
64
+ } catch {
65
+ // skip malformed line
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function isBlockedDecision(record) {
72
+ const decision = String(record?.decision || '').toLowerCase();
73
+ const mode = String(record?.mode || '').toLowerCase();
74
+ return decision === 'deny' || decision === 'block' || mode === 'block';
75
+ }
76
+
77
+ function extractCommandText(record) {
78
+ const input = record?.toolInput;
79
+ if (!input || typeof input !== 'object') return '';
80
+ return String(input.command || input.cmd || input.input || input.file_path || input.path || '').trim();
81
+ }
82
+
83
+ function classifyCategory(record) {
84
+ const gateId = String(record?.gateId || '').toLowerCase();
85
+ const reason = String(record?.reason || record?.message || '');
86
+ const command = extractCommandText(record);
87
+ const haystack = `${gateId}\n${reason}\n${command}`;
88
+ for (const rule of CATEGORY_RULES) {
89
+ if (rule.gateIds.some((id) => gateId === id || gateId.includes(id))) return rule;
90
+ if (rule.pattern.test(haystack)) return rule;
91
+ }
92
+ return { id: 'other_risky_action', label: 'Other risky action stopped' };
93
+ }
94
+
95
+ function isNoiseRecord(record) {
96
+ const source = String(record?.source || '');
97
+ const sessionId = String(record?.sessionId || '');
98
+ const identity = `${source} ${sessionId}`;
99
+ const command = extractCommandText(record);
100
+ return NOISE_SOURCE_PATTERN.test(identity) || NOISE_PATH_PATTERN.test(command);
101
+ }
102
+
103
+ function anonymizeExample(text) {
104
+ let out = String(text || '').replace(/\s+/g, ' ').trim();
105
+ out = out
106
+ .replace(/\/(?:Users|home)\/[^\s'"]+/gi, '~/<redacted-path>')
107
+ .replace(/\b[\w.-]+\/[\w./-]+/g, '<redacted-path>')
108
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '<redacted-email>')
109
+ .replace(/\b(?:sk|rk|pk|ghp|gho|github_pat|xox[baprs]|AKIA|ASIA)[_-][A-Za-z0-9_\-]{8,}\b/g, '<redacted-secret>')
110
+ .replace(/\b[A-Z][A-Z0-9_]*(?:PAT|TOKEN|SECRET|PASSWORD|KEY)\b/g, '<redacted-secret>')
111
+ .replace(/\bwith-secrets\b/gi, '<redacted-secret>')
112
+ .replace(/\b(?:api[_-]?key|token|secret|password|passwd|credential|pat)\s*[:=]\s*\S+/gi, '<redacted-secret>');
113
+ if (out.length > MAX_EXAMPLE_CHARS) out = `${out.slice(0, MAX_EXAMPLE_CHARS - 1)}โ€ฆ`;
114
+ return out;
115
+ }
116
+
117
+ function buildProofReport(options = {}) {
118
+ const days = Math.max(1, Math.trunc(Number(options.days) || PROOF_WINDOW_DAYS_DEFAULT));
119
+ const nowMs = options.now ? new Date(options.now).getTime() : Date.now();
120
+ const windowStartMs = nowMs - days * 24 * 60 * 60 * 1000;
121
+ const paths = options.paths || resolveProofPaths(options.env);
122
+ const records = options.records || readJsonl(paths.auditTrailPath);
123
+
124
+ const realByCategory = new Map();
125
+ const excluded = { test: 0, cron: 0, diagnostic: 0, fixture: 0, other: 0 };
126
+ let realBlocked = 0;
127
+ let excludedTotal = 0;
128
+
129
+ for (const record of records) {
130
+ if (!isBlockedDecision(record)) continue;
131
+ const ts = new Date(record.timestamp || 0).getTime();
132
+ if (!Number.isFinite(ts) || ts < windowStartMs || ts > nowMs) continue;
133
+
134
+ if (isNoiseRecord(record)) {
135
+ excludedTotal += 1;
136
+ const haystack = `${record.source || ''} ${record.sessionId || ''} ${record.reason || ''} ${extractCommandText(record)}`.toLowerCase();
137
+ if (haystack.includes('cron')) excluded.cron += 1;
138
+ else if (haystack.includes('diagnostic')) excluded.diagnostic += 1;
139
+ else if (haystack.includes('fixture')) excluded.fixture += 1;
140
+ else if (haystack.includes('test')) excluded.test += 1;
141
+ else excluded.other += 1;
142
+ continue;
143
+ }
144
+
145
+ realBlocked += 1;
146
+ const category = classifyCategory(record);
147
+ const bucket = realByCategory.get(category.id) || {
148
+ id: category.id,
149
+ label: category.label,
150
+ count: 0,
151
+ example: '',
152
+ };
153
+ bucket.count += 1;
154
+ if (!bucket.example) {
155
+ const exampleSource = extractCommandText(record) || String(record.message || record.reason || '');
156
+ bucket.example = anonymizeExample(exampleSource);
157
+ }
158
+ realByCategory.set(category.id, bucket);
159
+ }
160
+
161
+ const categories = [...realByCategory.values()].sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
162
+
163
+ return {
164
+ windowDays: days,
165
+ generatedAt: new Date(nowMs).toISOString(),
166
+ source: 'founder-local-audit-trail',
167
+ realAgentToolCallsBlocked: realBlocked,
168
+ excludedNoise: {
169
+ total: excludedTotal,
170
+ ...excluded,
171
+ },
172
+ categories,
173
+ };
174
+ }
175
+
176
+ function formatProofText(report) {
177
+ const lines = [
178
+ `ThumbGate proof โ€” last ${report.windowDays} days (founder local use, not a customer)`,
179
+ `Real agent tool calls blocked: ${report.realAgentToolCallsBlocked}`,
180
+ `Excluded noise (test/cron/diagnostic/fixture): ${report.excludedNoise.total}`,
181
+ '',
182
+ 'Top categories:',
183
+ ];
184
+ const top = report.categories.slice(0, 5);
185
+ if (!top.length) {
186
+ lines.push(' (none in window)');
187
+ } else {
188
+ for (const cat of top) {
189
+ lines.push(` - ${cat.label}: ${cat.count}`);
190
+ if (cat.example) lines.push(` example: ${cat.example}`);
191
+ }
192
+ }
193
+ return lines.join('\n');
194
+ }
195
+
196
+ function runProofCli(argv = process.argv.slice(3), options = {}) {
197
+ const args = {};
198
+ for (let i = 0; i < argv.length; i += 1) {
199
+ const arg = argv[i];
200
+ if (!arg.startsWith('--')) continue;
201
+ const [key, ...rest] = arg.slice(2).split('=');
202
+ if (rest.length) args[key] = rest.join('=');
203
+ else if (argv[i + 1] && !argv[i + 1].startsWith('--')) {
204
+ args[key] = argv[i + 1];
205
+ i += 1;
206
+ } else args[key] = true;
207
+ }
208
+ const report = buildProofReport({
209
+ days: args.days,
210
+ env: options.env,
211
+ paths: options.paths,
212
+ records: options.records,
213
+ now: options.now,
214
+ });
215
+ const out = args.json ? JSON.stringify(report, null, 2) : formatProofText(report);
216
+ if (!options.silent) process.stdout.write(`${out}\n`);
217
+ return report;
218
+ }
219
+
220
+ module.exports = {
221
+ CATEGORY_RULES,
222
+ anonymizeExample,
223
+ buildProofReport,
224
+ formatProofText,
225
+ isNoiseRecord,
226
+ resolveProofPaths,
227
+ runProofCli,
228
+ };
229
+
230
+ if (require.main === module) {
231
+ runProofCli(process.argv.slice(2));
232
+ }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { normalizeCommandValue } = require('./harness-tool-names');
4
5
  const DEFAULT_SOFT_TOKEN_LIMIT = 8000;
5
6
  const DEFAULT_MAX_PARALLEL_BRANCHES = 4;
6
7
 
@@ -215,13 +216,20 @@ function collectAffectedFiles(toolInput = {}, fallback = {}) {
215
216
  return uniqueStrings(files);
216
217
  }
217
218
 
219
+ function coerceCommandCandidate(candidate) {
220
+ if (Array.isArray(candidate)) {
221
+ return normalizeCommandValue(candidate);
222
+ }
223
+ return candidate;
224
+ }
225
+
218
226
  function inferCommand(toolName, toolInput = {}, fallback = {}) {
219
227
  return firstString(
220
- toolInput.command,
221
- toolInput.cmd,
222
- toolInput.shell,
223
- fallback.command,
224
- fallback.cmd
228
+ coerceCommandCandidate(toolInput.command),
229
+ coerceCommandCandidate(toolInput.cmd),
230
+ coerceCommandCandidate(toolInput.shell),
231
+ coerceCommandCandidate(fallback.command),
232
+ coerceCommandCandidate(fallback.cmd)
225
233
  );
226
234
  }
227
235
 
@@ -232,7 +240,7 @@ function inferActionType(toolName, toolInput = {}, fallback = {}) {
232
240
  if (fallback.method === 'prompts/get') return 'prompt.get';
233
241
  const normalizedTool = String(toolName || '').trim();
234
242
  const lowerTool = normalizedTool.toLowerCase();
235
- if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command'])) {
243
+ if (normalizedTool === 'Bash' || containsAny(lowerTool, ['bash', 'shell', 'terminal', 'exec', 'run_command', 'powershell', 'pwsh'])) {
236
244
  return 'shell.exec';
237
245
  }
238
246
  if (EDIT_TOOL_NAMES.has(normalizedTool) || containsAny(lowerTool, ['edit', 'write', 'patch', 'file'])) {
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ const { getOperationalBillingSummary } = require('./operational-summary');
3
+
4
+ function getPulseSnapshot(summary, now = new Date()) {
5
+ const funnel = summary.funnel || {};
6
+ const revenue = summary.revenue || {};
7
+ const signups = summary.signups || {};
8
+ const trafficMetrics = summary.trafficMetrics || {};
9
+ const pipeline = summary.pipeline || {};
10
+ const operatorGeneratedAcquisition = summary.operatorGeneratedAcquisition || {};
11
+ const dataQuality = summary.dataQuality || {};
12
+ const leadCount = signups.uniqueLeads || 0;
13
+ const activeCount = funnel.stageCounts ? funnel.stageCounts.activation || 0 : 0;
14
+ const sprintLeads = pipeline.workflowSprintLeads ? pipeline.workflowSprintLeads.total || 0 : 0;
15
+ const qualifiedSprintLeads = pipeline.qualifiedWorkflowSprintLeads ? pipeline.qualifiedWorkflowSprintLeads.total || 0 : 0;
16
+ const paidProviderEvents = revenue.paidProviderEvents || 0;
17
+ const paidOrders = revenue.paidOrders || 0;
18
+ const bookedRevenueCents = revenue.bookedRevenueCents || 0;
19
+ const conversionRate = leadCount > 0 ? ((paidOrders / leadCount) * 100).toFixed(2) : '0.00';
20
+ const health = bookedRevenueCents > 0
21
+ ? '๐ŸŸข BOOKED REVENUE ACTIVE'
22
+ : ((leadCount > 0 || sprintLeads > 0) ? '๐ŸŸก PIPELINE ACTIVE' : '๐Ÿ”ด BLIND / COLD');
23
+
24
+ let eta = 'N/A';
25
+ if (bookedRevenueCents === 0 && (leadCount > 0 || sprintLeads > 0)) {
26
+ const hoursRemaining = 4;
27
+ const etaDate = new Date(now.getTime() + hoursRemaining * 60 * 60 * 1000);
28
+ eta = `${etaDate.toLocaleTimeString()} (Decision Window)`;
29
+ } else if (bookedRevenueCents > 0) {
30
+ eta = 'SUCCESS';
31
+ }
32
+
33
+ return {
34
+ leadCount,
35
+ activeCount,
36
+ visitors: trafficMetrics.visitors || 0,
37
+ ctaClicks: trafficMetrics.ctaClicks || 0,
38
+ checkoutStarts: trafficMetrics.checkoutStarts || 0,
39
+ sprintLeads,
40
+ qualifiedSprintLeads,
41
+ paidProviderEvents,
42
+ paidOrders,
43
+ bookedRevenueCents,
44
+ conversionRate,
45
+ health,
46
+ eta,
47
+ operatorGeneratedAcquisitionEvents: operatorGeneratedAcquisition.totalEvents || 0,
48
+ operatorGeneratedUniqueLeads: operatorGeneratedAcquisition.uniqueLeads || 0,
49
+ unreconciledPaidEvents: dataQuality.unreconciledPaidEvents || 0,
50
+ topAcquisitionChannels: Object.entries(funnel.eventCounts || {})
51
+ .filter(([key]) => key.startsWith('acquisition:'))
52
+ .sort((a, b) => b[1] - a[1])
53
+ .slice(0, 3),
54
+ };
55
+ }
56
+
57
+ async function showPulse() {
58
+ const now = new Date();
59
+ const { source, summary, fallbackReason } = await getOperationalBillingSummary();
60
+ const snapshot = getPulseSnapshot(summary, now);
61
+ console.log('๐Ÿ“ก [MISSION CONTROL] MISSION PULSE โ€” ' + now.toLocaleTimeString());
62
+ console.log('โ”€'.repeat(60));
63
+ console.log(`๐Ÿ›ฐ๏ธ SOURCE: ${source.toUpperCase()}${fallbackReason ? ` (${fallbackReason})` : ''}`);
64
+ console.log(`๐Ÿš€ TRAFFIC: ${snapshot.visitors} Visitors | ${snapshot.ctaClicks} CTA Clicks | ${snapshot.checkoutStarts} Checkout Starts | ${snapshot.leadCount} Unique Leads`);
65
+ console.log(`๐Ÿงช PIPELINE: ${snapshot.sprintLeads} Sprint Leads | ${snapshot.qualifiedSprintLeads} Qualified Sprint Leads | ${snapshot.activeCount} Activations`);
66
+ console.log(`๐Ÿค– OPERATOR ACQ: ${snapshot.operatorGeneratedAcquisitionEvents} Events | ${snapshot.operatorGeneratedUniqueLeads} Unique Leads`);
67
+ console.log(`๐Ÿ’ณ REVENUE FLOW: ${snapshot.paidProviderEvents} Paid Provider Events | ${snapshot.paidOrders} Paid Orders`);
68
+ console.log(`๐Ÿ’ต BOOKED REVENUE: $${(snapshot.bookedRevenueCents / 100).toFixed(2)}`);
69
+ console.log(`๐Ÿ“ˆ HEALTH: ${snapshot.health} (${snapshot.conversionRate}% lead-to-paid conversion)`);
70
+ console.log(`โฑ๏ธ FIRST DOLLAR ETA: ${snapshot.eta}`);
71
+ console.log(`๐Ÿงน DATA QUALITY: ${snapshot.unreconciledPaidEvents} unreconciled paid event(s)`);
72
+ console.log('โ”€'.repeat(60));
73
+ console.log('๐Ÿ“Š TOP ACQUISITION CHANNELS:');
74
+ snapshot.topAcquisitionChannels.forEach(([key, count]) => {
75
+ const name = key.split(':')[1];
76
+ console.log(` - ${name.padEnd(25)} : ${count} events`);
77
+ });
78
+ }
79
+ if (require.main === module) showPulse().catch(console.error);
80
+ module.exports = { showPulse, getPulseSnapshot };
@@ -218,6 +218,44 @@ function getUsage(action, authContext) {
218
218
  return { count: lifetimeCount, limit: lifetimeLimit, remaining: Math.max(0, lifetimeLimit - lifetimeCount) };
219
219
  }
220
220
 
221
+ const PRO_REPEAT_URL = 'https://thumbgate.ai/pro';
222
+ const RULE_SECTION_SKIP = new Set([
223
+ 'High-Priority Contracts',
224
+ 'Rubric Failure Dimensions',
225
+ 'Root Cause Categories',
226
+ 'Repeated Failure Constraints',
227
+ ]);
228
+
229
+ function scrubRepeatText(value) {
230
+ return String(value || '')
231
+ .replace(/\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b/g, '[redacted]')
232
+ .replace(/\b(?:sk|ghp|github_pat|AKIA)[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
233
+ .replace(/\/Users\/[^\s]+/g, '[path]')
234
+ .replace(/\s+/g, ' ')
235
+ .trim()
236
+ .slice(0, 140);
237
+ }
238
+
239
+ function proWouldHaveBlockedSentence(mistake) {
240
+ const clean = scrubRepeatText(mistake);
241
+ if (!clean) return null;
242
+ return `Pro would have blocked this repeat: ${clean}. ${PRO_REPEAT_URL}`;
243
+ }
244
+
245
+ function droppedRepeatFromRulesMarkdown(markdown, maxActive = FREE_TIER_MAX_GATES) {
246
+ const mistakes = [];
247
+ for (const section of String(markdown || '').split(/\n## /)) {
248
+ const title = section.replace(/^## /, '').split('\n')[0].trim();
249
+ if (!title || RULE_SECTION_SKIP.has(title)) continue;
250
+ if (!/^- Rule: /m.test(section) && !/^- Latest mistake: /m.test(section)) continue;
251
+ const latest = (section.match(/^- Latest mistake: (.+)$/m) || [])[1];
252
+ const rule = (section.match(/^- Rule: (.+)$/m) || [])[1];
253
+ const text = scrubRepeatText(latest || rule || title);
254
+ if (text) mistakes.push(text);
255
+ }
256
+ return mistakes.length > maxActive ? mistakes[maxActive] : null;
257
+ }
258
+
221
259
  module.exports = {
222
260
  checkLimit,
223
261
  getUsage,
@@ -235,4 +273,7 @@ module.exports = {
235
273
  UPGRADE_MESSAGE,
236
274
  PAYWALL_MESSAGES,
237
275
  USAGE_FILE,
276
+ proWouldHaveBlockedSentence,
277
+ droppedRepeatFromRulesMarkdown,
278
+ scrubRepeatText,
238
279
  };