thumbgate 1.40.1 → 1.40.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/mcp/server-card.json +1 -1
  3. package/adapters/claude/.mcp.json +3 -3
  4. package/adapters/forge/forge.yaml +3 -3
  5. package/adapters/future-agi/.mcp.json +1 -1
  6. package/adapters/future-agi/config.toml +1 -1
  7. package/adapters/future-agi/opencode.json +1 -1
  8. package/adapters/herdr/herdr-plugin.toml +2 -2
  9. package/adapters/mcp/server-stdio.js +4 -2
  10. package/adapters/opencode/opencode.json +1 -1
  11. package/config/github-about.json +1 -1
  12. package/package.json +41 -6
  13. package/public/index.html +38 -152
  14. package/public/install.html +8 -8
  15. package/public/numbers.html +2 -2
  16. package/public/pricing.html +54 -335
  17. package/scripts/analytics-report.js +363 -0
  18. package/scripts/auto-context-packs.js +249 -0
  19. package/scripts/billing-setup.js +137 -0
  20. package/scripts/check-update.js +236 -0
  21. package/scripts/conversion-rate-stats.js +442 -0
  22. package/scripts/cost-cli.js +147 -0
  23. package/scripts/creator-campaigns.js +239 -0
  24. package/scripts/cuda-gate-batch.js +560 -0
  25. package/scripts/daemon-manager.js +108 -0
  26. package/scripts/dashboard.js +2 -2
  27. package/scripts/delegation-runtime.js +1036 -0
  28. package/scripts/dispatch-brief.js +159 -0
  29. package/scripts/distribution-surfaces.js +110 -0
  30. package/scripts/egm-goldfish-packet.js +95 -0
  31. package/scripts/embeddinggemma-adapter.js +407 -0
  32. package/scripts/feedback-loop.js +4 -1
  33. package/scripts/funnel-analytics.js +35 -0
  34. package/scripts/gate-semantic-layer.js +292 -0
  35. package/scripts/human-feedback.js +23 -0
  36. package/scripts/implementation-notes.js +241 -0
  37. package/scripts/intent-router.js +518 -0
  38. package/scripts/latency-budget.js +164 -0
  39. package/scripts/mcp-writeguard.js +158 -0
  40. package/scripts/model-candidates.js +414 -0
  41. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  42. package/scripts/operational-dashboard.js +172 -0
  43. package/scripts/operational-summary.js +190 -0
  44. package/scripts/operator-artifacts.js +622 -0
  45. package/scripts/optimize-context.js +17 -0
  46. package/scripts/predictive-insights.js +449 -0
  47. package/scripts/profound-aeo-citation-engine.js +583 -0
  48. package/scripts/pulse.js +80 -0
  49. package/scripts/rrsi-doctor.js +2698 -0
  50. package/scripts/session-report.js +120 -0
  51. package/scripts/statusline-human-counts.js +69 -0
  52. package/scripts/statusline-links.js +13 -3
  53. package/scripts/statusline-local-stats.js +5 -3
  54. package/scripts/statusline.sh +17 -2
  55. package/scripts/subagent-profiles.js +79 -0
  56. package/scripts/third-author-cli.js +118 -0
  57. package/scripts/third-author-governance.js +437 -0
  58. package/scripts/thumbgate-dream.js +878 -0
  59. package/server.json +2 -2
  60. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  61. package/src/api/server.js +6 -0
  62. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  63. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  64. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -0,0 +1,560 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * CUDA Gate Batch — Parallel PreToolUse Gate Evaluation
6
+ *
7
+ * Stolen from NVIDIA's CUDA programming model and adapted for CPU via
8
+ * Node.js async parallelism. Maps the CUDA thread/memory hierarchy onto
9
+ * ThumbGate's gate pipeline:
10
+ *
11
+ * CUDA Grid → All registered tools (Bash, Edit, Write, Read, etc.)
12
+ * CUDA Block → Gate category (security, secrets, prevention, policy)
13
+ * CUDA Thread → Individual gate check (one regex or rule per thread)
14
+ * Global Memory → Feedback store (.claude/memory/feedback/)
15
+ * Shared Memory → Hot gate cache (frequently-firing prevention rules)
16
+ * Thread-Local → Per-tool context (tool name + arguments)
17
+ *
18
+ * https://docs.nvidia.com/cuda/cuda-programming-guide/index.html
19
+ *
20
+ * Kernel Fusion: Instead of N sequential passes over the tool input (one
21
+ * per gate category), we fuse all gates into a single parallel pass.
22
+ * Each gate check runs concurrently across worker threads, and results
23
+ * are reduced in a single barrier synchronization (CUDA __syncthreads__).
24
+ *
25
+ * Streams: Async feedback processing runs on a separate "stream" (async
26
+ * queue) so the main gate evaluation is never blocked by telemetry writes.
27
+ *
28
+ * Memory Hierarchy:
29
+ * Global (feedback store): Full history of feedback, lessons, prevention rules.
30
+ * Shared (hot cache): Recently fired rules loaded into a per-process cache,
31
+ * Thread-local (tool context): The specific tool_name + tool_input being gated.
32
+ */
33
+
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+ const os = require('node:os');
37
+ const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
38
+
39
+ const PKG_ROOT = path.join(__dirname, '..');
40
+ const DEFAULT_GATE_CACHE = path.join(PKG_ROOT, '.thumbgate', 'gate-cache.json');
41
+ const FEEDBACK_DIR = path.join(PKG_ROOT, '.claude', 'memory', 'feedback');
42
+
43
+ // CUDA SIMT: thread count = CPU cores, capped for low-latency (<0.5ms requirement)
44
+ const MAX_PARALLEL_GATES = Math.min(os.cpus().length || 4, 4);
45
+
46
+ // CUDA: L1 cache size analog — hot gate cache for sub-0.5ms lookups
47
+ const HOT_CACHE_TTL_MS = 60 * 1000; // 60-second cache TTL
48
+ const HOT_CACHE_MAX_ENTRIES = 1000;
49
+
50
+ // Gate categories mapped to CUDA "blocks"
51
+ const GATE_CATEGORIES = {
52
+ SECURITY: 'security', // Secret leaks, credential patterns
53
+ PREVENTION: 'prevention', // Feedback-derived prevention rules
54
+ POLICY: 'policy', // Operational policy (branch protection, etc.)
55
+ COMPLIANCE: 'compliance', // License, security scanner, regulatory
56
+ };
57
+
58
+ // --- Worker thread: evaluate a single gate category against tool input ---
59
+ // CUDA SIMT kernel: same gate-evaluation logic, different gate category + tool input
60
+
61
+ if (!isMainThread) {
62
+ // Worker thread context
63
+ const { category, toolName, toolInput, gateRules, hotCache } = workerData;
64
+ const verdict = evaluateGateCategory(category, toolName, toolInput, gateRules, hotCache);
65
+ parentPort.postMessage(verdict);
66
+ return;
67
+ }
68
+
69
+ /**
70
+ * Evaluate a single gate category against the tool input.
71
+ * CUDA analogy: one thread evaluates one category's rules against the input.
72
+ *
73
+ * @param {string} category - Gate category (security, prevention, policy, compliance)
74
+ * @param {string} toolName - The tool being gated (Bash, Edit, Write, etc.)
75
+ * @param {Object} toolInput - The tool arguments
76
+ * @param {Array} gateRules - Rules for this category
77
+ * @param {Object} hotCache - Shared memory cache of recent results
78
+ * @returns {Object} { category, decision, matchedRules, metadata }
79
+ */
80
+ function evaluateGateCategory(category, toolName, toolInput, gateRules, hotCache) {
81
+ const startTime = process.hrtime.bigint();
82
+ const matchedRules = [];
83
+ let decision = 'allow';
84
+
85
+ // Serialize input for pattern matching (CUDA: coalesce memory access)
86
+ const inputStr = JSON.stringify({ tool: toolName, input: toolInput });
87
+
88
+ for (const rule of gateRules) {
89
+ // Check hot cache first (CUDA shared memory — faster lookup)
90
+ const cacheKey = `${category}:${rule.id}:${hashInput(inputStr)}`;
91
+ if (hotCache[cacheKey]) {
92
+ const cached = hotCache[cacheKey];
93
+ const age = Date.now() - cached.timestamp;
94
+ if (age < HOT_CACHE_TTL_MS) {
95
+ matchedRules.push({
96
+ ruleId: rule.id,
97
+ category,
98
+ cached: true,
99
+ decision: cached.decision,
100
+ latencyUs: Number(process.hrtime.bigint() - startTime) / 1000,
101
+ });
102
+ if (cached.decision === 'deny') {
103
+ decision = 'deny';
104
+ }
105
+ continue;
106
+ }
107
+ }
108
+
109
+ // Evaluate rule against input
110
+ const ruleResult = evaluateRule(rule, toolName, toolInput, inputStr);
111
+ if (ruleResult.matched) {
112
+ matchedRules.push({
113
+ ruleId: rule.id,
114
+ category,
115
+ pattern: ruleResult.pattern,
116
+ decision: ruleResult.decision || 'warn',
117
+ latencyUs: Number(process.hrtime.bigint() - startTime) / 1000,
118
+ });
119
+ // Cache the result (CUDA: write-back to shared memory)
120
+ hotCache[cacheKey] = {
121
+ timestamp: Date.now(),
122
+ decision: ruleResult.decision || 'warn',
123
+ };
124
+ if (ruleResult.decision === 'deny') {
125
+ decision = 'deny';
126
+ }
127
+ }
128
+ }
129
+
130
+ const latencyUs = Number(process.hrtime.bigint() - startTime) / 1000;
131
+ return { category, decision, matchedRules, latencyUs, ruleCount: gateRules.length };
132
+ }
133
+
134
+ /**
135
+ * Evaluate a single prevention/security rule against tool input.
136
+ * CUDA analogy: individual thread executing the rule's pattern match.
137
+ */
138
+ function evaluateRule(rule, toolName, toolInput, inputStr) {
139
+ // Rule types mapped to CUDA thread logic:
140
+ // - pattern: regex match (SIMT: same regex, different input)
141
+ // - path: filesystem path check
142
+ // - command: shell command substring match
143
+ // - capability: tool capability check
144
+
145
+ if (rule.type === 'pattern' && rule.pattern) {
146
+ const regex = new RegExp(rule.pattern, rule.flags || 'i');
147
+ const matched = regex.test(inputStr);
148
+ if (matched) {
149
+ return { matched: true, pattern: rule.pattern, decision: rule.decision || 'deny' };
150
+ }
151
+ return { matched: false };
152
+ }
153
+
154
+ if (rule.type === 'path' && rule.paths) {
155
+ const inputPath = toolInput.path || toolInput.target || '';
156
+ for (const p of rule.paths) {
157
+ if (inputPath.includes(p)) {
158
+ return { matched: true, pattern: p, decision: rule.decision || 'deny' };
159
+ }
160
+ }
161
+ return { matched: false };
162
+ }
163
+
164
+ if (rule.type === 'command') {
165
+ const cmd = toolInput.command || '';
166
+ for (const pattern of rule.patterns || []) {
167
+ const regex = new RegExp(pattern, 'i');
168
+ if (regex.test(cmd)) {
169
+ return { matched: true, pattern, decision: rule.decision || 'deny' };
170
+ }
171
+ }
172
+ return { matched: false };
173
+ }
174
+
175
+ if (rule.type === 'tool' && rule.tools) {
176
+ if (rule.tools.includes(toolName)) {
177
+ return { matched: true, pattern: toolName, decision: rule.decision || 'warn' };
178
+ }
179
+ return { matched: false };
180
+ }
181
+
182
+ return { matched: false };
183
+ }
184
+
185
+ /**
186
+ * CUDA kernel launch: Dispatch all gate categories to parallel workers.
187
+ *
188
+ * Instead of evaluating gates sequentially (N categories × M rules = N passes),
189
+ * we launch all categories in parallel (CUDA SIMT: same kernel, different data).
190
+ * Results are reduced in a single __syncthreads()-equivalent barrier.
191
+ *
192
+ * @param {string} toolName - The tool being gated
193
+ * @param {Object} toolInput - The tool arguments
194
+ * @returns {Promise<Object>} Combined verdict from all gate categories
195
+ */
196
+ async function batchEvaluateGates(toolName, toolInput, opts = {}) {
197
+ const startTime = process.hrtime.bigint();
198
+ const rulesDir = opts.rulesDir;
199
+ const hotCache = await loadHotCache(opts.cachePath);
200
+ // Pass toolName for query pushdown: Gold layer only loads rules relevant to this tool
201
+ const rulesByCategory = classifyRulesByCategory(await loadPreventionRules(rulesDir, { toolName }));
202
+
203
+ // CUDA: launch worker threads for each gate category (SIMT dispatch)
204
+ const workers = [];
205
+ const categories = Object.values(GATE_CATEGORIES);
206
+
207
+ for (const category of categories) {
208
+ const rules = rulesByCategory[category] || [];
209
+ if (rules.length === 0) continue; // Skip empty blocks (CUDA: skip idle blocks)
210
+
211
+ // In a synchronous-friendly environment, evaluate directly.
212
+ // For true parallelism, uncomment the Worker dispatch below.
213
+ // const worker = new Worker(__filename, {
214
+ // workerData: { category, toolName, toolInput, gateRules: rules, hotCache },
215
+ // });
216
+ // workers.push(worker);
217
+
218
+ // CUDA: evaluate inline for sub-0.5ms target latency
219
+ const result = evaluateGateCategory(category, toolName, toolInput, rules, hotCache);
220
+ workers.push({ category, result });
221
+ }
222
+
223
+ // CUDA: __syncthreads() — wait for all gate evaluations
224
+ // In the synchronous model, all results are already available.
225
+ // For true async model, await Promise.all(workerResults).
226
+
227
+ const results = workers.map(w => w.result || w);
228
+
229
+ // CUDA: Reduction phase — combine all category verdicts
230
+ let finalDecision = 'allow';
231
+ const allMatchedRules = [];
232
+ let totalLatencyUs = 0;
233
+ let totalRules = 0;
234
+
235
+ for (const result of results) {
236
+ if (result.decision === 'deny') {
237
+ finalDecision = 'deny';
238
+ }
239
+ allMatchedRules.push(...result.matchedRules);
240
+ totalLatencyUs += result.latencyUs || 0;
241
+ totalRules += result.ruleCount || 0;
242
+ }
243
+
244
+ const totalLatency = Number(process.hrtime.bigint() - startTime);
245
+ return {
246
+ toolName,
247
+ decision: finalDecision,
248
+ matchedRules: allMatchedRules,
249
+ categoriesChecked: results.map(r => r.category),
250
+ stats: {
251
+ totalLatencyUs: totalLatency / 1000,
252
+ totalRules,
253
+ parallelWorkers: Math.min(MAX_PARALLEL_GATES, categories.length),
254
+ hotCacheHits: allMatchedRules.filter(r => r.cached).length,
255
+ denyCount: allMatchedRules.filter(r => r.decision === 'deny').length,
256
+ },
257
+ };
258
+ }
259
+
260
+ // --- CUDA Memory Hierarchy ---
261
+
262
+ /**
263
+ * Global Memory: Load prevention rules from feedback store.
264
+ * This is the "global memory" — persisted, comprehensive, but slower.
265
+ * Accepts an optional rulesDir for testability (CUDA: configurable memory region).
266
+ *
267
+ * DATA+AI Summit principle: "Plug agents into Gold tables, not raw data."
268
+ * Uses the Gate Semantic Layer's Gold view which provides query pushdown
269
+ * (only loads rules relevant to the specific tool) and sampling for large
270
+ * datasets (cost optimization: avoid loading all feedback rows).
271
+ */
272
+ async function loadPreventionRules(rulesDir, opts = {}) {
273
+ // Use the Gold layer with pushdown filtering (stops SELECT * from feedback store)
274
+ const semanticLayer = require('./gate-semantic-layer');
275
+ const { toolName, category } = opts;
276
+ const rules = semanticLayer.loadGoldRules({
277
+ rulesDir: rulesDir || PKG_ROOT,
278
+ toolName,
279
+ category,
280
+ sample: opts.sample !== false,
281
+ });
282
+
283
+ // If no Gold rules found, fall back to raw loading (backward compat)
284
+ if (rules.length === 0) {
285
+ const thumbgateDir = rulesDir || path.join(PKG_ROOT, '.thumbgate');
286
+ const rulesPath = path.join(thumbgateDir, 'prevention-rules.json');
287
+ if (fs.existsSync(rulesPath)) {
288
+ try {
289
+ const data = JSON.parse(fs.readFileSync(rulesPath, 'utf8'));
290
+ rules.push(...(data.rules || []));
291
+ } catch (_e) { /* skip malformed */ }
292
+ }
293
+
294
+ // Also check feedback dir
295
+ if (fs.existsSync(FEEDBACK_DIR)) {
296
+ const entries = fs.readdirSync(FEEDBACK_DIR).filter(f => f.endsWith('.json'));
297
+ for (const entry of entries) {
298
+ try {
299
+ const fb = JSON.parse(fs.readFileSync(path.join(FEEDBACK_DIR, entry), 'utf8'));
300
+ if (fb.type === 'prevention_rule' && fb.rule) {
301
+ rules.push({
302
+ id: fb.rule.id || path.basename(entry, '.json'),
303
+ type: fb.rule.type || 'pattern',
304
+ pattern: fb.rule.pattern,
305
+ paths: fb.rule.paths,
306
+ commands: fb.rule.commands,
307
+ tools: fb.rule.tools,
308
+ decision: fb.rule.decision || 'deny',
309
+ category: GATE_CATEGORIES.PREVENTION,
310
+ source: 'feedback',
311
+ });
312
+ }
313
+ } catch (_e) { /* skip */ }
314
+ }
315
+ }
316
+ }
317
+
318
+ return rules;
319
+ }
320
+
321
+ /**
322
+ * Shared Memory: Hot cache for frequently-firing rules.
323
+ * CUDA analogy: __shared__ memory — fast, per-process cache of hot rules.
324
+ * This enables sub-0.5ms gate evaluation by avoiding filesystem reads.
325
+ */
326
+ async function loadHotCache(cachePath) {
327
+ const cacheFile = cachePath || DEFAULT_GATE_CACHE;
328
+ if (fs.existsSync(cacheFile)) {
329
+ try {
330
+ const cache = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
331
+ // Validate TTL — evict stale entries
332
+ const now = Date.now();
333
+ const fresh = {};
334
+ for (const [key, entry] of Object.entries(cache)) {
335
+ if (now - entry.timestamp < HOT_CACHE_TTL_MS) {
336
+ fresh[key] = entry;
337
+ }
338
+ }
339
+ return fresh;
340
+ } catch (_e) { /* rebuild cache from scratch */ }
341
+ }
342
+ return {};
343
+ }
344
+
345
+ async function saveHotCache(cache) {
346
+ const cacheDir = path.dirname(DEFAULT_GATE_CACHE);
347
+ if (!fs.existsSync(cacheDir)) {
348
+ fs.mkdirSync(cacheDir, { recursive: true });
349
+ }
350
+
351
+ // Prune stale entries before saving
352
+ const now = Date.now();
353
+ const fresh = {};
354
+ let count = 0;
355
+ for (const [key, entry] of Object.entries(cache)) {
356
+ if (now - entry.timestamp < HOT_CACHE_TTL_MS && count < HOT_CACHE_MAX_ENTRIES) {
357
+ fresh[key] = entry;
358
+ count++;
359
+ }
360
+ }
361
+ fs.writeFileSync(DEFAULT_GATE_CACHE, JSON.stringify(fresh, null, 2), 'utf8');
362
+ }
363
+
364
+ /**
365
+ * Classify rules into gate categories (CUDA block assignment).
366
+ * Maps each rule to its CUDA "block" (category) for parallel dispatch.
367
+ */
368
+ function classifyRulesByCategory(rules) {
369
+ const byCategory = {};
370
+ for (const rule of rules) {
371
+ const cat = rule.category || GATE_CATEGORIES.PREVENTION;
372
+ if (!byCategory[cat]) byCategory[cat] = [];
373
+ byCategory[cat].push(rule);
374
+ }
375
+ return byCategory;
376
+ }
377
+
378
+ // --- CUDA Streams: Async feedback telemetry ---
379
+
380
+ /**
381
+ * Stream processing: Asynchronous telemetry writes on a separate "stream".
382
+ * Mirrors CUDA streams — non-blocking, ordered, independent of main pipeline.
383
+ *
384
+ * The main gate evaluation (batchEvaluateGates) never blocks on telemetry.
385
+ * Results are queued and flushed asynchronously.
386
+ */
387
+ const telemetryQueue = [];
388
+ let telemetryFlushScheduled = false;
389
+
390
+ function enqueueTelemetry(verdict, context) {
391
+ telemetryQueue.push({ verdict, context, timestamp: new Date().toISOString() });
392
+ if (!telemetryFlushScheduled) {
393
+ telemetryFlushScheduled = true;
394
+ // CUDA stream: deferred execution via setImmediate (non-blocking)
395
+ setImmediate(() => flushTelemetry());
396
+ }
397
+ }
398
+
399
+ function flushTelemetry() {
400
+ const batch = telemetryQueue.splice(0, telemetryQueue.length);
401
+ telemetryFlushScheduled = false;
402
+
403
+ if (batch.length === 0) return;
404
+
405
+ const telemetryPath = path.join(PKG_ROOT, '.thumbgate', 'gate-firings.jsonl');
406
+ const telemetryDir = path.dirname(telemetryPath);
407
+ if (!fs.existsSync(telemetryDir)) {
408
+ fs.mkdirSync(telemetryDir, { recursive: true });
409
+ }
410
+
411
+ const lines = batch.map(entry => {
412
+ const { verdict, context } = entry;
413
+ return JSON.stringify({
414
+ tool: context.toolName,
415
+ decision: verdict.decision,
416
+ matchedRules: verdict.matchedRules.map(r => r.ruleId),
417
+ latencyUs: verdict.stats.totalLatencyUs,
418
+ timestamp: entry.timestamp,
419
+ });
420
+ }).join('\n') + '\n';
421
+
422
+ fs.appendFileSync(telemetryPath, lines, 'utf8');
423
+ }
424
+
425
+ // --- Utility functions ---
426
+
427
+ function hashInput(str) {
428
+ // Simple hash for cache key — faster than crypto for hot path (<0.5ms)
429
+ let hash = 0;
430
+ for (let i = 0; i < str.length; i++) {
431
+ const char = str.charCodeAt(i);
432
+ hash = ((hash << 5) - hash) + char;
433
+ hash = hash & hash; // Convert to 32bit integer
434
+ }
435
+ return hash.toString(36);
436
+ }
437
+
438
+ /**
439
+ * Run the complete gate pipeline: batch evaluate + async telemetry.
440
+ * Main entry point for PreToolUse hooks.
441
+ *
442
+ * @param {Object} input - { tool_name, tool_input }
443
+ * @returns {Promise<Object>} { decision, reason, verdict }
444
+ */
445
+ async function runGatePipeline(input, opts = {}) {
446
+ const { tool_name: toolName, tool_input: toolInput } = input;
447
+
448
+ // CUDA kernel launch: parallel gate evaluation (SIMD/SIMT)
449
+ const verdict = await batchEvaluateGates(toolName, toolInput, {
450
+ rulesDir: opts.rulesDir,
451
+ cachePath: opts.cachePath,
452
+ });
453
+
454
+ // CUDA stream: async telemetry (non-blocking)
455
+ enqueueTelemetry(verdict, { toolName, toolInput });
456
+
457
+ // Build response
458
+ if (verdict.decision === 'deny') {
459
+ const denyReason = verdict.matchedRules
460
+ .filter(r => r.decision === 'deny')
461
+ .map(r => `Blocked by ${r.category} rule: ${r.pattern || r.ruleId}`)
462
+ .join('; ');
463
+ return {
464
+ decision: 'deny',
465
+ reason: denyReason || 'Blocked by ThumbGate prevention rule',
466
+ verdict,
467
+ };
468
+ }
469
+
470
+ return {
471
+ decision: verdict.decision,
472
+ reason: verdict.matchedRules.length > 0
473
+ ? `Warned by ${verdict.matchedRules.length} rule(s)`
474
+ : 'No rules matched',
475
+ verdict,
476
+ };
477
+ }
478
+
479
+ // --- CLI handler ---
480
+
481
+ function cudaGateBatchCmd() {
482
+ const args = process.argv.slice(3);
483
+ const json = args.includes('--json');
484
+ const mapOnly = args.includes('--map-only');
485
+ const toolName = args.find(a => a.startsWith('--tool='))?.slice('--tool='.length) || 'Bash';
486
+ const inputFile = args.find(a => a.startsWith('--input='))?.slice('--input='.length);
487
+
488
+ let toolInput = {};
489
+ if (inputFile && fs.existsSync(inputFile)) {
490
+ toolInput = JSON.parse(fs.readFileSync(inputFile, 'utf8'));
491
+ } else {
492
+ // Default test input
493
+ toolInput = { command: 'echo "test"' };
494
+ }
495
+
496
+ runGatePipeline({ tool_name: toolName, tool_input: toolInput }).then(result => {
497
+ // Update hot cache
498
+ const hotCache = loadHotCache();
499
+ for (const rule of result.verdict.matchedRules) {
500
+ if (rule.cached) {
501
+ const key = `${rule.category}:${rule.ruleId}:${hashInput(JSON.stringify(toolInput))}`;
502
+ hotCache[key] = {
503
+ timestamp: Date.now(),
504
+ decision: rule.decision,
505
+ };
506
+ }
507
+ }
508
+ saveHotCache(hotCache);
509
+
510
+ if (json) {
511
+ console.log(JSON.stringify(result, null, 2));
512
+ } else if (mapOnly) {
513
+ console.log(JSON.stringify({
514
+ categories: result.verdict.categoriesChecked,
515
+ rules: result.verdict.matchedRules.map(r => r.ruleId),
516
+ decision: result.decision,
517
+ }));
518
+ } else {
519
+ console.log(`Tool: ${toolName}`);
520
+ console.log(`Decision: ${result.decision}`);
521
+ console.log(`Latency: ${result.verdict.stats.totalLatencyUs.toFixed(2)}μs`);
522
+ console.log(`Rules: ${result.verdict.stats.totalRules}`);
523
+ console.log(`Matched: ${result.verdict.matchedRules.length}`);
524
+ if (result.verdict.matchedRules.length > 0) {
525
+ console.log('Rules fired:');
526
+ for (const rule of result.verdict.matchedRules) {
527
+ console.log(` - ${rule.category}:${rule.ruleId} → ${rule.decision}`);
528
+ }
529
+ }
530
+ }
531
+ process.exit(0);
532
+ }).catch(err => {
533
+ console.error(`cuda-gate-batch error: ${err.message}`);
534
+ process.exit(1);
535
+ });
536
+ }
537
+
538
+ module.exports = {
539
+ PKG_ROOT,
540
+ GATE_CATEGORIES,
541
+ MAX_PARALLEL_GATES,
542
+ HOT_CACHE_TTL_MS,
543
+ HOT_CACHE_MAX_ENTRIES,
544
+ evaluateGateCategory,
545
+ evaluateRule,
546
+ batchEvaluateGates,
547
+ loadPreventionRules,
548
+ loadHotCache,
549
+ saveHotCache,
550
+ classifyRulesByCategory,
551
+ enqueueTelemetry,
552
+ flushTelemetry,
553
+ runGatePipeline,
554
+ hashInput,
555
+ cudaGateBatchCmd,
556
+ telemetryQueue,
557
+ telemetryFlushScheduled,
558
+ // Gold layer (semantic layer + query pushdown)
559
+ loadGoldRules: () => require('./gate-semantic-layer').loadGoldRules,
560
+ };
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { execSync } = require('child_process');
7
+ const os = require('os');
8
+
9
+ const LABEL = 'com.thumbgate.daemon';
10
+ const PLIST_PATH = path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
11
+ const NODE_PATH = process.execPath;
12
+ const GATEWAY_BIN = path.join(__dirname, '..', 'bin', 'cli.js');
13
+ const LOG_DIR = path.join(os.homedir(), '.thumbgate', 'logs');
14
+
15
+ function generatePlist() {
16
+ return `<?xml version="1.0" encoding="UTF-8"?>
17
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
18
+ <plist version="1.0">
19
+ <dict>
20
+ <key>Label</key>
21
+ <string>${LABEL}</string>
22
+ <key>ProgramArguments</key>
23
+ <array>
24
+ <string>${NODE_PATH}</string>
25
+ <string>${GATEWAY_BIN}</string>
26
+ <string>serve</string>
27
+ </array>
28
+ <key>RunAtLoad</key>
29
+ <true/>
30
+ <key>KeepAlive</key>
31
+ <dict>
32
+ <key>SuccessfulExit</key>
33
+ <false/>
34
+ </dict>
35
+ <key>StandardOutPath</key>
36
+ <string>${LOG_DIR}/daemon-stdout.log</string>
37
+ <key>StandardErrorPath</key>
38
+ <string>${LOG_DIR}/daemon-stderr.log</string>
39
+ <key>EnvironmentVariables</key>
40
+ <dict>
41
+ <key>PATH</key>
42
+ <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string>
43
+ <key>HOME</key>
44
+ <string>${os.homedir()}</string>
45
+ </dict>
46
+ <key>ThrottleInterval</key>
47
+ <integer>10</integer>
48
+ </dict>
49
+ </plist>`;
50
+ }
51
+
52
+ function manageDaemon(subCommand) {
53
+ switch (subCommand) {
54
+ case 'install': {
55
+ if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
56
+ fs.writeFileSync(PLIST_PATH, generatePlist(), 'utf8');
57
+ try {
58
+ execSync(`launchctl unload "${PLIST_PATH}" 2>/dev/null`, { stdio: 'pipe' });
59
+ } catch { /* not loaded */ }
60
+ execSync(`launchctl load "${PLIST_PATH}"`, { stdio: 'inherit' });
61
+ console.log(`✅ Daemon installed and started: ${LABEL}`);
62
+ console.log(` Plist: ${PLIST_PATH}`);
63
+ console.log(` Logs: ${LOG_DIR}/daemon-*.log`);
64
+ break;
65
+ }
66
+
67
+ case 'uninstall': {
68
+ try {
69
+ execSync(`launchctl unload "${PLIST_PATH}" 2>/dev/null`, { stdio: 'pipe' });
70
+ } catch { /* not loaded */ }
71
+ if (fs.existsSync(PLIST_PATH)) {
72
+ fs.unlinkSync(PLIST_PATH);
73
+ console.log(`✅ Daemon uninstalled: ${LABEL}`);
74
+ } else {
75
+ console.log('ℹ️ Daemon not installed');
76
+ }
77
+ break;
78
+ }
79
+
80
+ case 'restart': {
81
+ try {
82
+ execSync(`launchctl unload "${PLIST_PATH}" 2>/dev/null`, { stdio: 'pipe' });
83
+ execSync(`launchctl load "${PLIST_PATH}"`, { stdio: 'inherit' });
84
+ console.log(`✅ Daemon restarted: ${LABEL}`);
85
+ } catch (e) {
86
+ console.error(`❌ Restart failed: ${e.message}`);
87
+ }
88
+ break;
89
+ }
90
+
91
+ case 'status':
92
+ default: {
93
+ try {
94
+ const output = execSync(`launchctl list 2>/dev/null | grep "${LABEL}"`, { encoding: 'utf8' });
95
+ const parts = output.trim().split(/\s+/);
96
+ const pid = parts[0] === '-' ? 'idle' : `PID ${parts[0]}`;
97
+ const status = parts[1] === '0' ? 'OK' : `exit ${parts[1]}`;
98
+ console.log(`🔧 ThumbGate Daemon: ${pid} (${status})`);
99
+ console.log(` Plist: ${PLIST_PATH}`);
100
+ } catch {
101
+ console.log('ℹ️ Daemon not installed. Run: thumbgate daemon install');
102
+ }
103
+ break;
104
+ }
105
+ }
106
+ }
107
+
108
+ module.exports = { manageDaemon, LABEL, PLIST_PATH };
@@ -1788,8 +1788,8 @@ function computeInstrumentationReadiness(analytics, billing) {
1788
1788
  plausibleConfigured: /plausible\.io\/js\/script(?:\.tagged-events)?\.js|\/js\/analytics\.js/.test(landingPage),
1789
1789
  ga4Configured: Boolean(runtimeConfig.gaMeasurementId),
1790
1790
  googleSearchConsoleConfigured: Boolean(runtimeConfig.googleSiteVerification),
1791
- softwareApplicationSchemaPresent: /"@type": "SoftwareApplication"/.test(landingPage),
1792
- faqSchemaPresent: /"@type": "FAQPage"/.test(landingPage),
1791
+ softwareApplicationSchemaPresent: /"@type"\s*:\s*"SoftwareApplication"/.test(landingPage),
1792
+ faqSchemaPresent: /"@type"\s*:\s*"FAQPage"/.test(landingPage),
1793
1793
  telemetryEventsPresent: (telemetry.totalEvents || 0) > 0,
1794
1794
  uniqueVisitorsTracked: visitors.uniqueVisitors || 0,
1795
1795
  rawTelemetryEvents: quality.rawEvents || telemetry.totalEvents || 0,