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
@@ -1,10 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const { tenantDataScope } = require('./feedback-scope');
5
+
4
6
  const fs = require('fs');
7
+ const os = require('os');
5
8
  const path = require('path');
6
9
  const { aggregateFailureDiagnostics } = require('./failure-diagnostics');
7
10
  const { AUDIT_LOG_FILENAME } = require('./audit-trail');
11
+ const { buildAgentRegister } = require('./agent-action-inventory');
8
12
  const { getBillingSummary, loadFunnelLedger, loadResolvedRevenueEvents } = require('./billing');
9
13
  const {
10
14
  createUnavailableReport,
@@ -98,16 +102,6 @@ function buildUnavailableOrgDashboard(windowHours) {
98
102
  };
99
103
  }
100
104
 
101
- // ---------------------------------------------------------------------------
102
- // Data readers
103
- // ---------------------------------------------------------------------------
104
-
105
- // Prod feedback/memory logs can grow past V8's max string size (~512MB–1GB).
106
- // Full-file readFileSync/stringify then throws:
107
- // "Cannot create a string longer than 0x1fffffe8 characters"
108
- // Cap dashboard JSONL ingestion to a recent tail so /v1/dashboard stays live.
109
- // A 32 MiB default is still too large: generateDashboard reads several logs
110
- // and aggregation/analyze used to full-scan the same files again.
111
105
  const DEFAULT_JSONL_MAX_BYTES = DEFAULT_JSONL_TAIL_BYTES;
112
106
  const DEFAULT_JSONL_MAX_ENTRIES = DEFAULT_JSONL_TAIL_ENTRIES;
113
107
 
@@ -121,7 +115,6 @@ function readJSONL(filePath, options = {}) {
121
115
  try {
122
116
  text = readTextTail(filePath, maxBytes).text;
123
117
  } catch (err) {
124
- // Never let a single bloated/unreadable log take down the whole dashboard.
125
118
  return [];
126
119
  }
127
120
  if (!text?.trim()) return [];
@@ -134,7 +127,7 @@ function readJSONL(filePath, options = {}) {
134
127
  try {
135
128
  const parsed = JSON.parse(line);
136
129
  if (parsed) entries.push(parsed);
137
- } catch { /* skip bad line */ }
130
+ } catch { }
138
131
  }
139
132
  return entries;
140
133
  }
@@ -186,8 +179,6 @@ function resolveGitDir(projectRoot) {
186
179
  if (!fs.existsSync(gitPath)) return null;
187
180
  const stat = fs.statSync(gitPath);
188
181
  if (stat.isDirectory()) return gitPath;
189
- // Worktree / submodule: .git is a file like "gitdir: /path/to/real/gitdir".
190
- // Parse with startsWith+slice — no regex, so no ReDoS surface (S5852).
191
182
  if (stat.isFile()) {
192
183
  const contents = fs.readFileSync(gitPath, 'utf8').trim();
193
184
  const prefix = 'gitdir:';
@@ -207,20 +198,13 @@ function readGitHead(projectRoot) {
207
198
  const gitDir = resolveGitDir(projectRoot);
208
199
  if (!gitDir) return null;
209
200
  try {
210
- // Read .git/HEAD directly instead of spawning `git rev-parse HEAD`.
211
- // Avoids S4036 (PATH-resolved binary) and is faster: no subprocess.
212
201
  const head = fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8').trim();
213
202
  if (!head) return null;
214
- // Detached HEAD: the file contains the raw SHA.
215
203
  if (/^[0-9a-f]{40}$/i.test(head)) return head;
216
- // Symbolic ref: "ref: refs/heads/<branch>" — resolve the ref file.
217
- // Parse with startsWith+slice — no regex, so no ReDoS surface (S5852).
218
204
  const refPrefix = 'ref:';
219
205
  if (!head.startsWith(refPrefix)) return null;
220
206
  const refName = head.slice(refPrefix.length).trim();
221
207
  if (!refName) return null;
222
- // For worktrees, the commondir points to the main .git. Refs may live
223
- // there rather than in the per-worktree gitdir.
224
208
  const commonDirFile = path.join(gitDir, 'commondir');
225
209
  let commonDir = gitDir;
226
210
  if (fs.existsSync(commonDirFile)) {
@@ -234,7 +218,6 @@ function readGitHead(projectRoot) {
234
218
  if (/^[0-9a-f]{40}$/i.test(sha)) return sha;
235
219
  }
236
220
  }
237
- // Packed refs fallback.
238
221
  const packed = path.join(commonDir, 'packed-refs');
239
222
  if (!fs.existsSync(packed)) return null;
240
223
  const lines = fs.readFileSync(packed, 'utf8').split(/\r?\n/);
@@ -258,10 +241,26 @@ function findLatestTimestamp(entries) {
258
241
  }, null);
259
242
  }
260
243
 
244
+ function normalizeDashboardFeedback(entries) {
245
+ return entries.map((entry) => {
246
+ const signal = String(entry.signal || entry.feedback || '').toLowerCase();
247
+ return { ...entry, signal: ['up', 'positive', 'thumbs_up'].includes(signal) ? 'positive' : ['down', 'negative', 'thumbs_down'].includes(signal) ? 'negative' : entry.signal };
248
+ });
249
+ }
250
+
251
+ function selectDashboardFeedback(entries, humanOnly) {
252
+ return humanOnly
253
+ ? entries.filter((entry) => entry.reviewOrigin === 'human' && ['positive', 'negative'].includes(entry.signal))
254
+ : entries;
255
+ }
256
+
261
257
  function buildReviewSnapshot(feedbackDir, options = {}) {
262
- const feedbackEntries = Array.isArray(options.feedbackEntries)
263
- ? options.feedbackEntries
264
- : readJSONL(path.join(feedbackDir, 'feedback-log.jsonl'));
258
+ const feedbackEntries = selectDashboardFeedback(
259
+ Array.isArray(options.feedbackEntries)
260
+ ? (options.humanOnly && shouldAggregateFeedback() ? normalizeDashboardFeedback(options.feedbackEntries) : options.feedbackEntries)
261
+ : (options.humanOnly ? collectAllFeedbackEntries(feedbackDir) : readJSONL(path.join(feedbackDir, 'feedback-log.jsonl'))),
262
+ options.humanOnly,
263
+ );
265
264
  const memoryEntries = Array.isArray(options.memoryEntries)
266
265
  ? options.memoryEntries
267
266
  : readJSONL(path.join(feedbackDir, 'memory-log.jsonl'));
@@ -286,13 +285,17 @@ function buildReviewSnapshot(feedbackDir, options = {}) {
286
285
  };
287
286
  }
288
287
 
289
- function readDashboardReviewState(feedbackDir) {
290
- return readJsonFile(getDashboardReviewStatePath(feedbackDir));
288
+ function readDashboardReviewState(feedbackDir, options = {}) {
289
+ const state = readJsonFile(getDashboardReviewStatePath(feedbackDir));
290
+ return state?.version === 2 ? state.byProject?.[options.projectKey || 'all'] || null : options.projectKey ? null : state;
291
291
  }
292
292
 
293
- function writeDashboardReviewState(feedbackDir, snapshot) {
293
+ function writeDashboardReviewState(feedbackDir, snapshot, options = {}) {
294
+ const old = readJsonFile(getDashboardReviewStatePath(feedbackDir));
295
+ const state = old?.version === 2 ? old : { version: 2, byProject: old ? { all: old } : {} };
296
+ state.byProject[options.projectKey || 'all'] = snapshot;
294
297
  fs.mkdirSync(feedbackDir, { recursive: true });
295
- fs.writeFileSync(getDashboardReviewStatePath(feedbackDir), `${JSON.stringify(snapshot, null, 2)}\n`);
298
+ fs.writeFileSync(getDashboardReviewStatePath(feedbackDir), `${JSON.stringify(state, null, 2)}\n`);
296
299
  return snapshot;
297
300
  }
298
301
 
@@ -390,17 +393,12 @@ function summarizeReviewDelta(feedbackEntries, memoryEntries, auditEntries, base
390
393
  };
391
394
  }
392
395
 
393
- // ---------------------------------------------------------------------------
394
- // Approval rate + trend
395
- // ---------------------------------------------------------------------------
396
-
397
396
  function computeApprovalStats(entries) {
398
397
  const total = entries.length;
399
398
  const positive = entries.filter((e) => e.signal === 'positive').length;
400
399
  const negative = entries.filter((e) => e.signal === 'negative').length;
401
400
  const approvalRate = total > 0 ? Math.round((positive / total) * 100) : 0;
402
401
 
403
- // 7-day trend
404
402
  const now = Date.now();
405
403
  const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000;
406
404
  const recentEntries = entries.filter((e) => {
@@ -427,27 +425,44 @@ function computeApprovalStats(entries) {
427
425
  };
428
426
  }
429
427
 
430
- // ---------------------------------------------------------------------------
431
- // Gate enforcement stats
432
- // ---------------------------------------------------------------------------
433
-
434
- function computeGateStats() {
435
- const autoGatesPath = getAutoGatesPath();
436
- const statsPath = path.join(
437
- process.env.HOME || '/tmp',
438
- '.thumbgate',
439
- 'gate-stats.json'
428
+ function resolveScopedGateStatsPath(feedbackDir) {
429
+ const stateDir = process.env.THUMBGATE_STATE_DIR
430
+ || path.join(process.env.HOME || '/tmp', '.thumbgate');
431
+ const defaultStatsPath = path.join(stateDir, 'gate-stats.json');
432
+ if (!feedbackDir) return defaultStatsPath;
433
+ const localStatsPath = path.join(feedbackDir, 'gate-stats.json');
434
+ if (fs.existsSync(localStatsPath)) return localStatsPath;
435
+ const resolved = path.resolve(feedbackDir);
436
+ const homeTg = path.resolve(stateDir);
437
+ const projRoot = path.resolve(PROJECT_ROOT);
438
+ const tmpRoot = path.resolve(require('node:os').tmpdir());
439
+ const explicitFeedbackDir = Boolean(String(process.env.THUMBGATE_FEEDBACK_DIR || '').trim());
440
+ const isProjectFeedbackSubdir = !explicitFeedbackDir && (
441
+ resolved.endsWith(`${path.sep}.thumbgate`)
442
+ || resolved.endsWith(`${path.sep}.thumbgate-compat`)
443
+ || resolved.endsWith(`${path.sep}.claude${path.sep}memory${path.sep}feedback`)
440
444
  );
441
- const stats = readJsonFile(statsPath) || { blocked: 0, warned: 0, passed: 0, byGate: {} };
445
+ const inDefaultScope = (
446
+ resolved === homeTg
447
+ || resolved.startsWith(`${homeTg}${path.sep}`)
448
+ || resolved === projRoot
449
+ || resolved.startsWith(`${projRoot}${path.sep}`)
450
+ || isProjectFeedbackSubdir
451
+ ) && !resolved.includes(`${path.sep}tenants${path.sep}`) && !resolved.startsWith(`${tmpRoot}${path.sep}`);
452
+ return inDefaultScope ? defaultStatsPath : localStatsPath;
453
+ }
442
454
 
443
- // Count manual vs auto-promoted gates
455
+ function computeGateStats(feedbackDir, options = {}) {
456
+ if (options.projectKey != null) return require('./project-dashboard').generateProjectDashboard(feedbackDir, options).gateStats;
457
+ const autoGatesPath = getAutoGatesPath({ feedbackDir });
458
+ const statsPath = resolveScopedGateStatsPath(feedbackDir);
459
+ const stats = readJsonFile(statsPath) || { blocked: 0, warned: 0, passed: 0, byGate: {} };
444
460
  const defaultGates = readJsonFile(DEFAULT_GATES_PATH);
445
461
  const autoGates = readJsonFile(autoGatesPath);
446
462
  const manualCount = defaultGates && Array.isArray(defaultGates.gates) ? defaultGates.gates.length : 0;
447
463
  const autoCount = autoGates && Array.isArray(autoGates.gates) ? autoGates.gates.length : 0;
448
464
  const totalGates = manualCount + autoCount;
449
465
 
450
- // Top blocked gate
451
466
  let topBlocked = null;
452
467
  let topBlockedCount = 0;
453
468
  if (stats.byGate) {
@@ -530,23 +545,399 @@ function listActiveGates() {
530
545
  const config = loadGatesConfig();
531
546
  return (config.gates || []).map((gate) => ({
532
547
  id: gate.id || null,
533
- name: gate.id || gate.pattern || 'gate',
548
+ name: gate.id || 'Gate',
534
549
  pattern: gate.pattern || '',
535
550
  action: gate.action || 'warn',
536
551
  severity: gate.severity || 'medium',
537
552
  layer: gate.layer || null,
553
+ message: gate.message || null,
554
+ source: gate.source || null,
555
+ sourceLessonId: gate.sourceLessonId || null,
556
+ sourceFeedbackId: gate.sourceFeedbackId || null,
557
+ createdAt: gate.createdAt || null,
558
+ promotedAt: gate.promotedAt || null,
538
559
  }));
539
560
  } catch {
540
561
  return [];
541
562
  }
542
563
  }
543
564
 
544
- // ---------------------------------------------------------------------------
545
- // Prevention impact
546
- // ---------------------------------------------------------------------------
565
+ function formatStorageBytes(bytes) {
566
+ const n = Number.isFinite(bytes) && bytes > 0 ? Math.trunc(bytes) : 0;
567
+ if (n === 0) return '0 B';
568
+ if (n < 1024) return `${n} B`;
569
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(2)} KB`;
570
+ if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(2)} MB`;
571
+ return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
572
+ }
573
+
574
+ function measureDirBytesBounded(targetPath, depth = 0) {
575
+ if (depth > 3 || !targetPath || !fs.existsSync(targetPath)) return 0;
576
+ try {
577
+ const st = fs.lstatSync(targetPath);
578
+ if (st.isSymbolicLink()) return 0;
579
+ if (st.isFile()) return st.size;
580
+ if (!st.isDirectory()) return 0;
581
+ let total = 0;
582
+ for (const entry of fs.readdirSync(targetPath).slice(0, 128)) {
583
+ total += measureDirBytesBounded(path.join(targetPath, entry), depth + 1);
584
+ }
585
+ return total;
586
+ } catch {
587
+ return 0;
588
+ }
589
+ }
590
+
591
+ function formatDisplayStoragePath(rawDir) {
592
+ const resolved = path.resolve(String(rawDir || ''));
593
+ const home = process.env.HOME ? path.resolve(process.env.HOME) : '';
594
+ if (home && (resolved === home || resolved.startsWith(`${home}${path.sep}`))) {
595
+ return `~${resolved.slice(home.length)}`;
596
+ }
597
+ return path.basename(path.dirname(resolved))
598
+ ? `${path.basename(path.dirname(resolved))}/${path.basename(resolved)}`
599
+ : path.basename(resolved) || '.thumbgate';
600
+ }
601
+
602
+ function computeLessonStorageSummary(feedbackDir, memoryCount = 0) {
603
+ const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
604
+ const trackedNames = ['memory-log.jsonl', 'prevention-rules.md', 'auto-promoted-gates.json', 'lancedb', 'vectors'];
605
+ let lessonDbBytes = 0;
606
+ for (const name of trackedNames) {
607
+ lessonDbBytes += measureDirBytesBounded(path.join(feedbackDir, name), 0);
608
+ }
609
+ const dirDisplay = formatDisplayStoragePath(feedbackDir);
610
+ return {
611
+ label: '100% On-Device Private Memory',
612
+ location: `${dirDisplay}/memory-log.jsonl`,
613
+ exists: fs.existsSync(memoryLogPath),
614
+ lessonCount: Number.isFinite(memoryCount) && memoryCount > 0 ? Math.trunc(memoryCount) : 0,
615
+ lessonDbBytes,
616
+ lessonDbSizeDisplay: formatStorageBytes(lessonDbBytes),
617
+ };
618
+ }
619
+
620
+ const FINISH_SETUP_COMMAND = 'npx thumbgate quickstart';
621
+ const FINISH_SETUP_HREF = '/install#quickstart';
622
+ const FINISH_SETUP_DETAIL = 'Run npx thumbgate quickstart to fire your first PreToolUse block and unlock the built-in safety rule pack + 3 custom block rules on the Free tier (7-day local Pro trial included).';
623
+ const ACCOUNT_ACTIVATIONS_FILENAME = 'account-activations.json';
624
+ const PAID_SETUP_TIERS = new Set(['pro', 'team', 'enterprise']);
625
+ const CLI_ACTIVATION_EVENTS = new Set([
626
+ 'first_block',
627
+ 'first_blocked_tool_call',
628
+ 'activation_first_rule_promoted',
629
+ 'cli_quickstart_activated',
630
+ 'cli_heartbeat',
631
+ 'cli_capture',
632
+ 'cli_recall',
633
+ 'cli_stats',
634
+ 'cli_init',
635
+ ]);
636
+ const _backfillMtimeCache = new Map();
637
+
638
+ function isPaidSetupTier(tier) {
639
+ return PAID_SETUP_TIERS.has(String(tier || '').trim().toLowerCase());
640
+ }
641
+
642
+ function pickEarliestStamp(a, b) {
643
+ if (!a) return b || null;
644
+ if (!b) return a;
645
+ const ta = Date.parse(a);
646
+ const tb = Date.parse(b);
647
+ if (!Number.isFinite(ta)) return b;
648
+ if (!Number.isFinite(tb)) return a;
649
+ return ta <= tb ? a : b;
650
+ }
651
+
652
+ function isBlockActivationMarker(parsed) {
653
+ if (!parsed || typeof parsed !== 'object') return false;
654
+ return Boolean(parsed.firstBlockAt || parsed.blockedAt || parsed.event === 'first_block');
655
+ }
656
+
657
+ function readActivationMarker(feedbackDir) {
658
+ if (!feedbackDir) return null;
659
+ const candidates = [
660
+ path.join(feedbackDir, 'activation-recorded.json'),
661
+ path.join(feedbackDir, 'activation', 'first-blocked-call.json'),
662
+ ];
663
+ if (path.basename(feedbackDir) === 'feedback') {
664
+ const parentDir = path.dirname(feedbackDir);
665
+ if (path.resolve(parentDir) !== path.resolve(os.tmpdir())) {
666
+ candidates.push(
667
+ path.join(parentDir, 'activation-recorded.json'),
668
+ path.join(parentDir, 'activation', 'first-blocked-call.json'),
669
+ );
670
+ }
671
+ }
672
+ for (const candidate of candidates) {
673
+ const parsed = readJsonFile(candidate);
674
+ if (isBlockActivationMarker(parsed)) return parsed;
675
+ }
676
+ return null;
677
+ }
678
+ function writeActivationMarkerFile(targetDir, firstBlockAt, source = 'first_block') {
679
+ if (!targetDir) return;
680
+ try {
681
+ fs.mkdirSync(targetDir, { recursive: true });
682
+ const markerPath = path.join(targetDir, 'activation-recorded.json');
683
+ const existing = readJsonFile(markerPath) || {};
684
+ const stamp = pickEarliestStamp(existing.firstBlockAt || existing.at, firstBlockAt) || new Date().toISOString();
685
+ if (existing.firstBlockAt === stamp && existing.event) return;
686
+ fs.writeFileSync(markerPath, JSON.stringify({
687
+ ...existing,
688
+ at: existing.at || stamp,
689
+ firstBlockAt: stamp,
690
+ event: existing.event || 'first_block',
691
+ source: existing.source || source,
692
+ }), 'utf8');
693
+ } catch { }
694
+ }
695
+
696
+ function loadAccountActivations(baseFeedbackDir) {
697
+ const empty = { version: 1, adminFirstBlockAt: null, byCustomerId: {}, byEmailHash: {}, byInstallId: {} };
698
+ if (!baseFeedbackDir) return empty;
699
+ const raw = readJsonFile(path.join(baseFeedbackDir, ACCOUNT_ACTIVATIONS_FILENAME));
700
+ if (!raw || typeof raw !== 'object') return empty;
701
+ return {
702
+ version: 1,
703
+ adminFirstBlockAt: raw.adminFirstBlockAt || null,
704
+ byCustomerId: raw.byCustomerId && typeof raw.byCustomerId === 'object' ? raw.byCustomerId : {},
705
+ byEmailHash: raw.byEmailHash && typeof raw.byEmailHash === 'object' ? raw.byEmailHash : {},
706
+ byInstallId: raw.byInstallId && typeof raw.byInstallId === 'object' ? raw.byInstallId : {},
707
+ };
708
+ }
709
+
710
+ function saveAccountActivations(baseFeedbackDir, store) {
711
+ if (!baseFeedbackDir) return;
712
+ try {
713
+ fs.mkdirSync(baseFeedbackDir, { recursive: true });
714
+ fs.writeFileSync(path.join(baseFeedbackDir, ACCOUNT_ACTIVATIONS_FILENAME), JSON.stringify(store), 'utf8');
715
+ } catch { }
716
+ }
717
+
718
+ function upsertActivationEntry(map, key, firstBlockAt, source, maxKeys = 0) {
719
+ if (!key) return false;
720
+ const prev = map[key];
721
+ if (!prev && maxKeys > 0 && Object.keys(map).length >= maxKeys) return false;
722
+ const nextAt = pickEarliestStamp(prev && prev.firstBlockAt, firstBlockAt);
723
+ if (prev && prev.firstBlockAt === nextAt) return false;
724
+ map[key] = { firstBlockAt: nextAt, source: (prev && prev.source) || source || 'first_block' };
725
+ return true;
726
+ }
727
+
728
+ function recordHostedFirstBlock(baseFeedbackDir, params = {}) {
729
+ const stamp = params.firstBlockAt || new Date().toISOString();
730
+ const source = params.source || 'first_block';
731
+ const store = loadAccountActivations(baseFeedbackDir);
732
+ let changed = false;
733
+ if (params.isAdmin) {
734
+ const nextAdmin = pickEarliestStamp(store.adminFirstBlockAt, stamp);
735
+ if (store.adminFirstBlockAt !== nextAdmin) {
736
+ store.adminFirstBlockAt = nextAdmin;
737
+ changed = true;
738
+ }
739
+ writeActivationMarkerFile(baseFeedbackDir, nextAdmin, source);
740
+ }
741
+ if (upsertActivationEntry(store.byCustomerId, params.customerId, stamp, source)) changed = true;
742
+ if (upsertActivationEntry(store.byEmailHash, params.emailHash, stamp, source)) changed = true;
743
+ if (upsertActivationEntry(store.byInstallId, params.installId, stamp, source, 4096)) changed = true;
744
+ if (changed) saveAccountActivations(baseFeedbackDir, store);
745
+ if (params.tenantDir) writeActivationMarkerFile(params.tenantDir, stamp, source);
746
+ const resolved = (params.customerId && store.byCustomerId[params.customerId]?.firstBlockAt)
747
+ || (params.emailHash && store.byEmailHash[params.emailHash]?.firstBlockAt)
748
+ || (params.installId && store.byInstallId[params.installId]?.firstBlockAt)
749
+ || (params.isAdmin && store.adminFirstBlockAt)
750
+ || stamp;
751
+ return { firstBlockAt: resolved, store };
752
+ }
753
+
754
+ function statMtimeSafe(filePath) {
755
+ try { return fs.statSync(filePath).mtimeMs; } catch { return 0; }
756
+ }
757
+
758
+ function resolveFunnelPathForBackfill(baseFeedbackDir) {
759
+ return process.env._TEST_FUNNEL_LEDGER_PATH
760
+ || process.env.THUMBGATE_FUNNEL_LEDGER_PATH
761
+ || path.join(baseFeedbackDir, 'funnel-events.jsonl');
762
+ }
763
+
764
+ function collectTelemetryCliInstalls(baseFeedbackDir) {
765
+ const installs = new Map();
766
+ let earliestOwnerOrCli = null;
767
+ const telemetryRows = readJSONL(path.join(baseFeedbackDir, 'telemetry-pings.jsonl'), {
768
+ maxEntries: 100000,
769
+ maxBytes: 64 * 1024 * 1024,
770
+ });
771
+ for (const row of telemetryRows) {
772
+ if (!row || row.visitorType === 'bot' || row.visitorType === 'ci') continue;
773
+ const ev = String(row.eventType || row.event || '');
774
+ if (!CLI_ACTIVATION_EVENTS.has(ev) && row.clientType !== 'cli') continue;
775
+ const ts = row.firstBlockAt || row.timestamp || row.receivedAt || new Date().toISOString();
776
+ earliestOwnerOrCli = pickEarliestStamp(earliestOwnerOrCli, ts);
777
+ if (row.installId && installs.size < 4096) {
778
+ installs.set(row.installId, pickEarliestStamp(installs.get(row.installId), ts));
779
+ }
780
+ }
781
+ const funnelRows = readJSONL(resolveFunnelPathForBackfill(baseFeedbackDir), {
782
+ maxEntries: 50000,
783
+ maxBytes: 16 * 1024 * 1024,
784
+ });
785
+ const customerStamps = new Map();
786
+ for (const row of funnelRows) {
787
+ if (!row || row.stage !== 'activation' || row.event === 'api_key_first_usage') continue;
788
+ const ts = row.timestamp || row.createdAt || new Date().toISOString();
789
+ earliestOwnerOrCli = pickEarliestStamp(earliestOwnerOrCli, ts);
790
+ if (row.installId && installs.size < 4096) installs.set(row.installId, pickEarliestStamp(installs.get(row.installId), ts));
791
+ const cid = row.metadata && row.metadata.customerId;
792
+ if (cid) customerStamps.set(String(cid), pickEarliestStamp(customerStamps.get(String(cid)), ts));
793
+ }
794
+ return { installs, customerStamps, earliestOwnerOrCli };
795
+ }
796
+
797
+ function backfillHostedAccountActivations(baseFeedbackDir, opts = {}) {
798
+ if (!baseFeedbackDir) return { backfilled: 0 };
799
+ const keySig = Object.values((opts.keyStore && opts.keyStore.keys) || {})
800
+ .map((m) => `${m?.customerId || ''}|${m?.installId || ''}|${m?.active ? 1 : 0}|${m?.firstBlockAt ? 1 : 0}`).join(';');
801
+ const sig = [
802
+ statMtimeSafe(path.join(baseFeedbackDir, 'telemetry-pings.jsonl')),
803
+ statMtimeSafe(resolveFunnelPathForBackfill(baseFeedbackDir)),
804
+ statMtimeSafe(path.join(baseFeedbackDir, 'marketing-install-emails.jsonl')),
805
+ statMtimeSafe(path.join(baseFeedbackDir, 'account-activations.json')),
806
+ Boolean(opts.includeAdmin),
807
+ Boolean(opts.includeActivePaidKeys),
808
+ (opts.ownerEmails || []).join(','),
809
+ keySig,
810
+ ].join(':');
811
+ if (!opts.force && _backfillMtimeCache.get(baseFeedbackDir) === sig) {
812
+ return { backfilled: 0, cached: true };
813
+ }
814
+ const store = loadAccountActivations(baseFeedbackDir);
815
+ const { installs, customerStamps, earliestOwnerOrCli } = collectTelemetryCliInstalls(baseFeedbackDir);
816
+ let backfilled = 0;
817
+ for (const [installId, ts] of installs.entries()) {
818
+ if (upsertActivationEntry(store.byInstallId, installId, ts, 'telemetry_backfill')) backfilled += 1;
819
+ }
820
+ for (const [cid, ts] of customerStamps.entries()) {
821
+ if (upsertActivationEntry(store.byCustomerId, cid, ts, 'funnel_backfill')) backfilled += 1;
822
+ }
823
+ const hashEmail = typeof opts.hashEmail === 'function' ? opts.hashEmail : null;
824
+ const hashTenant = typeof opts.hashCustomerTenant === 'function' ? opts.hashCustomerTenant : null;
825
+ const emailRows = readJSONL(path.join(baseFeedbackDir, 'marketing-install-emails.jsonl'));
826
+ for (const row of emailRows) {
827
+ const email = String(row?.email || '').trim().toLowerCase();
828
+ const matchedAt = row?.installId && store.byInstallId[row.installId]?.firstBlockAt;
829
+ if (email && matchedAt && hashEmail) {
830
+ const emailHash = hashEmail(email);
831
+ if (upsertActivationEntry(store.byEmailHash, emailHash, matchedAt, 'install_email_backfill')) backfilled += 1;
832
+ writeActivationMarkerFile(path.join(baseFeedbackDir, 'tenants', emailHash), matchedAt, 'install_email_backfill');
833
+ }
834
+ }
835
+ const ownerStamp = earliestOwnerOrCli || new Date().toISOString();
836
+ for (const rawOwner of opts.ownerEmails || []) {
837
+ const ownerEmail = String(rawOwner || '').trim().toLowerCase();
838
+ if (ownerEmail && hashEmail) {
839
+ const emailHash = hashEmail(ownerEmail);
840
+ if (upsertActivationEntry(store.byEmailHash, emailHash, ownerStamp, 'owner_backfill')) backfilled += 1;
841
+ writeActivationMarkerFile(path.join(baseFeedbackDir, 'tenants', emailHash), ownerStamp, 'owner_backfill');
842
+ }
843
+ }
844
+ if (opts.includeAdmin || earliestOwnerOrCli) {
845
+ const nextAdmin = pickEarliestStamp(store.adminFirstBlockAt, ownerStamp);
846
+ if (store.adminFirstBlockAt !== nextAdmin) {
847
+ store.adminFirstBlockAt = nextAdmin;
848
+ backfilled += 1;
849
+ }
850
+ writeActivationMarkerFile(baseFeedbackDir, nextAdmin, 'owner_backfill');
851
+ }
852
+ const keys = (opts.keyStore && opts.keyStore.keys) || {};
853
+ for (const [key, meta] of Object.entries(keys)) {
854
+ if (!meta || !meta.active) continue;
855
+ const normEmail = String(meta.customerEmail || '').trim().toLowerCase();
856
+ const emailHash = normEmail && hashEmail ? hashEmail(normEmail) : null;
857
+ const isFree = String(meta.plan || '').toLowerCase() === 'free' || String(meta.tier || '').toLowerCase() === 'free';
858
+ const matchedStamp = meta.firstBlockAt
859
+ || (meta.installId && store.byInstallId[meta.installId]?.firstBlockAt)
860
+ || (meta.customerId && store.byCustomerId[meta.customerId]?.firstBlockAt)
861
+ || (emailHash && store.byEmailHash[emailHash]?.firstBlockAt)
862
+ || (!isFree && Number(meta.usageCount) > 0 ? (meta.createdAt || ownerStamp) : null)
863
+ || (opts.includeActivePaidKeys && !isFree ? (meta.createdAt || ownerStamp) : null);
864
+ if (!matchedStamp) continue;
865
+ if (meta.customerId && upsertActivationEntry(store.byCustomerId, meta.customerId, matchedStamp, 'account_backfill')) backfilled += 1;
866
+ if (emailHash && upsertActivationEntry(store.byEmailHash, emailHash, matchedStamp, 'account_backfill')) backfilled += 1;
867
+ if (!meta.firstBlockAt && typeof opts.recordKeyFirstBlock === 'function') {
868
+ opts.recordKeyFirstBlock({ apiKey: key }, { firstBlockAt: matchedStamp });
869
+ backfilled += 1;
870
+ }
871
+ if (meta.customerId && hashTenant) {
872
+ writeActivationMarkerFile(path.join(baseFeedbackDir, 'tenants', hashTenant(meta.customerId)), matchedStamp, 'account_backfill');
873
+ }
874
+ }
875
+ if (backfilled > 0) saveAccountActivations(baseFeedbackDir, store);
876
+ _backfillMtimeCache.set(baseFeedbackDir, sig);
877
+ return { backfilled, activatedInstalls: Object.keys(store.byInstallId).length };
878
+ }
879
+
880
+ function countRecordedGateBlocks(auditEntries, gateAudit, gateStats) {
881
+ let auditDenies = 0;
882
+ for (const ev of auditEntries) {
883
+ if (ev?.decision === 'deny' || ev?.decision === 'block') {
884
+ auditDenies += 1;
885
+ }
886
+ }
887
+ const seriesDenies = Number(gateAudit?.totals?.deny) || 0;
888
+ const statsBlocked = Number(gateStats?.blocked) || 0;
889
+ const topBlocked = Number(gateStats?.topBlockedCount) || 0;
890
+ return Math.max(auditDenies, seriesDenies, statsBlocked, topBlocked);
891
+ }
892
+
893
+ function computeTodayOverview(feedbackDir, options = {}) {
894
+ const memoryEntries = Array.isArray(options.memoryEntries) ? options.memoryEntries : readJSONL(path.join(feedbackDir, 'memory-log.jsonl'));
895
+ const auditEntries = Array.isArray(options.auditEntries) ? options.auditEntries : readJSONL(path.join(feedbackDir, AUDIT_LOG_FILENAME));
896
+ const gateStats = options.gateStats || computeGateStats(feedbackDir);
897
+ const gateAudit = options.gateAudit || computeGateAuditSeries(feedbackDir);
898
+
899
+ const todayBucket = Array.isArray(gateAudit.days) && gateAudit.days.length > 0
900
+ ? gateAudit.days[gateAudit.days.length - 1]
901
+ : { deny: 0, warn: 0, allow: 0 };
902
+ const gateStatusChips = {
903
+ blockedToday: Number(todayBucket.deny) || 0,
904
+ warnedToday: Number(todayBucket.warn) || 0,
905
+ activeGates: Number(gateStats.totalGates) || 0,
906
+ };
907
+
908
+ const totalGateBlocks = countRecordedGateBlocks(auditEntries, gateAudit, gateStats);
909
+ const marker = readActivationMarker(feedbackDir);
910
+ const firstBlockAt = options.firstBlockAt || marker?.firstBlockAt || marker?.blockedAt || null;
911
+ const paidAccount = isPaidSetupTier(options.tier);
912
+ const hasActivationOrHeartbeat = Boolean(firstBlockAt || marker || options.activationRecorded || options.cliHeartbeat);
913
+ const setupSignalKnown = options.setupSignalKnown !== false;
914
+ const firstBlockRecorded = totalGateBlocks > 0 || paidAccount || hasActivationOrHeartbeat;
915
+ const upNext = (!setupSignalKnown || firstBlockRecorded)
916
+ ? null
917
+ : {
918
+ kind: 'finish_setup',
919
+ kicker: 'Finish setup',
920
+ title: 'Finish setup to record your first gate block →',
921
+ detail: FINISH_SETUP_DETAIL,
922
+ command: FINISH_SETUP_COMMAND,
923
+ reward: 'Built-in safety rule pack + 3 custom block rules on Free tier (7-day local Pro trial included)',
924
+ actionLabel: 'Finish setup →',
925
+ actionTab: null,
926
+ actionHref: FINISH_SETUP_HREF,
927
+ };
928
+
929
+ return {
930
+ firstBlockRecorded,
931
+ firstBlockAt,
932
+ totalGateBlocks,
933
+ upNext,
934
+ gateStatusChips,
935
+ lessonStorage: computeLessonStorageSummary(feedbackDir, memoryEntries.length),
936
+ };
937
+ }
547
938
 
548
939
  function computePreventionImpact(feedbackDir, gateStats) {
549
- const autoGatesPath = getAutoGatesPath();
940
+ const autoGatesPath = getAutoGatesPath({ feedbackDir });
550
941
  const preventionRulesPath = path.join(feedbackDir, 'prevention-rules.md');
551
942
  let ruleCount = 0;
552
943
  if (fs.existsSync(preventionRulesPath)) {
@@ -555,17 +946,12 @@ function computePreventionImpact(feedbackDir, gateStats) {
555
946
  ruleCount = headers ? headers.length : 0;
556
947
  }
557
948
 
558
- // Estimate time saved: ~16 min per blocked action (conservative)
559
- // Based on: Claude Code review takes ~30 min, guard saves ~14 min
560
949
  const estimatedMinutesSaved = gateStats.blocked * 16;
561
950
  const estimatedHoursSaved = Number((estimatedMinutesSaved / 60).toFixed(1));
562
951
 
563
- // Estimate cost savings: $0.004 per blocked action (16 min @ $1.50/hr = 40 cents)
564
- // This is the cost of the agent time saved
565
- const estimatedCostSavingsCents = gateStats.blocked * (16 / 60) * 1.5 * 100; // 16min * $1.50/hr -> cents
952
+ const estimatedCostSavingsCents = gateStats.blocked * (16 / 60) * 1.5 * 100;
566
953
  const estimatedCostSavings = `$${(estimatedCostSavingsCents / 100).toFixed(2)}`;
567
954
 
568
- // Last auto-promotion
569
955
  const autoGates = readJsonFile(autoGatesPath);
570
956
  let lastPromotion = null;
571
957
  if (autoGates && Array.isArray(autoGates.promotionLog) && autoGates.promotionLog.length > 0) {
@@ -579,9 +965,7 @@ function computePreventionImpact(feedbackDir, gateStats) {
579
965
  }
580
966
  }
581
967
 
582
- // Feedback-to-gate conversion rate
583
- // How many blocked actions led to prevention rules — rate per blocked event
584
- const feedbackCount = gateStats.blocked; // denominator: blocked actions
968
+ const feedbackCount = gateStats.blocked;
585
969
  const conversionRate = feedbackCount > 0 ? Math.min(gateStats.totalGates / feedbackCount, 1) : 0;
586
970
 
587
971
  return {
@@ -595,62 +979,45 @@ function computePreventionImpact(feedbackDir, gateStats) {
595
979
  }
596
980
 
597
981
  function computeRoiSummary(gateStats, prevention, analytics, billing) {
598
- // North Star: Earn $100/day after-tax profit
599
- // ROI metrics that drive acquisition and retention
600
982
 
601
983
  const blockedActions = gateStats.blocked || 0;
602
984
  const warnedActions = gateStats.warned || 0;
603
985
  const passedActions = gateStats.passed || 0;
604
986
 
605
- // Time saved from blocked actions (16 min per block)
606
987
  const hoursSaved = prevention.estimatedHoursSaved || 0;
607
988
 
608
- // Conversion funnel effectiveness
609
989
  const funnel = analytics.funnel || {};
610
990
  const visitorToPaidRate = funnel.visitorToPaidRate || 0;
611
991
  const ctaToPaidRate = funnel.ctaToPaidRate || 0;
612
992
 
613
- // Revenue tracking — aligns with billing.js getBillingSummary: revenue.bookedRevenueCents
614
993
  const paidOrders = funnel.paidOrders || 0;
615
994
  const monthlyRevenueCents = billing.revenue ? billing.revenue.bookedRevenueCents || 0 : 0;
616
995
  const monthlyRevenue = monthlyRevenueCents / 100;
617
996
 
618
- // Prevention effectiveness: blocked actions per attempted action
619
997
  const totalActions = blockedActions + warnedActions + passedActions;
620
998
  const preventionRate = totalActions > 0 ? (blockedActions / totalActions) : 0;
621
999
 
622
- // PR merge efficiency (GitHub Label Archiving impact)
623
1000
  const decisionMetrics = analytics.decisionMetrics || {};
624
1001
  const prMergeRate = decisionMetrics.mergeRate || 0;
625
1002
 
626
1003
  return {
627
- // Cost savings from prevention (time-based ROI)
628
1004
  hoursSaved: Number(hoursSaved.toFixed(1)),
629
1005
  preventionRate: Number(preventionRate.toFixed(4)),
630
1006
  blockedActions,
631
1007
 
632
- // Conversion metrics (acquisition ROI)
633
1008
  visitorToPaidRate: Number((visitorToPaidRate * 100).toFixed(2)),
634
1009
  ctaToPaidRate: Number((ctaToPaidRate * 100).toFixed(2)),
635
1010
 
636
- // Revenue signals (retention/retention)
637
1011
  monthlyRevenue: Number(monthlyRevenue.toFixed(2)),
638
1012
  paidOrders,
639
1013
 
640
- // North Star tracking
641
- monthlyRevenueTarget: 3000, // $100/day after tax
1014
+ monthlyRevenueTarget: 3000,
642
1015
  revenueProgress: monthlyRevenue > 0 ? (monthlyRevenue / 3000 * 100).toFixed(1) : 0,
643
1016
 
644
- // Process efficiency (GitHub Label Archiving benefits)
645
1017
  prMergeRate: Number((prMergeRate * 100).toFixed(1)),
646
- // Higher merge rate = better process efficiency from archived labels reducing noise
647
1018
  };
648
1019
  }
649
1020
 
650
- // ---------------------------------------------------------------------------
651
- // Feedback time series (daily up/down for charts)
652
- // ---------------------------------------------------------------------------
653
-
654
1021
  function computeFeedbackTimeSeries(entries, dayCount = 30) {
655
1022
  const today = new Date();
656
1023
  today.setHours(0, 0, 0, 0);
@@ -682,10 +1049,6 @@ function isAuditTrailEntry(entry) {
682
1049
  return Array.isArray(entry.tags) && entry.tags.includes('audit-trail');
683
1050
  }
684
1051
 
685
- // ---------------------------------------------------------------------------
686
- // Lesson pipeline (feedback → lesson → gate conversion)
687
- // ---------------------------------------------------------------------------
688
-
689
1052
  function computeLessonPipeline(feedbackDir, entries, gateStats) {
690
1053
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
691
1054
  const memories = readJSONL(memoryLogPath);
@@ -701,7 +1064,7 @@ function computeLessonPipeline(feedbackDir, entries, gateStats) {
701
1064
  const errorLessons = memories.filter((m) => m.category === 'error').length;
702
1065
  const learningLessons = memories.filter((m) => m.category === 'learning').length;
703
1066
 
704
- const autoGatesPath = getAutoGatesPath();
1067
+ const autoGatesPath = getAutoGatesPath({ feedbackDir });
705
1068
  const autoGates = readJsonFile(autoGatesPath);
706
1069
  const promotedGates = autoGates && Array.isArray(autoGates.gates) ? autoGates.gates.length : 0;
707
1070
 
@@ -711,7 +1074,6 @@ function computeLessonPipeline(feedbackDir, entries, gateStats) {
711
1074
  ? Math.min(100, Math.round((promotedGates / totalLessons) * 100)) : 0;
712
1075
  const totalBlocked = gateStats.blocked || 0;
713
1076
 
714
- // Populate lesson counts onto the time series if available
715
1077
  const lessonsByDay = new Map();
716
1078
  for (const m of memories) {
717
1079
  if (!m.timestamp) continue;
@@ -734,10 +1096,6 @@ function computeLessonPipeline(feedbackDir, entries, gateStats) {
734
1096
  };
735
1097
  }
736
1098
 
737
- // ---------------------------------------------------------------------------
738
- // Session trend (last N sessions)
739
- // ---------------------------------------------------------------------------
740
-
741
1099
  function computeSessionTrend(entries, windowCount) {
742
1100
  if (entries.length < 10) return { bars: '', percentage: 0 };
743
1101
  const windowSize = Math.max(1, Math.floor(entries.length / windowCount));
@@ -754,10 +1112,6 @@ function computeSessionTrend(entries, windowCount) {
754
1112
  return { bars, percentage: avg };
755
1113
  }
756
1114
 
757
- // ---------------------------------------------------------------------------
758
- // System health
759
- // ---------------------------------------------------------------------------
760
-
761
1115
  function computeSystemHealth(feedbackDir, gateStats) {
762
1116
  const feedbackLogPath = path.join(feedbackDir, 'feedback-log.jsonl');
763
1117
  const memoryLogPath = path.join(feedbackDir, 'memory-log.jsonl');
@@ -770,7 +1124,7 @@ function computeSystemHealth(feedbackDir, gateStats) {
770
1124
  memoryCount,
771
1125
  gateConfigLoaded: gateStats.totalGates > 0,
772
1126
  gateCount: gateStats.totalGates,
773
- mcpServerRunning: true, // If dashboard is running, server is available
1127
+ mcpServerRunning: true,
774
1128
  };
775
1129
  }
776
1130
 
@@ -1029,14 +1383,14 @@ function computeAnalyticsSummary(feedbackDir, options = {}) {
1029
1383
  (entry) => entry && (entry.receivedAt || entry.timestamp)
1030
1384
  );
1031
1385
  const telemetry = getTelemetryAnalytics(feedbackDir, analyticsWindow);
1032
- const billing = options.billingSummary || getBillingSummary(analyticsWindow);
1386
+ const billing = tenantDataScope() ? {} : (options.billingSummary || getBillingSummary(analyticsWindow));
1033
1387
  const funnelEntries = filterEntriesForWindow(
1034
- loadFunnelLedger(),
1388
+ tenantDataScope() ? [] : loadFunnelLedger(),
1035
1389
  analyticsWindow,
1036
1390
  (entry) => entry && entry.timestamp
1037
1391
  );
1038
1392
  const paidOrderEntries = filterEntriesForWindow(
1039
- loadResolvedRevenueEvents(),
1393
+ tenantDataScope() ? [] : loadResolvedRevenueEvents(),
1040
1394
  analyticsWindow,
1041
1395
  (entry) => entry && entry.timestamp
1042
1396
  ).filter((entry) => entry && entry.status === 'paid');
@@ -1204,8 +1558,25 @@ function computeSecretGuardStats(diagnosticEntries) {
1204
1558
  });
1205
1559
 
1206
1560
  const byConstraint = {};
1561
+ const byType = {};
1562
+ const byService = {};
1563
+ let promptBlocks = 0;
1564
+
1207
1565
  for (const entry of secretEntries) {
1208
- const violations = entry.diagnosis && Array.isArray(entry.diagnosis.violations)
1566
+ if (entry.step === 'user_prompt_submit') {
1567
+ promptBlocks += 1;
1568
+ }
1569
+ const metaType = entry.metadata?.type ? String(entry.metadata.type) : null;
1570
+ const metaService = entry.metadata?.serviceGuess
1571
+ ? String(entry.metadata.serviceGuess)
1572
+ : null;
1573
+ if (metaType) {
1574
+ byType[metaType] = (byType[metaType] || 0) + 1;
1575
+ }
1576
+ if (metaService) {
1577
+ byService[metaService] = (byService[metaService] || 0) + 1;
1578
+ }
1579
+ const violations = Array.isArray(entry.diagnosis?.violations)
1209
1580
  ? entry.diagnosis.violations
1210
1581
  : [];
1211
1582
  for (const violation of violations) {
@@ -1219,6 +1590,10 @@ function computeSecretGuardStats(diagnosticEntries) {
1219
1590
 
1220
1591
  return {
1221
1592
  blocked: secretEntries.length,
1593
+ preventedLeaks: secretEntries.length,
1594
+ promptBlocks,
1595
+ byType,
1596
+ byService,
1222
1597
  topConstraint: topConstraint ? { key: topConstraint[0], count: topConstraint[1] } : null,
1223
1598
  recent: secretEntries
1224
1599
  .slice(-5)
@@ -1226,6 +1601,8 @@ function computeSecretGuardStats(diagnosticEntries) {
1226
1601
  .map((entry) => ({
1227
1602
  step: entry.step || null,
1228
1603
  source: entry.source || null,
1604
+ type: entry.metadata?.type || null,
1605
+ serviceGuess: entry.metadata?.serviceGuess || null,
1229
1606
  timestamp: entry.timestamp || null,
1230
1607
  })),
1231
1608
  };
@@ -1260,12 +1637,7 @@ function computeObservabilityStats(diagnosticEntries, diagnostics, secretGuard,
1260
1637
  };
1261
1638
  }
1262
1639
 
1263
- // ---------------------------------------------------------------------------
1264
- // Agent File Audit (high-ROI improvement for agent governance)
1265
- // ---------------------------------------------------------------------------
1266
-
1267
1640
  function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1268
- // Audit agent configuration files for governance compliance
1269
1641
  const auditResults = {
1270
1642
  totalAgentFiles: 0,
1271
1643
  auditPassCount: 0,
@@ -1274,7 +1646,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1274
1646
  lastAuditAt: new Date().toISOString(),
1275
1647
  };
1276
1648
 
1277
- // Find all agent/MCP configuration files
1278
1649
  const agentFilePatterns = [
1279
1650
  '.mcp.json',
1280
1651
  '.cursor/mcp.json',
@@ -1284,7 +1655,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1284
1655
 
1285
1656
  const agentFiles = [];
1286
1657
 
1287
- // Scan for agent files
1288
1658
  for (const pattern of agentFilePatterns) {
1289
1659
  const fullPath = path.join(projectRoot, pattern);
1290
1660
  if (fs.existsSync(fullPath)) {
@@ -1292,7 +1662,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1292
1662
  }
1293
1663
  }
1294
1664
 
1295
- // Check adapters directory for MCP configs
1296
1665
  const adaptersDir = path.join(projectRoot, 'adapters');
1297
1666
  if (fs.existsSync(adaptersDir)) {
1298
1667
  const entries = fs.readdirSync(adaptersDir, { withFileTypes: true });
@@ -1306,7 +1675,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1306
1675
  }
1307
1676
  }
1308
1677
 
1309
- // Check plugins directory
1310
1678
  const pluginsDir = path.join(projectRoot, 'plugins');
1311
1679
  if (fs.existsSync(pluginsDir)) {
1312
1680
  const entries = fs.readdirSync(pluginsDir, { withFileTypes: true });
@@ -1322,7 +1690,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1322
1690
 
1323
1691
  auditResults.totalAgentFiles = agentFiles.length;
1324
1692
 
1325
- // Audit each file for basic governance
1326
1693
  for (const file of agentFiles) {
1327
1694
  try {
1328
1695
  const content = fs.readFileSync(file.fullPath, 'utf-8');
@@ -1331,12 +1698,9 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1331
1698
  let auditPass = true;
1332
1699
  const issues = [];
1333
1700
 
1334
- // Check for required safety fields
1335
1701
  if (!config.permissions && !config.allowAllPermissions) {
1336
- // Not all configs require permissions, so this is optional
1337
1702
  }
1338
1703
 
1339
- // Check for proper command structure
1340
1704
  if (config.mcpServers) {
1341
1705
  for (const [name, server] of Object.entries(config.mcpServers)) {
1342
1706
  if (!server.command) {
@@ -1369,7 +1733,6 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1369
1733
  }
1370
1734
  }
1371
1735
 
1372
- // Check for server-card.json (MCP registry compatibility)
1373
1736
  const serverCardPath = path.join(projectRoot, '.well-known', 'mcp', 'server-card.json');
1374
1737
  if (fs.existsSync(serverCardPath)) {
1375
1738
  auditResults.serverCard = {
@@ -1381,13 +1744,9 @@ function computeAgentFileAudit(projectRoot = PROJECT_ROOT) {
1381
1744
  return auditResults;
1382
1745
  }
1383
1746
 
1384
- // ---------------------------------------------------------------------------
1385
- // Agent Surface Inventory for Pro Dashboard
1386
- // ---------------------------------------------------------------------------
1387
-
1388
1747
  function computeAgentFileAuditFromFeedback(feedbackDir, options = {}) {
1389
- const readiness = options.readiness || generateAgentReadinessReport({ projectRoot: PROJECT_ROOT });
1390
- const auditResults = computeAgentFileAudit();
1748
+ const readiness = options.readiness || generateAgentReadinessReport({ projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT });
1749
+ const auditResults = computeAgentFileAudit(tenantDataScope()?.feedbackDir || PROJECT_ROOT);
1391
1750
 
1392
1751
  return {
1393
1752
  totalAgentFiles: auditResults.totalAgentFiles,
@@ -1429,8 +1788,8 @@ function computeInstrumentationReadiness(analytics, billing) {
1429
1788
  plausibleConfigured: /plausible\.io\/js\/script(?:\.tagged-events)?\.js|\/js\/analytics\.js/.test(landingPage),
1430
1789
  ga4Configured: Boolean(runtimeConfig.gaMeasurementId),
1431
1790
  googleSearchConsoleConfigured: Boolean(runtimeConfig.googleSiteVerification),
1432
- softwareApplicationSchemaPresent: /"@type": "SoftwareApplication"/.test(landingPage),
1433
- faqSchemaPresent: /"@type": "FAQPage"/.test(landingPage),
1791
+ softwareApplicationSchemaPresent: /"@type"\s*:\s*"SoftwareApplication"/.test(landingPage),
1792
+ faqSchemaPresent: /"@type"\s*:\s*"FAQPage"/.test(landingPage),
1434
1793
  telemetryEventsPresent: (telemetry.totalEvents || 0) > 0,
1435
1794
  uniqueVisitorsTracked: visitors.uniqueVisitors || 0,
1436
1795
  rawTelemetryEvents: quality.rawEvents || telemetry.totalEvents || 0,
@@ -1652,7 +2011,7 @@ function summarizeMcpServerInventory(projectRoot = PROJECT_ROOT) {
1652
2011
  }
1653
2012
 
1654
2013
  function computeAgentSurfaceInventory(feedbackDir, options = {}) {
1655
- const readiness = options.readiness || generateAgentReadinessReport({ projectRoot: PROJECT_ROOT });
2014
+ const readiness = options.readiness || generateAgentReadinessReport({ projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT });
1656
2015
  const auditEntries = Array.isArray(options.auditEntries)
1657
2016
  ? options.auditEntries
1658
2017
  : readJSONL(path.join(feedbackDir, AUDIT_LOG_FILENAME));
@@ -1711,7 +2070,7 @@ function computeAgentSurfaceInventory(feedbackDir, options = {}) {
1711
2070
  .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))
1712
2071
  .map(([source, count]) => ({ source, count }))
1713
2072
  .slice(0, 6);
1714
- const mcpInventory = summarizeMcpServerInventory(PROJECT_ROOT);
2073
+ const mcpInventory = summarizeMcpServerInventory(tenantDataScope()?.feedbackDir || PROJECT_ROOT);
1715
2074
 
1716
2075
  return {
1717
2076
  profile: readiness.permissions.profile,
@@ -1724,7 +2083,6 @@ function computeAgentSurfaceInventory(feedbackDir, options = {}) {
1724
2083
  writeCapableTools: readiness.permissions.writeCapableTools.slice(0, 8),
1725
2084
  activeBootstrapFiles: readiness.bootstrap.requiredPresent,
1726
2085
  requiredBootstrapFiles: readiness.bootstrap.requiredCount,
1727
- // Merged from computeAgentFileAuditFromFeedback — audit pass/fail for dashboard
1728
2086
  ...(() => {
1729
2087
  const audit = computeAgentFileAuditFromFeedback(feedbackDir, options);
1730
2088
  return {
@@ -1797,11 +2155,7 @@ function resolveTeamWindowHours(analyticsWindow) {
1797
2155
  return 24;
1798
2156
  }
1799
2157
 
1800
- // ---------------------------------------------------------------------------
1801
- // Full dashboard data
1802
- // ---------------------------------------------------------------------------
1803
-
1804
- function collectAllFeedbackEntries(feedbackDir) {
2158
+ function collectLegacyFeedbackEntries(feedbackDir) {
1805
2159
  if (shouldAggregateFeedback()) {
1806
2160
  return collectAggregateLogEntries('feedback-log.jsonl', {
1807
2161
  feedbackDir,
@@ -1823,23 +2177,17 @@ function collectAllFeedbackEntries(feedbackDir) {
1823
2177
  }
1824
2178
  }
1825
2179
 
1826
- // Primary: the passed feedbackDir (global ~/.thumbgate)
1827
2180
  mergeFrom(path.join(feedbackDir, 'feedback-log.jsonl'));
1828
2181
 
1829
- // Project-local .thumbgate directories (e.g. repo/.thumbgate/feedback-log.jsonl)
1830
- // The MCP server may write to a project-scoped dir that differs from the global one.
1831
2182
  const projectsDir = path.join(feedbackDir, 'projects');
1832
2183
  if (fs.existsSync(projectsDir)) {
1833
2184
  try {
1834
2185
  for (const project of fs.readdirSync(projectsDir)) {
1835
2186
  mergeFrom(path.join(projectsDir, project, 'feedback-log.jsonl'));
1836
2187
  }
1837
- } catch { /* ignore read errors */ }
2188
+ } catch { }
1838
2189
  }
1839
2190
 
1840
- // Also check the project root's .thumbgate if feedbackDir is global
1841
- // The MCP server often resolves to PROJECT_ROOT/.thumbgate for project-scoped feedback
1842
- // Skip this merge when feedbackDir is a temp/test directory (not ~/.thumbgate)
1843
2191
  const homeThumbgate = path.join(process.env.HOME || '/tmp', '.thumbgate');
1844
2192
  const projectLocalDir = path.join(PROJECT_ROOT, '.thumbgate');
1845
2193
  if (
@@ -1850,7 +2198,6 @@ function collectAllFeedbackEntries(feedbackDir) {
1850
2198
  mergeFrom(path.join(projectLocalDir, 'feedback-log.jsonl'));
1851
2199
  }
1852
2200
 
1853
- // Sort by timestamp for consistent ordering
1854
2201
  entries.sort((a, b) => {
1855
2202
  const ta = a.timestamp ? new Date(a.timestamp).getTime() : 0;
1856
2203
  const tb = b.timestamp ? new Date(b.timestamp).getTime() : 0;
@@ -1860,10 +2207,18 @@ function collectAllFeedbackEntries(feedbackDir) {
1860
2207
  return entries;
1861
2208
  }
1862
2209
 
2210
+ function collectAllFeedbackEntries(feedbackDir, options = {}) {
2211
+ // Without a project selection keep reading every aggregate root, home store and legacy store.
2212
+ if (options.projectKey == null) return collectLegacyFeedbackEntries(feedbackDir);
2213
+ const rows = require('./project-catalog').readProjectRows(feedbackDir, 'feedback-log.jsonl', options);
2214
+ return shouldAggregateFeedback() ? normalizeDashboardFeedback(rows) : rows;
2215
+ }
2216
+
1863
2217
  function generateDashboard(feedbackDir, options = {}) {
2218
+ if (options.projectKey != null) return require('./project-dashboard').generateProjectDashboard(feedbackDir, options);
1864
2219
  const analyticsWindow = resolveAnalyticsWindow(options.analyticsWindow || options);
1865
2220
  const diagnosticLogPath = path.join(feedbackDir, 'diagnostic-log.jsonl');
1866
- const entries = collectAllFeedbackEntries(feedbackDir);
2221
+ const entries = selectDashboardFeedback(collectAllFeedbackEntries(feedbackDir), options.humanOnly);
1867
2222
  const diagnosticEntries = readJSONL(diagnosticLogPath);
1868
2223
  const memoryEntries = readJSONL(path.join(feedbackDir, 'memory-log.jsonl'));
1869
2224
  const auditEntries = readJSONL(path.join(feedbackDir, AUDIT_LOG_FILENAME));
@@ -1876,28 +2231,64 @@ function generateDashboard(feedbackDir, options = {}) {
1876
2231
  auditEntries,
1877
2232
  reviewedAt: options.now || new Date().toISOString(),
1878
2233
  });
1879
- const billingSummary = options.billingSummary || getBillingSummary(analyticsWindow);
2234
+ const billingSummary = tenantDataScope() ? {} : (options.billingSummary || getBillingSummary(analyticsWindow));
1880
2235
 
1881
2236
  const approval = computeApprovalStats(entries);
1882
- // Surface the "repeat-attempts blocked before execution" metric on the
1883
- // dashboard JSON and the /v1/dashboard HTTP route. Use the non-mutating
1884
- // helper (mirrors server-stdio.js) instead of mutating computeGateStats()'s
1885
- // return value. (mergeRepeatMetricIntoGateStats is imported at top of file.)
1886
- const gateStats = mergeRepeatMetricIntoGateStats(computeGateStats());
2237
+ const gateStats = mergeRepeatMetricIntoGateStats(computeGateStats(feedbackDir));
1887
2238
  const prevention = computePreventionImpact(feedbackDir, gateStats);
1888
2239
  const trend = computeSessionTrend(entries, 10);
1889
2240
  const health = computeSystemHealth(feedbackDir, gateStats);
1890
2241
  const gateAudit = computeGateAuditSeries(feedbackDir);
2242
+ const flowAudit = computeGateAuditSeries(feedbackDir, { dayCount: 30 });
2243
+ let flowTracked = false;
2244
+ let flowIncomplete = false;
2245
+ try {
2246
+ const tail = readTextTail(path.join(feedbackDir, AUDIT_LOG_FILENAME), DEFAULT_JSONL_MAX_BYTES);
2247
+ const lines = tail.text.split('\n');
2248
+ flowIncomplete = tail.truncated || lines.length >= DEFAULT_JSONL_MAX_ENTRIES;
2249
+ if (!flowIncomplete) {
2250
+ for (const line of lines) {
2251
+ if (!line.trim()) continue;
2252
+ const event = JSON.parse(line);
2253
+ if (!event || typeof event !== 'object' || Array.isArray(event)
2254
+ || typeof event.timestamp !== 'string' || !Number.isFinite(Date.parse(event.timestamp))
2255
+ || !['allow', 'deny', 'warn', 'approve', 'log', 'override'].includes(event.decision)) {
2256
+ flowIncomplete = true;
2257
+ break;
2258
+ }
2259
+ }
2260
+ }
2261
+ flowTracked = !flowIncomplete;
2262
+ } catch {
2263
+ flowIncomplete = fs.existsSync(path.join(feedbackDir, AUDIT_LOG_FILENAME));
2264
+ }
2265
+ const flowDays = new Set(flowAudit.days.map((day) => day.dayKey));
2266
+ const gateFlowStats = {
2267
+ tracked: flowTracked,
2268
+ incomplete: flowIncomplete,
2269
+ blockedToday: flowTracked ? flowAudit.days[flowAudit.days.length - 1].deny : null,
2270
+ blocked30Days: flowTracked ? flowAudit.totals.deny : null,
2271
+ allowed30Days: flowTracked ? flowAudit.totals.allow : null,
2272
+ blockedEntries: flowTracked ? auditEntries
2273
+ .filter((entry) => entry && entry.decision === 'deny' && flowDays.has(toLocalDayKey(entry.timestamp)))
2274
+ .sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp))
2275
+ .slice(0, 20)
2276
+ .map((entry) => ({
2277
+ timestamp: entry.timestamp,
2278
+ gateId: entry.gateId || null,
2279
+ toolName: entry.toolName || null,
2280
+ })) : [],
2281
+ };
1891
2282
  const diagnostics = aggregateFailureDiagnostics([...entries, ...diagnosticEntries]);
1892
2283
  const secretGuard = computeSecretGuardStats(diagnosticEntries);
1893
- const gates = listActiveGates();
2284
+ const gates = require('./project-catalog').readProjectGates(feedbackDir).filter((gate) => gate.active !== false).map((gate) => ({ ...gate, name: gate.name || gate.id || 'Gate', pattern: gate.pattern || '', action: gate.action || 'warn', severity: gate.severity || 'medium', layer: gate.layer || 'Execution', message: gate.message || null, source: gate.source || null, sourceLessonId: gate.sourceLessonId || null, sourceFeedbackId: gate.sourceFeedbackId || null, createdAt: gate.createdAt || null, promotedAt: gate.promotedAt || null, scopeLabel: gate.scope === 'global' ? 'Global' : 'Project' }));
1894
2285
  const analytics = computeAnalyticsSummary(feedbackDir, {
1895
2286
  analyticsWindow,
1896
2287
  billingSummary,
1897
2288
  });
1898
2289
  analytics.lossAnalysis = buildLossAnalysis(analytics);
1899
2290
  const observability = computeObservabilityStats(diagnosticEntries, diagnostics, secretGuard, analytics.telemetry);
1900
- const instrumentation = computeInstrumentationReadiness(analytics, billingSummary);
2291
+ const instrumentation = tenantDataScope() ? { availability: 'admin_only' } : computeInstrumentationReadiness(analytics, billingSummary);
1901
2292
  const delegationRuntime = loadDelegationRuntimeModule();
1902
2293
  const delegation = delegationRuntime
1903
2294
  ? delegationRuntime.summarizeDelegation(feedbackDir)
@@ -1908,9 +2299,10 @@ function generateDashboard(feedbackDir, options = {}) {
1908
2299
  activePlans: [],
1909
2300
  availability: 'private_core',
1910
2301
  };
1911
- const readiness = generateAgentReadinessReport({ projectRoot: PROJECT_ROOT });
2302
+ const readiness = generateAgentReadinessReport({ projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT });
1912
2303
  const feedbackAnalysis = analyzeFeedback(path.join(feedbackDir, 'feedback-log.jsonl'), {
1913
2304
  entries,
2305
+ humanOnly: options.humanOnly,
1914
2306
  maxLines: DEFAULT_JSONL_MAX_ENTRIES,
1915
2307
  maxBytes: DEFAULT_JSONL_MAX_BYTES,
1916
2308
  });
@@ -1926,18 +2318,18 @@ function generateDashboard(feedbackDir, options = {}) {
1926
2318
  auditEntries,
1927
2319
  decisionRecords,
1928
2320
  });
1929
- const settingsStatus = getSettingsStatus({ projectRoot: PROJECT_ROOT });
2321
+ const settingsStatus = getSettingsStatus({ projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT, ...(tenantDataScope() ? { homeDir: tenantDataScope().feedbackDir } : {}) });
1930
2322
  settingsStatus.routingPreview = {
1931
2323
  dashboardTool: routeProfile({
1932
2324
  toolName: 'dashboard',
1933
- settingsOptions: { projectRoot: PROJECT_ROOT },
2325
+ settingsOptions: { projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT, ...(tenantDataScope() ? { homeDir: tenantDataScope().feedbackDir } : {}) },
1934
2326
  }),
1935
2327
  defaultSession: routeProfile({
1936
- settingsOptions: { projectRoot: PROJECT_ROOT },
2328
+ settingsOptions: { projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT, ...(tenantDataScope() ? { homeDir: tenantDataScope().feedbackDir } : {}) },
1937
2329
  }),
1938
2330
  reviewSession: routeProfile({
1939
2331
  sessionType: 'review',
1940
- settingsOptions: { projectRoot: PROJECT_ROOT },
2332
+ settingsOptions: { projectRoot: tenantDataScope()?.feedbackDir || PROJECT_ROOT, ...(tenantDataScope() ? { homeDir: tenantDataScope().feedbackDir } : {}) },
1941
2333
  }),
1942
2334
  };
1943
2335
  const workflowSummary = summarizeWorkflowRuns(feedbackDir);
@@ -1951,7 +2343,6 @@ function generateDashboard(feedbackDir, options = {}) {
1951
2343
  readiness,
1952
2344
  );
1953
2345
 
1954
- // Live metrics — gate hit rate, lesson effectiveness, error trend
1955
2346
  const now = Date.now();
1956
2347
  const day = 24 * 60 * 60 * 1000;
1957
2348
  const weekAgo = now - 7 * day;
@@ -1959,7 +2350,7 @@ function generateDashboard(feedbackDir, options = {}) {
1959
2350
  const negRecent = recentEntries.filter((e) => ['down', 'negative', 'thumbs_down'].includes(String(e.signal || e.feedback || '').toLowerCase()));
1960
2351
  const posRecent = recentEntries.filter((e) => ['up', 'positive', 'thumbs_up'].includes(String(e.signal || e.feedback || '').toLowerCase()));
1961
2352
  const timestamps = entries.filter((e) => e.timestamp).map((e) => new Date(e.timestamp).getTime());
1962
- const daysActive = timestamps.length > 0 ? Math.max(1, Math.ceil((now - Math.min(...timestamps)) / day)) : 1;
2353
+ const daysActive = timestamps.length > 0 ? Math.max(1, Math.ceil((now - timestamps.reduce((oldest, stamp) => Math.min(oldest, stamp), Infinity)) / day)) : 1;
1963
2354
  const totalNeg = entries.filter((e) => ['down', 'negative', 'thumbs_down'].includes(String(e.signal || e.feedback || '').toLowerCase())).length;
1964
2355
  const autoGates = gateStats.autoCount || 0;
1965
2356
  const twoWeeksAgo = now - 14 * day;
@@ -1981,19 +2372,14 @@ function generateDashboard(feedbackDir, options = {}) {
1981
2372
  const feedbackTimeSeries = computeFeedbackTimeSeries(entries, 30);
1982
2373
  const lessonPipeline = computeLessonPipeline(feedbackDir, entries, gateStats);
1983
2374
 
1984
- // Estimated token savings — computed from gate blocked counts using the
1985
- // conservative methodology in scripts/token-savings.js. This is the ONLY
1986
- // place "$ saved" appears that's backed by real gate-block data; the landing
1987
- // page hero uses a hardcoded sample number disclosed as "Sample".
1988
2375
  let tokenSavings = null;
1989
2376
  try {
1990
2377
  const { computeTokenSavings } = require('./token-savings');
1991
2378
  tokenSavings = computeTokenSavings({
1992
2379
  blockedCalls: Number(gateStats.blocked) || 0,
1993
2380
  });
1994
- } catch { /* module missing — skip */ }
2381
+ } catch { }
1995
2382
 
1996
- // Merge lesson counts into feedbackTimeSeries days
1997
2383
  for (const day of feedbackTimeSeries.days) {
1998
2384
  day.lessons = lessonPipeline.lessonsByDay.get(day.dayKey) || 0;
1999
2385
  }
@@ -2008,17 +2394,35 @@ function generateDashboard(feedbackDir, options = {}) {
2008
2394
  })
2009
2395
  : buildUnavailableOrgDashboard(teamWindowHours);
2010
2396
  const templateLibrary = summarizeGateTemplates();
2011
- const predictive = buildPredictiveInsights({
2397
+ const predictive = tenantDataScope() ? { availability: 'admin_only' } : buildPredictiveInsights({
2012
2398
  telemetryAnalytics: analytics.telemetry,
2013
2399
  billingSummary,
2014
2400
  gateStats,
2015
2401
  team,
2016
2402
  });
2017
2403
  const reviewDelta = summarizeReviewDelta(entries, memoryEntries, auditEntries, reviewBaseline, reviewSnapshot);
2404
+ const todayOverview = computeTodayOverview(feedbackDir, {
2405
+ entries,
2406
+ memoryEntries,
2407
+ auditEntries,
2408
+ gateStats,
2409
+ gateAudit,
2410
+ gates,
2411
+ now: options.now,
2412
+ tier: options.tier,
2413
+ authContext: options.authContext,
2414
+ firstBlockAt: options.firstBlockAt,
2415
+ activationRecorded: options.activationRecorded,
2416
+ cliHeartbeat: options.cliHeartbeat,
2417
+ setupSignalKnown: options.setupSignalKnown,
2418
+ });
2419
+ const agentRegister = buildAgentRegister({
2420
+ dataDir: feedbackDir,
2421
+ windowDays: 30,
2422
+ now: options.now,
2423
+ });
2018
2424
 
2019
- // High-ROI metrics for North Star: $100/day after-tax profit
2020
2425
  const roiSummary = computeRoiSummary(gateStats, prevention, analytics, billingSummary);
2021
-
2022
2426
  return {
2023
2427
  operational: {
2024
2428
  source: options.billingSource || 'local',
@@ -2032,6 +2436,7 @@ function generateDashboard(feedbackDir, options = {}) {
2032
2436
  trend,
2033
2437
  health,
2034
2438
  gateAudit,
2439
+ gateFlowStats,
2035
2440
  diagnostics,
2036
2441
  delegation,
2037
2442
  secretGuard,
@@ -2043,6 +2448,7 @@ function generateDashboard(feedbackDir, options = {}) {
2043
2448
  feedbackAnalysis,
2044
2449
  actionableRemediations,
2045
2450
  agentSurfaceInventory,
2451
+ agentRegister,
2046
2452
  backgroundAgents,
2047
2453
  regulatedProof,
2048
2454
  interventionPolicy,
@@ -2055,6 +2461,7 @@ function generateDashboard(feedbackDir, options = {}) {
2055
2461
  reviewDelta,
2056
2462
  feedbackTimeSeries,
2057
2463
  tokenSavings,
2464
+ todayOverview,
2058
2465
  lessonPipeline: {
2059
2466
  stages: lessonPipeline.stages,
2060
2467
  rates: lessonPipeline.rates,
@@ -2062,10 +2469,6 @@ function generateDashboard(feedbackDir, options = {}) {
2062
2469
  };
2063
2470
  }
2064
2471
 
2065
- // ---------------------------------------------------------------------------
2066
- // Rich CLI output
2067
- // ---------------------------------------------------------------------------
2068
-
2069
2472
  function printDashboard(data) {
2070
2473
  const {
2071
2474
  approval,
@@ -2330,10 +2733,6 @@ function printDashboard(data) {
2330
2733
  console.log('');
2331
2734
  }
2332
2735
 
2333
- // ---------------------------------------------------------------------------
2334
- // Exports + CLI
2335
- // ---------------------------------------------------------------------------
2336
-
2337
2736
  module.exports = {
2338
2737
  generateDashboard,
2339
2738
  buildReviewSnapshot,
@@ -2341,8 +2740,16 @@ module.exports = {
2341
2740
  writeDashboardReviewState,
2342
2741
  printDashboard,
2343
2742
  computeApprovalStats,
2743
+ summarizeReviewDelta,
2344
2744
  computeDecisionMetrics,
2345
2745
  computeGateStats,
2746
+ computeTodayOverview,
2747
+ isPaidSetupTier,
2748
+ CLI_ACTIVATION_EVENTS,
2749
+ loadAccountActivations,
2750
+ recordHostedFirstBlock,
2751
+ backfillHostedAccountActivations,
2752
+ computeLessonStorageSummary,
2346
2753
  computePreventionImpact,
2347
2754
  computeRoiSummary,
2348
2755
  computeSessionTrend,