thumbgate 1.39.0 → 1.40.1

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 (180) hide show
  1. package/.agents/skills/craft-playbook-gate/SKILL.md +51 -0
  2. package/.agents/skills/qwenwork-policy-group-honesty-not-clone/SKILL.md +36 -0
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.well-known/llms.txt +2 -2
  5. package/.well-known/mcp/server-card.json +1 -1
  6. package/README.md +11 -5
  7. package/adapters/claude/.mcp.json +6 -2
  8. package/adapters/codex/config.toml +5 -0
  9. package/adapters/forge/forge.yaml +4 -4
  10. package/adapters/future-agi/.mcp.json +1 -1
  11. package/adapters/future-agi/config.toml +1 -1
  12. package/adapters/future-agi/opencode.json +1 -1
  13. package/adapters/herdr/herdr-plugin.toml +2 -2
  14. package/adapters/mcp/server-stdio.js +104 -7
  15. package/adapters/opencode/opencode.json +1 -1
  16. package/adapters/strands/strands-middleware.js +31 -4
  17. package/bin/cli.js +191 -54
  18. package/config/brand-standards.json +131 -0
  19. package/config/gates/default.json +18 -1
  20. package/config/github-about.json +1 -1
  21. package/config/mcp-allowlists.json +16 -3
  22. package/config/merge-quality-checks.json +3 -1
  23. package/config/post-deploy-marketing-pages.json +4 -4
  24. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  25. package/hooks/hooks.json +24 -0
  26. package/openapi/openapi.yaml +7 -3
  27. package/package.json +87 -33
  28. package/public/about.html +2 -2
  29. package/public/admin.html +771 -0
  30. package/public/agent-manager.html +3 -3
  31. package/public/agents-cost-savings.html +1 -1
  32. package/public/ai-malpractice-prevention.html +12 -12
  33. package/public/architecture.html +0 -1
  34. package/public/assets/diagrams/decision.svg +3 -3
  35. package/public/assets/diagrams/hero-thumbs.svg +2 -4
  36. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  37. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  38. package/public/blog/git-at-agent-scale.html +2 -2
  39. package/public/blog/inside-your-boundary.html +1 -1
  40. package/public/blog/process-over-outcome-gates.html +1 -1
  41. package/public/case-studies.html +5 -6
  42. package/public/codex-enterprise.html +1 -1
  43. package/public/codex-plugin.html +1 -1
  44. package/public/dashboard.html +775 -483
  45. package/public/diagnostic.html +15 -10
  46. package/public/enterprise-governance.html +26 -174
  47. package/public/eval-scorecard.html +3 -4
  48. package/public/eval-scorecard.json +2 -2
  49. package/public/evaluations.html +0 -1
  50. package/public/founders.html +3 -3
  51. package/public/gaming-playbook.html +4 -4
  52. package/public/guide.html +3 -5
  53. package/public/index.html +302 -97
  54. package/public/install.html +16 -10
  55. package/public/js/buyer-intent.js +49 -8
  56. package/public/lessons.html +246 -83
  57. package/public/numbers.html +32 -33
  58. package/public/operator-framework.html +44 -72
  59. package/public/peter.html +3 -3
  60. package/public/platform-partners.html +1 -1
  61. package/public/pricing.html +163 -66
  62. package/public/pro.html +3 -1
  63. package/public/project-switcher.js +76 -0
  64. package/public/whitepaper.html +1 -2
  65. package/scripts/action-receipts.js +393 -0
  66. package/scripts/activation-quickstart.js +15 -3
  67. package/scripts/activation-tracker.js +280 -3
  68. package/scripts/agent-action-inventory.js +235 -143
  69. package/scripts/agent-operations-planner.js +1 -1
  70. package/scripts/agent-readiness.js +36 -6
  71. package/scripts/agentic-prompt-pipelines.js +901 -0
  72. package/scripts/analytics-window.js +7 -1
  73. package/scripts/async-job-runner.js +66 -11
  74. package/scripts/audit-trail.js +37 -24
  75. package/scripts/auto-promote-gates.js +37 -27
  76. package/scripts/auto-wire-hooks.js +64 -25
  77. package/scripts/backfill-lesson-scopes.js +122 -0
  78. package/scripts/billing.js +889 -132
  79. package/scripts/bot-detection.js +112 -0
  80. package/scripts/brand-standards-gate.js +571 -0
  81. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  82. package/scripts/cli-demo.js +5 -27
  83. package/scripts/cli-schema.js +25 -1
  84. package/scripts/commercial-offer.js +2 -2
  85. package/scripts/contextfs.js +9 -3
  86. package/scripts/craft-playbook-gate.js +550 -0
  87. package/scripts/cross-encoder-reranker.js +4 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +574 -167
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/docker-sandbox-planner.js +3 -3
  92. package/scripts/export-dpo-pairs.js +12 -7
  93. package/scripts/failure-diagnostics.js +11 -0
  94. package/scripts/feedback-aggregate.js +4 -0
  95. package/scripts/feedback-attribution.js +6 -4
  96. package/scripts/feedback-history-distiller.js +18 -6
  97. package/scripts/feedback-loop.js +255 -89
  98. package/scripts/feedback-paths.js +8 -1
  99. package/scripts/feedback-sanitizer.js +5 -0
  100. package/scripts/feedback-scope.js +106 -0
  101. package/scripts/feedback-session.js +8 -2
  102. package/scripts/filesystem-search.js +13 -8
  103. package/scripts/financial-control-plane.js +707 -45
  104. package/scripts/gate-stats.js +38 -5
  105. package/scripts/gates-engine.js +1326 -240
  106. package/scripts/generate-eval-scorecard.js +0 -1
  107. package/scripts/gitlab-sdlc-prompts.js +397 -0
  108. package/scripts/harness-tool-names.js +31 -5
  109. package/scripts/hook-runtime.js +10 -0
  110. package/scripts/hybrid-feedback-context.js +7 -2
  111. package/scripts/intervention-policy.js +2 -1
  112. package/scripts/lesson-canonical.js +2 -2
  113. package/scripts/lesson-db.js +55 -14
  114. package/scripts/lesson-graph.js +2 -1
  115. package/scripts/lesson-retrieval.js +95 -9
  116. package/scripts/lesson-search.js +86 -22
  117. package/scripts/lesson-synthesis.js +21 -5
  118. package/scripts/mabl-failure-honesty.js +273 -0
  119. package/scripts/mailer/index.js +17 -1
  120. package/scripts/mailer/resend-mailer.js +213 -179
  121. package/scripts/migrate-project-scope.js +209 -0
  122. package/scripts/model-distress-detector.js +3 -3
  123. package/scripts/operational-integrity.js +436 -3
  124. package/scripts/override-audit.js +2 -0
  125. package/scripts/owner-admin.js +338 -0
  126. package/scripts/pr-manager.js +194 -1
  127. package/scripts/product-feedback.js +35 -0
  128. package/scripts/progressive-signoff.js +260 -0
  129. package/scripts/project-catalog.js +243 -0
  130. package/scripts/project-dashboard.js +61 -0
  131. package/scripts/project-evidence.js +172 -0
  132. package/scripts/project-identity.js +182 -0
  133. package/scripts/project-scope.js +381 -0
  134. package/scripts/prompt-eval.js +1 -1
  135. package/scripts/prompt-guard.js +446 -52
  136. package/scripts/proof-report.js +232 -0
  137. package/scripts/provider-action-normalizer.js +14 -6
  138. package/scripts/qwenwork-policy-group.js +413 -0
  139. package/scripts/rate-limiter.js +41 -0
  140. package/scripts/secret-redaction.js +171 -25
  141. package/scripts/secret-scanner.js +101 -42
  142. package/scripts/self-protection.js +2 -2
  143. package/scripts/seo-gsd.js +14 -14
  144. package/scripts/session-context-dedupe.js +66 -0
  145. package/scripts/settings-hierarchy.js +4 -2
  146. package/scripts/statusline-meta.js +34 -23
  147. package/scripts/tailscale-october-access.js +416 -0
  148. package/scripts/task-outcomes.js +58 -2
  149. package/scripts/telemetry-analytics.js +260 -16
  150. package/scripts/thumbgate-search.js +23 -9
  151. package/scripts/tool-kpi-tracker.js +5 -2
  152. package/scripts/tool-registry.js +42 -1
  153. package/scripts/triage-savings-calculator.js +1 -1
  154. package/scripts/vector-store.js +4 -1
  155. package/scripts/verified-lessons.js +270 -0
  156. package/scripts/verify-marketing-pages-deployed.js +2 -2
  157. package/scripts/workflow-sentinel.js +29 -10
  158. package/server.json +2 -2
  159. package/src/api/server.js +2478 -470
  160. package/src/feedback.js +21 -0
  161. package/src/hermes-sync-plane.js +2 -1
  162. package/src/index.js +2 -0
  163. package/src/lesson-search.js +9 -0
  164. package/src/mckinsey-top-company-ai-coding.js +493 -0
  165. package/src/mcp/email-triage-server/index.js +973 -0
  166. package/src/mcp/email-triage-server/package.json +12 -0
  167. package/src/mcp/server.js +3 -0
  168. package/src/mcp-writeguard.js +772 -11
  169. package/src/openshell-lovable-engine.js +1475 -0
  170. package/src/task-outcome.js +3 -0
  171. package/config/evals/agent-safety-eval.json +0 -447
  172. package/config/evals/retrieval-ranking-golden.json +0 -522
  173. package/config/progressive/01-wire-only.json +0 -11
  174. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  175. package/config/progressive/03-one-lesson.json +0 -10
  176. package/config/progressive/04-warn-fires.json +0 -11
  177. package/config/progressive/05-strict-optional.json +0 -11
  178. package/config/progressive/README.md +0 -15
  179. package/public/assets/diagrams/agent-integration.png +0 -0
  180. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
@@ -0,0 +1,571 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const DEFAULT_BRAND_STANDARDS_PATH = path.join(__dirname, '..', 'config', 'brand-standards.json');
8
+ const CREATIVE_EXT_RE = /\.(?:psd|psb|ai|indd|prproj|aep)$/i;
9
+ const CREATIVE_BACKUP_STEM_RE = /(?:[_.-](?:copy|backup|bak|draft|working)|\.copy)\.[a-z0-9]+$/i;
10
+ // [ \t]* (not \s*) after a line start keeps this linear on long runs of newlines (CodeQL js/polynomial-redos).
11
+ const LINE_LABEL_RE = /^[ \t]*(?:Problem|Solution|Fix|Note|TL;DR|Hook|CTA|Why it matters)[ \t]*:/m;
12
+ const PRICE_TOKEN_RE = /\$\d[\d,]*(?:\.\d{1,2})?(?:\s*\/\s*(?:mo|month|yr|year|seat))?/gi;
13
+ const URL_TOKEN_RE = /https?:\/\/[^\s<>()"'\]]+/gi;
14
+
15
+ const OUTBOUND_POST_CONTEXT_KEYWORDS = [
16
+ 'post', 'linkedin', 'bluesky', 'tweet', 'twitter', 'threads', 'reddit',
17
+ 'newsletter', 'substack', 'medium', 'social', 'copy', 'listing', 'pitch',
18
+ 'brand', 'voice', 'jargon', 'refund', 'guarantee', 'price', 'headline',
19
+ ];
20
+
21
+ function loadBrandStandards(configPath = DEFAULT_BRAND_STANDARDS_PATH) {
22
+ const raw = fs.readFileSync(configPath, 'utf8');
23
+ return JSON.parse(raw);
24
+ }
25
+
26
+ function detectBrandFromText(text, explicitBrand) {
27
+ if (explicitBrand) {
28
+ const norm = String(explicitBrand).trim().toLowerCase();
29
+ if (norm === 'mac-yolo' || norm === 'macyolo') return 'mac-yolo';
30
+ if (norm === 'thumbgate') return 'thumbgate';
31
+ }
32
+ const lower = String(text || '').toLowerCase();
33
+ const mentionsMacYolo = lower.includes('mac yolo') || lower.includes('macyolosafeguards');
34
+ const mentionsThumbGate = lower.includes('thumbgate');
35
+ if (mentionsMacYolo && !mentionsThumbGate) return 'mac-yolo';
36
+ return 'thumbgate';
37
+ }
38
+
39
+ function extractDistinctPrices(text) {
40
+ const seen = [];
41
+ const source = String(text || '');
42
+ PRICE_TOKEN_RE.lastIndex = 0;
43
+ let m = PRICE_TOKEN_RE.exec(source);
44
+ while (m !== null) {
45
+ const raw = m[0].replace(/\s+/g, '');
46
+ // Ignore "<$50 card limit" threshold comparisons only? No — "$50" in "<$50" is a price figure,
47
+ // but to match exact listed prices cleanly, ignore tokens immediately preceded by "<" or ">".
48
+ const prevChar = m.index > 0 ? source[m.index - 1] : '';
49
+ if (prevChar !== '<' && prevChar !== '>' && !seen.includes(raw)) {
50
+ seen.push(raw);
51
+ }
52
+ m = PRICE_TOKEN_RE.exec(source);
53
+ }
54
+ return seen;
55
+ }
56
+
57
+ function extractUrls(text) {
58
+ const urls = [];
59
+ const source = String(text || '');
60
+ URL_TOKEN_RE.lastIndex = 0;
61
+ let m = URL_TOKEN_RE.exec(source);
62
+ while (m !== null) {
63
+ const cleaned = m[0].replace(/[.,;:!?)]+$/, '');
64
+ if (!urls.includes(cleaned)) urls.push(cleaned);
65
+ m = URL_TOKEN_RE.exec(source);
66
+ }
67
+ return urls;
68
+ }
69
+
70
+ function findCaseInsensitivePhrase(haystack, needle) {
71
+ const lowerHay = haystack.toLowerCase();
72
+ const lowerNeedle = String(needle || '').toLowerCase().trim();
73
+ if (!lowerNeedle) return null;
74
+ const idx = lowerHay.indexOf(lowerNeedle);
75
+ if (idx === -1) return null;
76
+ // Require word boundaries on alphanumeric edges so short tokens never substring-collide
77
+ const startAlpha = /[a-z0-9]/i.test(lowerNeedle[0]);
78
+ const endAlpha = /[a-z0-9]/i.test(lowerNeedle[lowerNeedle.length - 1]);
79
+ if (startAlpha && idx > 0 && /[a-z0-9]/i.test(lowerHay[idx - 1])) return null;
80
+ const afterIdx = idx + lowerNeedle.length;
81
+ if (endAlpha && afterIdx < lowerHay.length && /[a-z0-9]/i.test(lowerHay[afterIdx])) return null;
82
+ return haystack.slice(idx, afterIdx);
83
+ }
84
+
85
+ /**
86
+ * Generates a plain-words rewrite following post-like-igor rules:
87
+ * - Plain words, real full sentences, proper capitalization and periods
88
+ * - Strips off-brand real-estate / cross-product / refund-guarantee / stacked-jargon sentences
89
+ * - Strips line-start labels ("Problem:", "Fix:", etc.) and em-dashes
90
+ * - Keeps at most ONE verified price and ONE canonical product link
91
+ */
92
+ function rewriteInIgorVoice(rawText, options = {}) {
93
+ const config = options.config || loadBrandStandards(options.configPath);
94
+ const brandKey = detectBrandFromText(rawText, options.brand);
95
+ const brandCfg = (config.brands && config.brands[brandKey]) || config.brands.thumbgate;
96
+
97
+ const bannedPhrases = [];
98
+ for (const rule of config.rules || []) {
99
+ for (const p of rule.phrases || []) bannedPhrases.push(p);
100
+ }
101
+ for (const cp of brandCfg.crossProductForbidden || []) {
102
+ bannedPhrases.push(cp);
103
+ }
104
+
105
+ // Split into candidate sentences while protecting decimal numbers (e.g. 0.5ms, 197.552, $9.99)
106
+ const normalized = String(rawText || '')
107
+ .replace(/^[ \t]*(?:Problem|Solution|Fix|Note|TL;DR|Hook|CTA|Why it matters)[ \t]*:[ \t]*/gim, '')
108
+ .replace(/[\u2014\u2013]/g, ', ')
109
+ .replace(/\r\n/g, '\n');
110
+
111
+ const rawChunks = normalized
112
+ .split(/\n+/)
113
+ .flatMap((para) => para.split(/(?<=[.!?])\s+(?=[A-Z0-9"$])/))
114
+ .map((s) => s.trim())
115
+ .filter(Boolean);
116
+
117
+ const keptSentences = [];
118
+ let keptPrice = null;
119
+ let keptUrl = null;
120
+
121
+ for (let chunk of rawChunks) {
122
+ // Drop any sentence containing real-estate, cross-product, unverified guarantee, or stacked-jargon phrases
123
+ const hitsBanned = bannedPhrases.some((phrase) => findCaseInsensitivePhrase(chunk, phrase) !== null);
124
+ if (hitsBanned) continue;
125
+
126
+ // Enforce at most 1 URL
127
+ const chunkUrls = extractUrls(chunk);
128
+ if (chunkUrls.length > 0) {
129
+ const allowedUrl = chunkUrls.find((u) =>
130
+ (brandCfg.allowedDomains || []).some((dom) => u.toLowerCase().includes(dom.toLowerCase())),
131
+ );
132
+ if (!allowedUrl) continue;
133
+ if (keptUrl && keptUrl !== allowedUrl) {
134
+ chunk = chunk.replace(URL_TOKEN_RE, '').replace(/\s{2,}/g, ' ').trim();
135
+ } else {
136
+ keptUrl = allowedUrl;
137
+ for (const extraUrl of chunkUrls) {
138
+ if (extraUrl !== allowedUrl) {
139
+ chunk = chunk.split(extraUrl).join('').replace(/\s{2,}/g, ' ').trim();
140
+ }
141
+ }
142
+ }
143
+ }
144
+
145
+ // Enforce at most 1 verified price across the entire post
146
+ const chunkPrices = extractDistinctPrices(chunk);
147
+ if (chunkPrices.length > 0) {
148
+ const firstVerified = chunkPrices.find((p) =>
149
+ (brandCfg.verifiedPrices || []).some((vp) => vp.toLowerCase() === p.toLowerCase()),
150
+ );
151
+ if (!firstVerified || chunkPrices.length > 1 || (keptPrice && keptPrice !== firstVerified)) {
152
+ continue;
153
+ }
154
+ keptPrice = firstVerified;
155
+ }
156
+
157
+ // Clean leftover punctuation/list prefixes and ensure proper capitalization + full stop
158
+ chunk = chunk.replace(/^[-*•\d.)]+\s*/, '').replace(/\s{2,}/g, ' ').trim();
159
+ if (!chunk) continue;
160
+ chunk = chunk[0].toUpperCase() + chunk.slice(1);
161
+ if (!/[.!?]$/.test(chunk)) chunk += '.';
162
+ keptSentences.push(chunk);
163
+ }
164
+
165
+ if (keptSentences.length === 0) {
166
+ if (brandKey === 'mac-yolo') {
167
+ return `Mac YOLO Safeguards stops runaway local agent loops and swap exhaustion on macOS before your Mac freezes. See ${brandCfg.canonicalOrigin}.`;
168
+ }
169
+ return `ThumbGate checks shell, git, file, and MCP tool calls locally before they run, and turns thumbs-down feedback into local rules. Install free with npx thumbgate init at ${brandCfg.canonicalOrigin}.`;
170
+ }
171
+
172
+ const joined = keptSentences.slice(0, 3).join(' ');
173
+ if (!extractUrls(joined).length && brandCfg.canonicalOrigin) {
174
+ return `${joined} Learn more at ${brandCfg.canonicalOrigin}.`;
175
+ }
176
+ return joined;
177
+ }
178
+
179
+ /**
180
+ * Evaluates outbound text against `config/brand-standards.json` plus voice rules
181
+ * (stacked jargon, line-start labels, >1 price, unverified prices/claims, cross-product conflation).
182
+ */
183
+ function evaluateBrandStandards(text, options = {}) {
184
+ const content = String(text || '').trim();
185
+ const config = options.config || loadBrandStandards(options.configPath);
186
+ const brand = detectBrandFromText(content, options.brand);
187
+ const brandCfg = (config.brands && config.brands[brand]) || config.brands.thumbgate;
188
+ const violations = [];
189
+
190
+ if (!content) {
191
+ return { allowed: true, brand, violations: [], rewriteSuggestion: null, message: null };
192
+ }
193
+
194
+ // 1. Declarative phrase rules from config/brand-standards.json
195
+ for (const rule of config.rules || []) {
196
+ for (const phrase of rule.phrases || []) {
197
+ const matched = findCaseInsensitivePhrase(content, phrase);
198
+ if (matched) {
199
+ violations.push({
200
+ ruleId: rule.id,
201
+ phrase: matched,
202
+ description: rule.description,
203
+ });
204
+ break;
205
+ }
206
+ }
207
+ }
208
+
209
+ // 2. Cross-product conflation check
210
+ for (const otherProduct of brandCfg.crossProductForbidden || []) {
211
+ const matched = findCaseInsensitivePhrase(content, otherProduct);
212
+ if (matched) {
213
+ // Avoid duplicating if already caught by no-real-estate-or-tax-deed
214
+ if (!violations.some((v) => v.phrase.toLowerCase() === matched.toLowerCase())) {
215
+ violations.push({
216
+ ruleId: 'no-cross-product-conflation',
217
+ phrase: matched,
218
+ description: `Do not mention other products (${matched}) in ${brandCfg.name} outbound copy.`,
219
+ });
220
+ }
221
+ }
222
+ }
223
+
224
+ // 3. Voice check: line-start bot labels ("Problem:", "Fix:", etc.)
225
+ const labelMatch = LINE_LABEL_RE.exec(content);
226
+ if (labelMatch) {
227
+ violations.push({
228
+ ruleId: 'voice-no-line-labels',
229
+ phrase: labelMatch[0].trim(),
230
+ description: 'Do not start lines with bot-style labels like Problem:, Fix:, or Solution:.',
231
+ });
232
+ }
233
+
234
+ // 4. Voice check: more than one price in a single post, or unverified price for the brand
235
+ const prices = extractDistinctPrices(content);
236
+ const maxPrices = Number.isFinite(config.maxPricesPerPost) ? config.maxPricesPerPost : 1;
237
+ if (prices.length > maxPrices) {
238
+ violations.push({
239
+ ruleId: 'voice-single-price-per-post',
240
+ phrase: prices.join(', '),
241
+ description: `Use at most ${maxPrices} price in a single outbound post (found ${prices.length}: ${prices.join(', ')}).`,
242
+ });
243
+ }
244
+ const verifiedLower = new Set((brandCfg.verifiedPrices || []).map((p) => p.toLowerCase()));
245
+ for (const p of prices) {
246
+ if (!verifiedLower.has(p.toLowerCase())) {
247
+ violations.push({
248
+ ruleId: 'voice-unverified-price-claim',
249
+ phrase: p,
250
+ description: `Price ${p} is not listed on ${brandCfg.canonicalOrigin}.`,
251
+ });
252
+ }
253
+ }
254
+
255
+ if (violations.length === 0) {
256
+ return {
257
+ allowed: true,
258
+ brand,
259
+ violations: [],
260
+ rewriteSuggestion: null,
261
+ message: null,
262
+ };
263
+ }
264
+
265
+ const rewriteSuggestion = rewriteInIgorVoice(content, { config, brand });
266
+ const ruleSummary = violations.map((v) => `${v.ruleId} ("${v.phrase}")`).join('; ');
267
+ const message =
268
+ `Brand standards gate denied outbound copy — violated ${ruleSummary}. ` +
269
+ `Plain-words rewrite: ${rewriteSuggestion}`;
270
+
271
+ return {
272
+ allowed: false,
273
+ brand,
274
+ violations,
275
+ rewriteSuggestion,
276
+ message,
277
+ };
278
+ }
279
+
280
+ function extractCliFlagValue(command, flagNames) {
281
+ for (const flag of flagNames) {
282
+ const idx = command.indexOf(flag);
283
+ if (idx === -1) continue;
284
+ let rest = command.slice(idx + flag.length).trimStart();
285
+ if (rest.startsWith('=')) rest = rest.slice(1).trimStart();
286
+ if (rest.startsWith('"') || rest.startsWith("'")) {
287
+ const q = rest[0];
288
+ let end = 1;
289
+ while (end < rest.length && rest[end] !== q) {
290
+ if (rest[end] === '\\') end += 2;
291
+ else end += 1;
292
+ }
293
+ return rest.slice(1, end);
294
+ }
295
+ const sp = rest.search(/\s/);
296
+ return sp === -1 ? rest : rest.slice(0, sp);
297
+ }
298
+ return null;
299
+ }
300
+
301
+ /**
302
+ * Extracts outbound publish text (or Adobe Creative Cloud local MCP file targets)
303
+ * from a proposed PreToolUse call. Returns null for non-outbound developer actions.
304
+ */
305
+ function inspectOutboundOrCreativeToolCall(toolName, toolInput = {}) {
306
+ const name = String(toolName || '').trim();
307
+ const cmd = String(toolInput.command || '').trim();
308
+ const filePath = String(toolInput.file_path || toolInput.path || toolInput.outputPath || '').trim();
309
+
310
+ // 1. Creative file protection (Adobe Creative Cloud local MCP preview & native project files)
311
+ const isCreativeTool = /(?:photoshop|illustrator|indesign|premiere|after[_-]?effects|adobe|creative)/i.test(name);
312
+ const isExportOrPublish = /(?:export|publish|render|share)/i.test(`${name} ${String(toolInput.action || '')}`);
313
+
314
+ if (isCreativeTool && isExportOrPublish) {
315
+ return {
316
+ kind: 'creative_export_publish',
317
+ target: filePath || name,
318
+ };
319
+ }
320
+
321
+ const isAdobeOrFileWrite = ['Write', 'Edit', 'MultiEdit'].includes(name) || isCreativeTool;
322
+ if (isAdobeOrFileWrite && filePath && CREATIVE_EXT_RE.test(filePath)) {
323
+ if (!CREATIVE_BACKUP_STEM_RE.test(path.basename(filePath)) && toolInput.savedCopyVerified !== true) {
324
+ return {
325
+ kind: 'creative_overwrite',
326
+ filePath,
327
+ };
328
+ }
329
+ }
330
+
331
+ // Never treat local source-code Edit/Write/Read/Glob/Grep as outbound publishing
332
+ if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Read', 'Glob', 'Grep', 'LS'].includes(name)) {
333
+ return null;
334
+ }
335
+
336
+ // 2. MCP social / email / browser publish tools
337
+ if (/^mcp__(?:zernio|linkedin|bluesky|threads|reddit|gmail|resend|substack|medium)/i.test(name)) {
338
+ const body = [toolInput.text, toolInput.body, toolInput.content, toolInput.post, toolInput.caption, toolInput.subject]
339
+ .filter(Boolean)
340
+ .join('\n');
341
+ if (body) return { kind: 'outbound_copy', text: body, brand: toolInput.brand };
342
+ }
343
+
344
+ if (/browseros[-_]neo|dayglass_browser_(?:type|fill)/i.test(name)) {
345
+ const codeOrText = String(toolInput.code || toolInput.text || toolInput.value || '');
346
+ const hitsSocialCompose = /(?:linkedin\.com\/(?:sharing|feed|posts)|bsky\.app|threads\.(?:com|net)|(?:x|twitter)\.com\/(?:compose|intent)|reddit\.com\/r\/.*\/submit|substack\.com|medium\.com)/i.test(
347
+ `${codeOrText} ${String(toolInput.url || '')}`,
348
+ );
349
+ if (hitsSocialCompose && codeOrText) {
350
+ return { kind: 'outbound_copy', text: codeOrText, brand: toolInput.brand };
351
+ }
352
+ }
353
+
354
+ // 3. Bash outbound publishing commands
355
+ if (name === 'Bash' && cmd) {
356
+ // Skip local developer/test/git commands immediately
357
+ if (/^(?:git|rg|grep|ls|cat|head|tail|wc|find)\b/.test(cmd) || /^node\s+--test\b/.test(cmd) || /^npm\s+(?:test|run\s+test)\b/.test(cmd)) {
358
+ return null;
359
+ }
360
+
361
+ // gh issue comment / gh pr comment
362
+ if (/\bgh\s+(?:issue|pr)\s+comment\b/.test(cmd)) {
363
+ const body = extractCliFlagValue(cmd, ['--body', '-b']) || cmd;
364
+ return { kind: 'outbound_copy', text: body, channel: 'github_comment' };
365
+ }
366
+
367
+ // Social / newsletter / email CLI publishers
368
+ if (
369
+ /(?:scripts\/(?:post-everywhere|publish-bluesky|social-post-hourly|publish-linkedin|social-analytics\/publishers|medium-weekly)|api\.linkedin\.com|ugcPosts|com\.atproto\.repo\.createRecord|dev\.to\/api\/articles|api\.medium\.com|sendmail\b|msmtp\b)/.test(
370
+ cmd,
371
+ )
372
+ ) {
373
+ const explicitText = extractCliFlagValue(cmd, ['--text', '--body', '--comment', '-d', '--data', '--data-raw']);
374
+ return { kind: 'outbound_copy', text: explicitText || cmd };
375
+ }
376
+ }
377
+
378
+ return null;
379
+ }
380
+
381
+ /**
382
+ * PreToolUse hook adapter for `scripts/gates-engine.js`.
383
+ */
384
+ function applyBrandStandardsPretool(toolName, toolInput = {}, options = {}) {
385
+ const inspected = inspectOutboundOrCreativeToolCall(toolName, toolInput);
386
+ if (!inspected) return null;
387
+
388
+ if (inspected.kind === 'creative_overwrite') {
389
+ return {
390
+ decision: 'deny',
391
+ gate: 'brand-standards-gate',
392
+ ruleId: 'creative-no-overwrite-original',
393
+ severity: 'critical',
394
+ message: `Brand standards gate denied overwriting original creative project file "${inspected.filePath}" without a saved copy (e.g. write to *_copy${path.extname(inspected.filePath)} first).`,
395
+ reasoning: ['rule: creative-no-overwrite-original', `target: ${inspected.filePath}`],
396
+ };
397
+ }
398
+
399
+ if (inspected.kind === 'creative_export_publish') {
400
+ return {
401
+ decision: 'approve',
402
+ gate: 'brand-standards-gate',
403
+ ruleId: 'creative-export-publish-approval',
404
+ severity: 'high',
405
+ requiresApproval: true,
406
+ message: `Exporting or publishing creative asset "${inspected.target}" via local MCP requires human approval.`,
407
+ reasoning: ['rule: creative-export-publish-approval', `target: ${inspected.target}`],
408
+ };
409
+ }
410
+
411
+ const verdict = evaluateBrandStandards(inspected.text, options);
412
+ if (verdict.allowed) return null;
413
+
414
+ return {
415
+ decision: 'deny',
416
+ gate: 'brand-standards-gate',
417
+ ruleId: verdict.violations[0].ruleId,
418
+ violations: verdict.violations,
419
+ rewriteSuggestion: verdict.rewriteSuggestion,
420
+ severity: 'critical',
421
+ message: verdict.message,
422
+ reasoning: verdict.violations.map((v) => `rule ${v.ruleId} matched "${v.phrase}"`),
423
+ };
424
+ }
425
+
426
+ // ---------------------------------------------------------------------------
427
+ // Candidate Brand Rule Learning (held for human approval; never auto-applied)
428
+ // ---------------------------------------------------------------------------
429
+
430
+ function resolvePendingBrandRulesPath(options = {}) {
431
+ const dir = options.feedbackDir || process.env.THUMBGATE_FEEDBACK_DIR || path.join(__dirname, '..', '.thumbgate', 'feedback');
432
+ return path.join(dir, 'pending-brand-rules.json');
433
+ }
434
+
435
+ function listPendingBrandRules(options = {}) {
436
+ const pendingPath = resolvePendingBrandRulesPath(options);
437
+ if (!fs.existsSync(pendingPath)) return [];
438
+ try {
439
+ const parsed = JSON.parse(fs.readFileSync(pendingPath, 'utf8'));
440
+ return Array.isArray(parsed) ? parsed : [];
441
+ } catch {
442
+ return [];
443
+ }
444
+ }
445
+
446
+ function savePendingBrandRules(entries, options = {}) {
447
+ const pendingPath = resolvePendingBrandRulesPath(options);
448
+ fs.mkdirSync(path.dirname(pendingPath), { recursive: true });
449
+ fs.writeFileSync(pendingPath, `${JSON.stringify(entries, null, 2)}\n`, 'utf8');
450
+ return pendingPath;
451
+ }
452
+
453
+ function extractCandidatePhrase(blob) {
454
+ // Prefer explicit quoted offending phrase ("7-day refund guarantee" or 'corporate-expensable')
455
+ const dblIdx = blob.indexOf('"');
456
+ if (dblIdx !== -1) {
457
+ const closeIdx = blob.indexOf('"', dblIdx + 1);
458
+ if (closeIdx > dblIdx + 2 && closeIdx - dblIdx <= 120) {
459
+ return blob.slice(dblIdx + 1, closeIdx).trim();
460
+ }
461
+ }
462
+ const sglIdx = blob.indexOf("'");
463
+ if (sglIdx !== -1) {
464
+ const closeIdx = blob.indexOf("'", sglIdx + 1);
465
+ if (closeIdx > sglIdx + 2 && closeIdx - sglIdx <= 120) {
466
+ return blob.slice(sglIdx + 1, closeIdx).trim();
467
+ }
468
+ }
469
+ const cleaned = blob.replace(/^(?:never|do not|don't|stop)\s+(?:post|say|mention|include|promise)\s+/i, '').trim();
470
+ return cleaned.slice(0, 80) || null;
471
+ }
472
+
473
+ function isBrandOrPostContentFeedback(feedbackEvent = {}) {
474
+ const tags = Array.isArray(feedbackEvent.tags) ? feedbackEvent.tags.map((t) => String(t).toLowerCase()) : [];
475
+ if (tags.some((t) => ['brand', 'post', 'social', 'linkedin', 'copy', 'voice', 'marketing'].includes(t))) {
476
+ return true;
477
+ }
478
+ const combined = [
479
+ feedbackEvent.context,
480
+ feedbackEvent.whatWentWrong,
481
+ feedbackEvent.whatToChange,
482
+ ]
483
+ .filter(Boolean)
484
+ .join(' ')
485
+ .toLowerCase();
486
+
487
+ return OUTBOUND_POST_CONTEXT_KEYWORDS.some((kw) => findCaseInsensitivePhrase(combined, kw) !== null);
488
+ }
489
+
490
+ /**
491
+ * Stages a candidate brand rule from a thumbs-down on post/copy content.
492
+ * Held in `pending-brand-rules.json` with `status: 'pending_approval'` — NEVER auto-applied.
493
+ */
494
+ function stageCandidateBrandRuleFromFeedback(feedbackEvent = {}, options = {}) {
495
+ const signal = String(feedbackEvent.signal || '').toLowerCase();
496
+ if (signal !== 'negative' && signal !== 'down') return null;
497
+ if (!isBrandOrPostContentFeedback(feedbackEvent)) return null;
498
+
499
+ const sourceText =
500
+ feedbackEvent.whatWentWrong ||
501
+ feedbackEvent.whatToChange ||
502
+ feedbackEvent.context ||
503
+ '';
504
+ const candidatePhrase = extractCandidatePhrase(String(sourceText));
505
+ if (!candidatePhrase || candidatePhrase.length < 3) return null;
506
+
507
+ const existing = listPendingBrandRules(options);
508
+ const dup = existing.find(
509
+ (entry) =>
510
+ entry.status === 'pending_approval' &&
511
+ String(entry.phrase || '').toLowerCase() === candidatePhrase.toLowerCase(),
512
+ );
513
+ if (dup) return dup;
514
+
515
+ const id = `brand_cand_${crypto.createHash('sha256').update(candidatePhrase.toLowerCase()).digest('hex').slice(0, 10)}`;
516
+ const entry = {
517
+ id,
518
+ status: 'pending_approval',
519
+ autoApplied: false,
520
+ phrase: candidatePhrase,
521
+ proposedRuleId: `learned-${candidatePhrase.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 32)}`,
522
+ ruleChangePreview: `Rule change preview (tightening, held for human approval): outbound posts containing "${candidatePhrase}" will be denied before publish once approved.`,
523
+ sourceFeedbackId: feedbackEvent.id || null,
524
+ createdAt: new Date().toISOString(),
525
+ approvedBy: null,
526
+ approvedAt: null,
527
+ };
528
+
529
+ existing.push(entry);
530
+ savePendingBrandRules(existing, options);
531
+ return entry;
532
+ }
533
+
534
+ function approveCandidateBrandRule(candidateId, { approvedBy, feedbackDir, configPath = DEFAULT_BRAND_STANDARDS_PATH } = {}) {
535
+ if (!approvedBy || !String(approvedBy).trim()) {
536
+ throw new Error('approvedBy is required to approve a candidate brand rule');
537
+ }
538
+ const entries = listPendingBrandRules({ feedbackDir });
539
+ const target = entries.find((e) => e.id === candidateId);
540
+ if (!target) {
541
+ throw new Error(`Candidate brand rule not found: ${candidateId}`);
542
+ }
543
+ target.status = 'approved';
544
+ target.approvedBy = String(approvedBy).trim();
545
+ target.approvedAt = new Date().toISOString();
546
+ savePendingBrandRules(entries, { feedbackDir });
547
+
548
+ const config = loadBrandStandards(configPath);
549
+ config.rules = Array.isArray(config.rules) ? config.rules : [];
550
+ config.rules.push({
551
+ id: target.proposedRuleId,
552
+ description: `Learned from human-approved feedback (${target.sourceFeedbackId || target.id}).`,
553
+ phrases: [target.phrase],
554
+ });
555
+ fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
556
+ return target;
557
+ }
558
+
559
+ module.exports = {
560
+ DEFAULT_BRAND_STANDARDS_PATH,
561
+ loadBrandStandards,
562
+ detectBrandFromText,
563
+ extractDistinctPrices,
564
+ rewriteInIgorVoice,
565
+ evaluateBrandStandards,
566
+ inspectOutboundOrCreativeToolCall,
567
+ applyBrandStandardsPretool,
568
+ listPendingBrandRules,
569
+ stageCandidateBrandRuleFromFeedback,
570
+ approveCandidateBrandRule,
571
+ };
@@ -29,7 +29,7 @@ function parseNumber(value, fallback = 0) {
29
29
 
30
30
  function normalizeOptions(raw = {}) {
31
31
  return {
32
- offer: normalizeText(raw.offer) || 'ThumbGate Pro and Workflow Hardening Sprint',
32
+ offer: normalizeText(raw.offer) || 'ThumbGate Pro and Setup Sprint',
33
33
  audience: normalizeText(raw.audience) || 'AI coding teams and developers comparing agent governance tools',
34
34
  budget: parseNumber(raw.budget || raw['test-budget'], 500),
35
35
  keywords: splitList(raw.keywords || raw.queries).length
@@ -1,17 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- /**
5
- * cli-demo.js — simulated walkthrough of the ThumbGate value prop.
6
- *
7
- * Shows in ~10 seconds:
8
- * 1. A mock bad action (force-push)
9
- * 2. Giving it a thumbs-down
10
- * 3. Lesson created
11
- * 4. Next session: gate fires, action blocked
12
- *
13
- * No actual data is written — this is a pure simulation for onboarding.
14
- */
4
+ // cli-demo.js — simulated walkthrough of the ThumbGate value prop
15
5
 
16
6
  const BD = '\x1b[1m';
17
7
  const RST = '\x1b[0m';
@@ -103,22 +93,10 @@ const REPO_URL = 'https://github.com/diggerhq/shipvideo';
103
93
  const GATE_ID = 'launchvideo-deterministic-film-diode';
104
94
 
105
95
  const RAIL_MAP = Object.freeze([
106
- {
107
- launchVideoConcept: 'No video diffusion model: LLM writes film as HTML/CSS/JS; virtual clock replaces rAF/timers/Date/Web Animations (1920x1080 @ 30fps, libx264 crf 18)',
108
- thumbgateRail: 'buildVirtualClockTimeline + seekVirtualClockFrame (usesVideoDiffusionModel=false; deterministic frame seek)',
109
- },
110
- {
111
- launchVideoConcept: '3-tool director surface: web_fetch (text, headings, top hex colors, Google Fonts), check_scene (JS errors + visible text at sample timestamps), render_video',
112
- thumbgateRail: 'extractBrandTokensFromHtml + checkSceneGate (blocks render_video on JS errors or blank sample frames)',
113
- },
114
- {
115
- launchVideoConcept: 'Agent holds no secrets: per-job manifest mints 3-hour single-path Blob upload token',
116
- thumbgateRail: 'mintScopedBlobUploadManifest (agentHoldsMasterSecret=false; blocks raw BLOB_READ_WRITE_TOKEN / AWS secrets; TTL <= 10800s)',
117
- },
118
- {
119
- launchVideoConcept: 'Control plane polls tool.started/tool.completed/turn.completed and treats MP4 appearing in Blob as done',
120
- thumbgateRail: 'verifyMp4ArtifactCompletion (turn.completed alone is not done; requires verified MP4 artifact with sizeBytes > 0)',
121
- },
96
+ { launchVideoConcept: '1. Virtual clock replaces rAF/timers/Date/CSS Animations', thumbgateRail: 'buildVirtualClockTimeline + seekVirtualClockFrame' },
97
+ { launchVideoConcept: '2. 3-tool director surface (web_fetch, check_scene, render_video)', thumbgateRail: 'extractBrandTokensFromHtml + checkSceneGate' },
98
+ { launchVideoConcept: '3. Zero-secret per-job 3h scoped Blob upload manifest', thumbgateRail: 'mintScopedBlobUploadManifest' },
99
+ { launchVideoConcept: '4. MP4 artifact in Blob is completion gate', thumbgateRail: 'verifyMp4ArtifactCompletion' },
122
100
  ]);
123
101
 
124
102
  /**
@@ -328,7 +328,7 @@ const CLI_COMMANDS = [
328
328
  mcpTool: 'plan_chatgpt_ads_readiness',
329
329
  flags: [
330
330
  jsonFlag(),
331
- { name: 'offer', type: 'string', description: 'Offer to advertise, such as Pro or Workflow Hardening Sprint' },
331
+ { name: 'offer', type: 'string', description: 'Offer to advertise, such as Pro or Setup Sprint' },
332
332
  { name: 'audience', type: 'string', description: 'Audience segment to target' },
333
333
  { name: 'budget', type: 'number', description: 'Initial test budget' },
334
334
  { name: 'keywords', type: 'string', description: 'Comma-separated high-intent conversational queries' },
@@ -813,6 +813,30 @@ const CLI_COMMANDS = [
813
813
  group: 'gates',
814
814
  flags: [],
815
815
  },
816
+ {
817
+ name: 'cuda-gate',
818
+ aliases: ['cuda-gate-batch'],
819
+ description: 'CUDA-inspired parallel PreToolUse gate evaluation (SIMT + shared-memory hot cache)',
820
+ group: 'gates',
821
+ flags: [
822
+ { name: 'tool', type: 'string', description: 'Tool name being gated (e.g. Bash, Write, Read)' },
823
+ { name: 'input', type: 'string', description: 'Path to JSON file with tool input' },
824
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
825
+ { name: 'map-only', type: 'boolean', description: 'Output only category/rule mapping' },
826
+ ],
827
+ },
828
+ {
829
+ name: 'dream',
830
+ aliases: ['dream-mode'],
831
+ description: 'Anthropic Dream Mode — 4-phase memory consolidation (orientation → gather → consolidate → prune & index)',
832
+ group: 'advanced',
833
+ flags: [
834
+ { name: 'force', type: 'boolean', description: 'Force run regardless of trigger thresholds' },
835
+ { name: 'dry-run', type: 'boolean', description: 'Preview what would change without writing' },
836
+ { name: 'json', type: 'boolean', description: 'Output as JSON' },
837
+ { name: 'memory-dir', type: 'string', description: 'Custom memory directory path' },
838
+ ],
839
+ },
816
840
  {
817
841
  name: 'force-gate',
818
842
  description: 'Immediately create a blocking gate from a pattern string',
@@ -22,10 +22,10 @@ const TEAM_ANNUAL_PRICE_DOLLARS = 588;
22
22
  const TEAM_MIN_SEATS = 3;
23
23
 
24
24
  const PRO_PRICE_LABEL = '$19/mo or $149/yr (individual)';
25
- // The Enterprise Workflow Gate is the one promoted public service offer. The
25
+ // The Setup Sprint is the one promoted public service offer. The
26
26
  // dormant TEAM_* Stripe constants below remain only as inert billing plumbing
27
27
  // pending a dedicated cleanup; they are no longer a customer-facing tier.
28
- const ENTERPRISE_PRICE_LABEL = 'Enterprise Workflow Gate — $499 one-time for one supported workflow';
28
+ const ENTERPRISE_PRICE_LABEL = 'Setup Sprint — $499 one-time for one supported workflow';
29
29
  const ENTERPRISE_ENTRY_URL = 'https://thumbgate.ai/pricing';
30
30
 
31
31
  function normalizePlanId(value) {