thumbgate 1.5.1 → 1.5.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.
@@ -0,0 +1,1399 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>ThumbGate Dashboard — Gate Stats, Approval Rate, Prevention Impact</title>
7
+ <meta name="description" content="Live dashboard showing gate enforcement stats, approval rate trends, prevention impact, and system health for ThumbGate pre-action gates.">
8
+ <link rel="canonical" href="https://thumbgate-production.up.railway.app/dashboard">
9
+ <meta name="robots" content="noindex">
10
+ <!-- Privacy-friendly analytics by Plausible -->
11
+ <script defer data-domain="thumbgate-production.up.railway.app" src="https://plausible.io/js/script.js"></script>
12
+ <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
13
+ <style>
14
+ *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
15
+ :root {
16
+ --bg: #0a0a0b; --bg-raised: #111113; --bg-card: #161618; --border: #222225;
17
+ --text: #e8e8ec; --text-muted: #8b8b96; --cyan: #22d3ee;
18
+ --cyan-dim: rgba(34,211,238,0.12); --green: #4ade80; --red: #f87171;
19
+ --font: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Inter', Roboto, sans-serif;
20
+ --mono: 'SF Mono', 'Cascadia Code', 'JetBrains Mono', 'Fira Code', Consolas, monospace;
21
+ }
22
+ html { scroll-behavior: smooth; }
23
+ body { font-family: var(--font); background: var(--bg); color: var(--text); line-height: 1.6; -webkit-font-smoothing: antialiased; }
24
+ .container { max-width: 1060px; margin: 0 auto; padding: 0 24px; }
25
+
26
+ /* NAV */
27
+ nav { position: sticky; top: 0; z-index: 50; background: rgba(10,10,11,0.85); backdrop-filter: blur(12px); border-bottom: 1px solid var(--border); padding: 14px 0; }
28
+ nav .container { display: flex; justify-content: space-between; align-items: center; }
29
+ .nav-logo { font-weight: 700; font-size: 15px; color: var(--text); text-decoration: none; }
30
+ .nav-links { display: flex; gap: 16px; align-items: center; }
31
+ .nav-links a { color: var(--text-muted); text-decoration: none; font-size: 13px; }
32
+ .nav-links a:hover { color: var(--text); }
33
+
34
+ /* AUTH */
35
+ .auth-bar { padding: 24px 0; border-bottom: 1px solid var(--border); margin-bottom: 32px; }
36
+ .auth-bar .container { display: flex; gap: 12px; align-items: center; }
37
+ .auth-input { flex: 1; max-width: 400px; background: var(--bg-raised); border: 1px solid var(--border); border-radius: 8px; padding: 10px 14px; color: var(--text); font-family: var(--mono); font-size: 13px; }
38
+ .auth-input:focus { outline: none; border-color: var(--cyan); }
39
+ .auth-input::placeholder { color: var(--text-muted); }
40
+ .btn { background: var(--cyan); color: var(--bg); padding: 10px 20px; border: none; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; }
41
+ .btn:hover { opacity: 0.85; }
42
+ .btn:disabled { opacity: 0.4; cursor: not-allowed; }
43
+ .auth-status { font-size: 13px; color: var(--text-muted); }
44
+ .auth-status.ok { color: var(--green); }
45
+ .auth-status.err { color: var(--red); }
46
+
47
+ /* STATS */
48
+ .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 32px; }
49
+ .stat-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 20px; transition: border-color 0.15s, background 0.15s, transform 0.1s; }
50
+ .stat-card:hover { border-color: rgba(34,211,238,0.4); transform: translateY(-2px); }
51
+ .stat-card.selected { border-color: rgba(34,211,238,0.6); background: rgba(34,211,238,0.05); }
52
+ .stat-label { font-size: 12px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 6px; }
53
+ .stat-value { font-size: 28px; font-weight: 700; letter-spacing: -0.02em; }
54
+ .stat-value.green { color: var(--green); }
55
+ .stat-value.red { color: var(--red); }
56
+ .stat-value.cyan { color: var(--cyan); }
57
+
58
+ /* SEARCH */
59
+ .search-section { margin-bottom: 32px; }
60
+ .search-bar { display: flex; gap: 12px; margin-bottom: 20px; }
61
+ .search-input { flex: 1; background: var(--bg-raised); border: 1px solid var(--border); border-radius: 8px; padding: 12px 16px; color: var(--text); font-size: 15px; }
62
+ .search-input:focus { outline: none; border-color: var(--cyan); }
63
+ .search-input::placeholder { color: var(--text-muted); }
64
+ .search-filters { display: flex; gap: 8px; margin-bottom: 16px; }
65
+ .filter-btn { background: var(--bg-raised); border: 1px solid var(--border); border-radius: 6px; padding: 6px 14px; color: var(--text-muted); font-size: 12px; cursor: pointer; }
66
+ .filter-btn:hover, .filter-btn.active { border-color: var(--cyan); color: var(--cyan); }
67
+
68
+ /* RESULTS */
69
+ .results { display: flex; flex-direction: column; gap: 12px; }
70
+ .result-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 20px; transition: border-color 0.15s; }
71
+ .result-card:hover { border-color: rgba(34,211,238,0.3); }
72
+ .result-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
73
+ .result-signal { display: inline-flex; align-items: center; gap: 4px; font-size: 13px; font-weight: 600; padding: 2px 8px; border-radius: 4px; }
74
+ .result-signal.up { background: rgba(74,222,128,0.12); color: var(--green); }
75
+ .result-signal.down { background: rgba(248,113,113,0.12); color: var(--red); }
76
+ .result-date { font-size: 12px; color: var(--text-muted); }
77
+ .result-title { font-size: 15px; font-weight: 600; margin-bottom: 6px; }
78
+ .result-context { font-size: 13px; color: var(--text-muted); line-height: 1.5; }
79
+ .result-tags { display: flex; gap: 6px; margin-top: 10px; flex-wrap: wrap; }
80
+ .tag { font-size: 11px; background: var(--cyan-dim); color: var(--cyan); padding: 2px 8px; border-radius: 4px; cursor: pointer; transition: background 0.15s, transform 0.1s; border: none; font-family: inherit; }
81
+ .tag:hover { background: rgba(34,211,238,0.25); transform: translateY(-1px); }
82
+ mark { background: rgba(34,211,238,0.25); color: var(--cyan); border-radius: 2px; padding: 0 2px; }
83
+
84
+ /* GATES */
85
+ .gates-section { margin-bottom: 32px; }
86
+ .gate-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 16px 20px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; }
87
+ .gate-name { font-size: 14px; font-weight: 600; }
88
+ .gate-pattern { font-size: 12px; color: var(--text-muted); font-family: var(--mono); margin-top: 4px; }
89
+ .gate-action { font-size: 12px; font-weight: 600; padding: 2px 8px; border-radius: 4px; }
90
+ .gate-action.block { background: rgba(248,113,113,0.12); color: var(--red); }
91
+ .gate-action.warn { background: rgba(251,191,36,0.12); color: #fbbf24; }
92
+
93
+ /* TEAM */
94
+ .team-section, .templates-section { margin-bottom: 40px; }
95
+ .team-grid, .template-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-bottom: 20px; }
96
+ .team-card, .template-card, .panel { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 18px; }
97
+ .panel h3, .template-card h3 { font-size: 15px; margin-bottom: 10px; }
98
+ .team-kicker { font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 6px; }
99
+ .team-value { font-size: 28px; font-weight: 700; color: var(--cyan); letter-spacing: -0.03em; }
100
+ .team-note { font-size: 13px; color: var(--text-muted); margin-top: 6px; }
101
+ .team-columns { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
102
+ .risk-row, .blocked-row, .template-meta { display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; }
103
+ .risk-row, .blocked-row { padding: 10px 0; border-bottom: 1px solid var(--border); }
104
+ .risk-row:last-child, .blocked-row:last-child { border-bottom: none; }
105
+ .risk-name, .blocked-name { font-size: 14px; font-weight: 600; }
106
+ .risk-meta, .blocked-meta, .template-copy { font-size: 12px; color: var(--text-muted); }
107
+ .template-copy { margin: 8px 0 12px; line-height: 1.6; }
108
+ .template-meta { margin-bottom: 8px; }
109
+ .template-pill { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; border-radius: 999px; padding: 4px 10px; background: var(--bg-raised); color: var(--text-muted); border: 1px solid var(--border); margin-right: 8px; margin-bottom: 8px; }
110
+ .template-pattern { font-family: var(--mono); font-size: 12px; color: var(--text-muted); background: var(--bg-raised); padding: 10px 12px; border-radius: 8px; overflow-x: auto; }
111
+ .template-summary { font-size: 13px; color: var(--text-muted); margin-bottom: 16px; }
112
+ .generated-toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
113
+ .generated-view-btn { background: var(--bg-raised); border: 1px solid var(--border); border-radius: 999px; padding: 8px 14px; color: var(--text-muted); font-size: 12px; font-weight: 600; cursor: pointer; }
114
+ .generated-view-btn:hover, .generated-view-btn.active { border-color: var(--cyan); color: var(--cyan); }
115
+ .generated-canvas { display: flex; flex-direction: column; gap: 16px; }
116
+ .generated-section-title { font-size: 15px; margin-bottom: 12px; }
117
+ .generated-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
118
+ .generated-list { display: flex; flex-direction: column; gap: 10px; }
119
+ .generated-list-row { display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; padding: 10px 0; border-bottom: 1px solid var(--border); }
120
+ .generated-list-row:last-child { border-bottom: none; padding-bottom: 0; }
121
+ .generated-list-title { font-size: 14px; font-weight: 600; }
122
+ .generated-list-subtitle { font-size: 12px; color: var(--text-muted); line-height: 1.55; margin-top: 4px; }
123
+ .generated-badge { display: inline-flex; align-items: center; border-radius: 999px; padding: 4px 10px; font-size: 11px; font-weight: 700; background: var(--bg-raised); color: var(--text-muted); border: 1px solid var(--border); white-space: nowrap; }
124
+ .generated-callout.warning { border-color: rgba(251,191,36,0.35); background: rgba(251,191,36,0.06); }
125
+ .generated-callout.danger { border-color: rgba(248,113,113,0.35); background: rgba(248,113,113,0.06); }
126
+ .generated-callout.success { border-color: rgba(74,222,128,0.35); background: rgba(74,222,128,0.06); }
127
+
128
+ /* EXPORT */
129
+ .export-section { margin-bottom: 48px; }
130
+ .export-btn { background: var(--bg-raised); border: 1px solid var(--border); border-radius: 8px; padding: 12px 20px; color: var(--text); font-size: 14px; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: border-color 0.15s; }
131
+ .export-btn:hover { border-color: var(--cyan); color: var(--cyan); }
132
+
133
+ /* TABS */
134
+ .tabs { display: flex; gap: 0; border-bottom: 1px solid var(--border); margin-bottom: 24px; }
135
+ .tab { padding: 12px 20px; font-size: 14px; font-weight: 500; color: var(--text-muted); cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; }
136
+ .tab:hover { color: var(--text); }
137
+ .tab.active { color: var(--cyan); border-bottom-color: var(--cyan); }
138
+ .tab-content { display: none; }
139
+ .tab-content.active { display: block; }
140
+
141
+ .btn-outline { background: transparent; color: var(--cyan); border: 1px solid var(--cyan); padding: 10px 20px; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; }
142
+ .btn-outline:hover { background: var(--cyan-dim); }
143
+ .demo-badge { background: var(--cyan-dim); color: var(--cyan); font-size: 11px; font-weight: 600; padding: 3px 8px; border-radius: 4px; margin-left: 10px; }
144
+ .demo-banner { background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; padding: 16px 20px; margin-bottom: 24px; font-size: 14px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
145
+ .demo-banner a { color: var(--cyan); text-decoration: none; font-weight: 600; }
146
+ .demo-banner a:hover { text-decoration: underline; }
147
+
148
+ .empty { text-align: center; padding: 48px; color: var(--text-muted); font-size: 15px; }
149
+ .loading { text-align: center; padding: 24px; color: var(--text-muted); }
150
+ h2 { font-size: 20px; font-weight: 700; margin-bottom: 16px; letter-spacing: -0.02em; }
151
+ .settings-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 16px; margin-bottom: 24px; }
152
+ .settings-card, .origin-row, .layer-row, .routing-row { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 16px; }
153
+ .layer-row, .routing-row, .origin-row { display: flex; justify-content: space-between; gap: 16px; align-items: flex-start; margin-bottom: 12px; }
154
+ .scope-pill { display: inline-flex; align-items: center; border-radius: 999px; padding: 3px 10px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; background: var(--cyan-dim); color: var(--cyan); }
155
+ .settings-card .team-kicker, .origin-path, .routing-name, .layer-name { font-family: var(--mono); font-size: 12px; color: var(--text-muted); }
156
+ .settings-card .team-value, .origin-value { font-size: 18px; font-weight: 700; color: var(--text); margin-top: 8px; word-break: break-word; }
157
+ .origin-list, .layer-list, .routing-list { display: flex; flex-direction: column; gap: 12px; }
158
+ .origin-note, .layer-note, .routing-note { font-size: 13px; color: var(--text-muted); line-height: 1.55; }
159
+
160
+ @media (max-width: 700px) {
161
+ .stats-grid { grid-template-columns: repeat(2, 1fr); }
162
+ .search-filters { flex-wrap: wrap; }
163
+ .team-grid, .template-grid, .team-columns, .settings-grid, .generated-grid { grid-template-columns: 1fr; }
164
+ }
165
+ </style>
166
+ </head>
167
+ <body>
168
+
169
+ <nav>
170
+ <div class="container">
171
+ <a href="/" class="nav-logo">👍👎 ThumbGate Dashboard</a>
172
+ <div class="nav-links">
173
+ <a href="/dashboard" class="active" style="color:var(--cyan);">Dashboard</a>
174
+ <a href="/lessons">Lessons</a>
175
+ <a href="/">Landing Page</a>
176
+ <a href="https://github.com/IgorGanapolsky/ThumbGate" target="_blank" rel="noopener">GitHub</a>
177
+ </div>
178
+ </div>
179
+ </nav>
180
+
181
+ <div class="auth-bar">
182
+ <div class="container">
183
+ <div style="margin-bottom:10px;">
184
+ <span style="font-size:14px;font-weight:600;">Connect your API key</span>
185
+ <span id="authHelp" style="font-size:13px;color:var(--text-muted);margin-left:8px;">Pro auto-connects locally when you launch with <code style="font-family:var(--mono);font-size:12px;background:var(--cyan-dim);color:var(--cyan);padding:2px 6px;border-radius:4px;">npx thumbgate pro</code>. Otherwise paste your <code style="font-family:var(--mono);font-size:12px;background:var(--cyan-dim);color:var(--cyan);padding:2px 6px;border-radius:4px;">THUMBGATE_API_KEY</code> manually.</span>
186
+ </div>
187
+ <div style="display:flex;gap:12px;align-items:center;">
188
+ <input type="password" class="auth-input" id="apiKey" placeholder="Paste your API key here (THUMBGATE_API_KEY or THUMBGATE_PRO_KEY)..." />
189
+ <button class="btn" id="connectBtn" onclick="connect()">Connect</button>
190
+ <button class="btn-outline" id="demoBtn" onclick="loadDemo()">Try Demo</button>
191
+ <span class="auth-status" id="authStatus"></span>
192
+ </div>
193
+ </div>
194
+ </div>
195
+
196
+ <div class="container" id="dashboardContent" style="display:none;">
197
+
198
+ <div style="margin:0 0 24px;padding:24px;background:linear-gradient(135deg,rgba(34,211,238,0.08),rgba(74,222,128,0.05));border:1px solid rgba(34,211,238,0.2);border-radius:12px;">
199
+ <h1 style="font-size:22px;font-weight:700;margin-bottom:8px;letter-spacing:-0.02em;">🔍 Operations Dashboard</h1>
200
+ <p style="font-size:14px;color:var(--text-muted);line-height:1.6;max-width:700px;">What's happening right now? Search memories, inspect active gates, manage your team, and export training data. <span style="color:var(--cyan);font-weight:600;">This is your control plane for AI agent behavior.</span></p>
201
+ <div style="display:flex;gap:16px;margin-top:12px;font-size:12px;color:var(--text-muted);">
202
+ <span>🔍 <strong style="color:var(--text);">Search</strong> — find any memory</span>
203
+ <span>🛡️ <strong style="color:var(--text);">Gates</strong> — what's blocking</span>
204
+ <span>👥 <strong style="color:var(--text);">Team</strong> — org metrics</span>
205
+ <span>📤 <strong style="color:var(--text);">Export</strong> — DPO training data</span>
206
+ </div>
207
+ </div>
208
+
209
+ <div class="demo-banner" id="demoBanner" style="display:none;">
210
+ <span>📊 <strong>Demo Mode</strong> — sample data. Pro unlocks your personal dashboard with search, DPO export, and gate analytics.</span>
211
+ <a href="https://buy.stripe.com/7sYcN5bmIf5IcSd8qf3sI0a" target="_blank" rel="noopener" style="background:#b85c2d;color:#fff;padding:6px 14px;border-radius:8px;text-decoration:none;font-weight:700;white-space:nowrap;">Start 7-day free trial</a>
212
+ </div>
213
+
214
+ <!-- STATS -->
215
+ <div class="stats-grid" id="statsGrid">
216
+ <a class="stat-card" data-card-action="all" onclick="selectCard(this,'all')" href="/lessons" style="cursor:pointer;text-decoration:none;color:inherit;display:block;" title="Click to view all feedback → Lessons page"><div class="stat-label">Total Feedback</div><div class="stat-value cyan" id="statTotal">—</div></a>
217
+ <a class="stat-card" data-card-action="up" onclick="selectCard(this,'up')" href="/lessons?signal=positive" style="cursor:pointer;text-decoration:none;color:inherit;display:block;" title="Click to view positive feedback → Lessons page"><div class="stat-label">👍 Positive</div><div class="stat-value green" id="statPositive">—</div></a>
218
+ <a class="stat-card" data-card-action="down" onclick="selectCard(this,'down')" href="/lessons?signal=negative" style="cursor:pointer;text-decoration:none;color:inherit;display:block;" title="Click to view negative feedback → Lessons page"><div class="stat-label">👎 Negative</div><div class="stat-value red" id="statNegative">—</div></a>
219
+ <a class="stat-card" data-card-action="gates" onclick="selectCard(this,'gates');return false;" href="#" style="cursor:pointer;text-decoration:none;color:inherit;display:block;" title="Click to view active gates"><div class="stat-label">Active Gates</div><div class="stat-value cyan" id="statGates">—</div></a>
220
+ </div>
221
+
222
+ <!-- TABS -->
223
+ <div class="tabs">
224
+ <div class="tab active" onclick="switchTab('search')">🔍 Search Memories</div>
225
+ <div class="tab" onclick="switchTab('gates')">🛡️ Active Gates</div>
226
+ <div class="tab" onclick="switchTab('team')">👥 Team</div>
227
+ <div class="tab" onclick="switchTab('generated')">🧩 Generated Views</div>
228
+ <div class="tab" onclick="switchTab('settings')">⚙️ Policy Origins</div>
229
+ <div class="tab" onclick="switchTab('templates')">🧱 Gate Templates</div>
230
+ <div class="tab" onclick="switchTab('insights')">📊 Insights</div>
231
+ <div class="tab" onclick="switchTab('export')">📦 Export</div>
232
+ </div>
233
+
234
+ <!-- SEARCH TAB -->
235
+ <div class="tab-content active" id="tab-search">
236
+ <div class="search-section">
237
+ <div class="search-bar">
238
+ <input type="text" class="search-input" id="searchQuery" placeholder="Search memories... (try: git, test, deploy, secrets, database)" onkeydown="if(event.key==='Enter')search()" />
239
+ <button class="btn" onclick="search()">Search</button>
240
+ </div>
241
+ <div class="search-filters">
242
+ <button class="filter-btn active" data-source="all" onclick="setSource(this,'all')">All</button>
243
+ <button class="filter-btn" data-source="feedback" onclick="setSource(this,'feedback')">Feedback</button>
244
+ <button class="filter-btn" data-source="context" onclick="setSource(this,'context')">Context</button>
245
+ <button class="filter-btn" data-source="rules" onclick="setSource(this,'rules')">Rules</button>
246
+ </div>
247
+ <div class="results" id="searchResults">
248
+ <div class="empty">Enter a query to search your memories</div>
249
+ </div>
250
+ </div>
251
+ </div>
252
+
253
+ <!-- GATES TAB -->
254
+ <div class="tab-content" id="tab-gates">
255
+ <div class="gates-section">
256
+ <h2>Active Pre-Action Gates</h2>
257
+ <div id="gatesList"><div class="loading">Loading gates...</div></div>
258
+ </div>
259
+ </div>
260
+
261
+ <!-- TEAM TAB -->
262
+ <div class="tab-content" id="tab-team">
263
+ <div class="team-section">
264
+ <h2>Shared Team Reliability</h2>
265
+ <p class="template-summary">See which agents drift, which gates save the team the most time, and whether the shared workflow is getting safer.</p>
266
+ <div class="team-grid" id="teamSummaryCards"><div class="loading">Loading team metrics...</div></div>
267
+ <div class="team-grid" id="predictiveSummaryCards"><div class="loading">Loading predictive insights...</div></div>
268
+ <div class="team-columns">
269
+ <div class="panel">
270
+ <h3>Highest-Risk Agents</h3>
271
+ <div id="teamRiskAgents"><div class="loading">Loading agent risk...</div></div>
272
+ </div>
273
+ <div class="panel">
274
+ <h3>Top Blocked Gates</h3>
275
+ <div id="teamBlockedGates"><div class="loading">Loading blocked gates...</div></div>
276
+ </div>
277
+ </div>
278
+ <div class="panel" style="margin-top:16px;">
279
+ <h3>Predictive Watchlist</h3>
280
+ <div id="predictiveAnomalies"><div class="loading">Loading predictive watchlist...</div></div>
281
+ </div>
282
+ </div>
283
+ </div>
284
+
285
+ <!-- GENERATED TAB -->
286
+ <div class="tab-content" id="tab-generated">
287
+ <div class="templates-section">
288
+ <h2>Generated Hosted Views</h2>
289
+ <p class="template-summary" id="generatedViewSummary">A constrained JSON spec builds opinionated review dashboards from approved cards, lists, and callouts.</p>
290
+ <div class="generated-toolbar" id="generatedViewToolbar"><div class="loading">Loading generated views...</div></div>
291
+ <div class="generated-canvas" id="generatedViewCanvas"><div class="loading">Loading generated view...</div></div>
292
+ </div>
293
+ </div>
294
+
295
+ <!-- SETTINGS TAB -->
296
+ <div class="tab-content" id="tab-settings">
297
+ <div class="templates-section">
298
+ <h2>Policy Origins</h2>
299
+ <div class="template-summary" id="settingsSummary">Loading settings hierarchy...</div>
300
+ <div class="settings-grid" id="settingsSummaryCards"><div class="loading">Loading settings summary...</div></div>
301
+ <div class="team-columns">
302
+ <div class="panel">
303
+ <h3>Layer Precedence</h3>
304
+ <div class="layer-list" id="settingsLayers"><div class="loading">Loading layers...</div></div>
305
+ </div>
306
+ <div class="panel">
307
+ <h3>Routing Preview</h3>
308
+ <div class="routing-list" id="settingsRouting"><div class="loading">Loading routing...</div></div>
309
+ </div>
310
+ </div>
311
+ <div class="panel">
312
+ <h3>Resolved Setting Origins</h3>
313
+ <div class="origin-list" id="settingsOrigins"><div class="loading">Loading settings origins...</div></div>
314
+ </div>
315
+ </div>
316
+ </div>
317
+
318
+ <!-- TEMPLATES TAB -->
319
+ <div class="tab-content" id="tab-templates">
320
+ <div class="templates-section">
321
+ <h2>Curated Gate Templates</h2>
322
+ <div class="template-summary" id="templateSummary">Loading template library...</div>
323
+ <div class="template-grid" id="templateLibrary"><div class="loading">Loading templates...</div></div>
324
+ </div>
325
+ </div>
326
+
327
+ <!-- INSIGHTS TAB -->
328
+ <div class="tab-content" id="tab-insights">
329
+ <div class="templates-section">
330
+ <h2>📊 Feedback Insights &amp; Lesson Pipeline</h2>
331
+ <p class="template-summary">How your thumbs-up/down signals turn into lessons that prevent repeat mistakes.</p>
332
+
333
+ <!-- Pipeline Flow -->
334
+ <div class="panel" style="margin-bottom:24px;">
335
+ <h3 style="margin-bottom:16px;">Feedback → Lesson Pipeline</h3>
336
+ <div id="pipelineFlow" style="display:flex;align-items:center;justify-content:center;gap:0;flex-wrap:wrap;padding:12px 0;">
337
+ <div class="loading">Loading pipeline...</div>
338
+ </div>
339
+ <div id="pipelineRates" style="display:flex;gap:24px;justify-content:center;margin-top:16px;font-size:13px;color:var(--text-muted);"></div>
340
+ </div>
341
+
342
+ <!-- Charts -->
343
+ <div class="team-columns" style="margin-bottom:24px;">
344
+ <div class="panel">
345
+ <h3>Feedback Trend (30 days)</h3>
346
+ <div style="position:relative;height:260px;margin-top:12px;">
347
+ <canvas id="feedbackTrendChart"></canvas>
348
+ </div>
349
+ </div>
350
+ <div class="panel">
351
+ <h3>Lessons Generated (30 days)</h3>
352
+ <div style="position:relative;height:260px;margin-top:12px;">
353
+ <canvas id="lessonTrendChart"></canvas>
354
+ </div>
355
+ </div>
356
+ </div>
357
+
358
+ <!-- Gate Effectiveness -->
359
+ <div class="panel" style="margin-bottom:24px;">
360
+ <h3>Gate Effectiveness (14-day audit)</h3>
361
+ <div style="position:relative;height:280px;margin-top:12px;">
362
+ <canvas id="gateAuditChart"></canvas>
363
+ </div>
364
+ </div>
365
+
366
+ <!-- How It Works -->
367
+ <div class="panel">
368
+ <h3 style="margin-bottom:12px;">How ThumbGate Learns</h3>
369
+ <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;text-align:center;">
370
+ <div>
371
+ <div style="font-size:32px;margin-bottom:8px;">👎👍</div>
372
+ <div style="font-size:13px;font-weight:600;margin-bottom:4px;">1. You React</div>
373
+ <div style="font-size:12px;color:var(--text-muted);">Thumbs-down on a bad action, thumbs-up on a good one</div>
374
+ </div>
375
+ <div>
376
+ <div style="font-size:32px;margin-bottom:8px;">🧠</div>
377
+ <div style="font-size:13px;font-weight:600;margin-bottom:4px;">2. Lesson Distilled</div>
378
+ <div style="font-size:12px;color:var(--text-muted);">ThumbGate extracts what went wrong and how to avoid it</div>
379
+ </div>
380
+ <div>
381
+ <div style="font-size:32px;margin-bottom:8px;">🛡️</div>
382
+ <div style="font-size:13px;font-weight:600;margin-bottom:4px;">3. Gate Promoted</div>
383
+ <div style="font-size:12px;color:var(--text-muted);">Repeated lessons auto-promote into pre-action gates</div>
384
+ </div>
385
+ <div>
386
+ <div style="font-size:32px;margin-bottom:8px;">🚫</div>
387
+ <div style="font-size:13px;font-weight:600;margin-bottom:4px;">4. Mistake Blocked</div>
388
+ <div style="font-size:12px;color:var(--text-muted);">Gates intercept the same mistake before it happens again</div>
389
+ </div>
390
+ </div>
391
+ </div>
392
+ </div>
393
+ </div>
394
+
395
+ <!-- EXPORT TAB -->
396
+ <div class="tab-content" id="tab-export">
397
+ <div class="export-section">
398
+ <h2>Export Training Data (DPO)</h2>
399
+ <div style="background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;margin-bottom:24px;max-width:640px;">
400
+ <h3 style="font-size:15px;margin-bottom:8px;">What is DPO?</h3>
401
+ <p style="color:var(--text-muted);font-size:14px;line-height:1.65;margin-bottom:12px;"><strong style="color:var(--text);">Direct Preference Optimization</strong> is a technique for fine-tuning LLMs using human preference data. Your 👍/👎 feedback is converted into training pairs:</p>
402
+ <div style="background:var(--bg-raised);border-radius:8px;padding:16px;font-family:var(--mono);font-size:13px;line-height:1.6;margin-bottom:12px;">
403
+ <div><span style="color:var(--green);">👍 "chosen"</span> — the response that worked</div>
404
+ <div><span style="color:var(--red);">👎 "rejected"</span> — the response that failed</div>
405
+ </div>
406
+ <p style="color:var(--text-muted);font-size:14px;line-height:1.65;">Use these pairs to fine-tune any model (OpenAI, Llama, Mistral) so it <strong style="color:var(--text);">actually learns from your corrections</strong> — not just blocks mistakes, but stops making them.</p>
407
+ </div>
408
+ <button class="export-btn" onclick="exportDpo()">📥 Download DPO Pairs (JSON)</button>
409
+ <div id="exportStatus" style="margin-top:12px;font-size:13px;color:var(--text-muted);"></div>
410
+ </div>
411
+ </div>
412
+
413
+ </div>
414
+
415
+ <script>
416
+ let API_KEY = '';
417
+ let currentSource = 'all';
418
+ let isDemo = false;
419
+ let demoData = [];
420
+ let dashboardSnapshot = null;
421
+ let currentGeneratedView = 'team-review';
422
+ const BOOTSTRAP_API_KEY = __DASHBOARD_BOOTSTRAP_KEY__;
423
+ const LOCAL_PRO_BOOTSTRAP = __DASHBOARD_BOOTSTRAP_ENABLED__;
424
+
425
+ function getHeaders() {
426
+ return { 'Authorization': 'Bearer ' + API_KEY, 'Content-Type': 'application/json' };
427
+ }
428
+
429
+ function hasBootstrapKey() {
430
+ return LOCAL_PRO_BOOTSTRAP && Boolean(BOOTSTRAP_API_KEY);
431
+ }
432
+
433
+ async function connect(options) {
434
+ var opts = options || {};
435
+ var input = document.getElementById('apiKey');
436
+ API_KEY = String(opts.key || input.value || '').trim();
437
+ if (!API_KEY) return;
438
+ const status = document.getElementById('authStatus');
439
+ const btn = document.getElementById('connectBtn');
440
+ btn.disabled = true;
441
+ status.className = 'auth-status';
442
+ status.textContent = opts.localPro ? 'Connecting local dashboard...' : 'Connecting...';
443
+ try {
444
+ const res = await fetch('/v1/feedback/stats', { headers: getHeaders() });
445
+ if (!res.ok) throw new Error('Invalid API key');
446
+ const data = await res.json();
447
+ status.className = 'auth-status ok';
448
+ status.textContent = opts.localPro ? '✓ Local Pro dashboard connected' : '✓ Connected';
449
+ document.getElementById('dashboardContent').style.display = 'block';
450
+ if (opts.localPro) {
451
+ input.value = 'local-license';
452
+ input.disabled = true;
453
+ input.placeholder = 'Local Pro auto-connected';
454
+ btn.disabled = true;
455
+ document.getElementById('demoBtn').style.display = 'none';
456
+ document.getElementById('authHelp').textContent = 'Local Pro is active on this machine. Your personal dashboard is using the saved license key automatically.';
457
+ }
458
+ renderStats(data);
459
+ setSelectedCard('all');
460
+ await loadDashboardData();
461
+ } catch (e) {
462
+ status.className = 'auth-status err';
463
+ status.textContent = '✗ ' + e.message;
464
+ if (opts.localPro) {
465
+ document.getElementById('authHelp').textContent = 'Local Pro bootstrap failed. Paste your THUMBGATE_API_KEY manually or retry the local launcher.';
466
+ }
467
+ }
468
+ if (!opts.localPro) {
469
+ btn.disabled = false;
470
+ }
471
+ }
472
+
473
+ function renderStats(data) {
474
+ const total = (data.totalFeedback || data.total || 0);
475
+ const pos = (data.totalPositive || data.positive || data.thumbsUp || 0);
476
+ const neg = (data.totalNegative || data.negative || data.thumbsDown || 0);
477
+ document.getElementById('statTotal').textContent = total;
478
+ document.getElementById('statPositive').textContent = pos;
479
+ document.getElementById('statNegative').textContent = neg;
480
+ }
481
+
482
+ function setSelectedCard(action) {
483
+ document.querySelectorAll('.stat-card').forEach(function(card) {
484
+ card.classList.toggle('selected', card.dataset.cardAction === action);
485
+ });
486
+ }
487
+
488
+ async function search() {
489
+ const query = document.getElementById('searchQuery').value.trim();
490
+ if (!query) return;
491
+ currentHighlightTerms = query.split(/\s+/).filter(function(t) { return t.length > 1; });
492
+ const container = document.getElementById('searchResults');
493
+ container.innerHTML = '<div class="loading">Searching...</div>';
494
+
495
+ // Demo mode: filter client-side
496
+ if (isDemo) {
497
+ var q = query.toLowerCase();
498
+ var results = demoData.filter(function(r) {
499
+ return (r.title + ' ' + r.context + ' ' + (r.tags || []).join(' ')).toLowerCase().indexOf(q) !== -1;
500
+ });
501
+ if (!results.length) {
502
+ setMessageState(container, 'empty', 'No demo results for "' + query + '". Try: git, test, deploy, secrets, database');
503
+ return;
504
+ }
505
+ container.innerHTML = results.map(renderResult).join('');
506
+ return;
507
+ }
508
+
509
+ try {
510
+ const res = await fetch('/v1/search', {
511
+ method: 'POST',
512
+ headers: getHeaders(),
513
+ body: JSON.stringify({ query: query, source: currentSource, limit: 20 })
514
+ });
515
+ if (!res.ok) throw new Error('Search failed');
516
+ const data = await res.json();
517
+ const results = data.results || data.memories || [];
518
+ if (!results.length) {
519
+ container.innerHTML = '<div class="empty">No results found</div>';
520
+ return;
521
+ }
522
+ container.innerHTML = results.map(renderResult).join('');
523
+ } catch (e) {
524
+ setMessageState(container, 'empty', e && e.message ? e.message : 'Search failed');
525
+ }
526
+ }
527
+
528
+ function renderResult(r) {
529
+ const signal = r.signal || r.type || '';
530
+ const isUp = signal === 'up' || signal === 'positive' || signal === 'thumbs_up';
531
+ const isDown = signal === 'down' || signal === 'negative' || signal === 'thumbs_down';
532
+ const signalClass = isUp ? 'up' : isDown ? 'down' : '';
533
+ const signalLabel = isUp ? '👍 Positive' : isDown ? '👎 Negative' : signal;
534
+ const title = r.title || r.context || r.text || '';
535
+ const context = r.context || r.text || r.content || '';
536
+ const tags = r.tags || [];
537
+ const date = r.timestamp ? new Date(r.timestamp).toLocaleDateString() : '';
538
+ return '<div class="result-card">' +
539
+ '<div class="result-header">' +
540
+ (signalLabel ? '<span class="result-signal ' + signalClass + '">' + signalLabel + '</span>' : '<span></span>') +
541
+ '<span class="result-date">' + date + '</span>' +
542
+ '</div>' +
543
+ (title ? '<div class="result-title">' + highlightText(title) + '</div>' : '') +
544
+ (context && context !== title ? '<div class="result-context">' + highlightText(context.slice(0, 300)) + '</div>' : '') +
545
+ (tags.length ? '<div class="result-tags">' + tags.map(function(t) {
546
+ return '<button type="button" class="tag" data-tag="' + encodeURIComponent(String(t)) + '" title="' + escAttr('Search for ' + t) + '">' + escHtml(t) + '</button>';
547
+ }).join('') + '</div>' : '') +
548
+ '</div>';
549
+ }
550
+
551
+ function escHtml(s) {
552
+ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
553
+ }
554
+
555
+ function escAttr(s) {
556
+ return escHtml(s).replace(/"/g, '&quot;').replace(/'/g, '&#39;');
557
+ }
558
+
559
+ function escJs(s) {
560
+ return String(s).replace(/\\/g, '\\\\').replace(/'/g, '\\\'');
561
+ }
562
+
563
+ function setMessageState(container, className, message) {
564
+ container.innerHTML = '<div class="' + className + '">' + escHtml(message) + '</div>';
565
+ }
566
+
567
+ var currentHighlightTerms = [];
568
+
569
+ function searchByTag(tag) {
570
+ document.getElementById('searchQuery').value = tag;
571
+ search();
572
+ }
573
+
574
+ function highlightText(text) {
575
+ if (!currentHighlightTerms.length) return escHtml(text);
576
+ var escaped = escHtml(text);
577
+ currentHighlightTerms.forEach(function(term) {
578
+ if (!term) return;
579
+ var re = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
580
+ escaped = escaped.replace(re, '<mark>$1</mark>');
581
+ });
582
+ return escaped;
583
+ }
584
+
585
+ function selectCard(el, action) {
586
+ currentHighlightTerms = [];
587
+ setSelectedCard(action);
588
+
589
+ if (action === 'gates') {
590
+ switchTab('gates');
591
+ return;
592
+ }
593
+
594
+ // Filter memories by signal
595
+ switchTab('search');
596
+ var container = document.getElementById('searchResults');
597
+ if (isDemo && demoData.length) {
598
+ var results = action === 'all' ? demoData : demoData.filter(function(r) { return r.signal === action; });
599
+ container.innerHTML = results.length ? results.map(renderResult).join('') : '<div class="empty">No ' + action + ' feedback in demo</div>';
600
+ return;
601
+ }
602
+ // Live mode: search by signal filter
603
+ var signalParam = action === 'all' ? '' : '&signal=' + action;
604
+ container.innerHTML = '<div class="loading">Loading...</div>';
605
+ fetch('/v1/search?q=*&limit=50' + signalParam, { method: 'GET', headers: getHeaders() })
606
+ .then(function(res) { return res.json(); })
607
+ .then(function(data) {
608
+ var items = data.results || [];
609
+ container.innerHTML = items.length ? items.map(renderResult).join('') : '<div class="empty">No ' + (action === 'all' ? '' : action + ' ') + 'feedback found</div>';
610
+ })
611
+ .catch(function(e) { setMessageState(container, 'empty', 'Error: ' + (e && e.message ? e.message : 'Unable to load feedback')); });
612
+ }
613
+
614
+ function setSource(el, source) {
615
+ currentSource = source;
616
+ document.querySelectorAll('.filter-btn').forEach(function(b) { b.classList.remove('active'); });
617
+ el.classList.add('active');
618
+ }
619
+
620
+ function switchTab(name) {
621
+ document.querySelectorAll('.tab').forEach(function(t) { t.classList.remove('active'); });
622
+ document.querySelectorAll('.tab-content').forEach(function(c) { c.classList.remove('active'); });
623
+ document.querySelector('[onclick*="' + name + '"]').classList.add('active');
624
+ document.getElementById('tab-' + name).classList.add('active');
625
+ }
626
+
627
+ async function loadGates() {
628
+ try {
629
+ const res = await fetch('/v1/dashboard', { headers: getHeaders() });
630
+ if (!res.ok) throw new Error('Failed to load dashboard');
631
+ const data = await res.json();
632
+ renderDashboardData(data);
633
+ } catch (e) {
634
+ setMessageState(document.getElementById('gatesList'), 'empty', e && e.message ? e.message : 'Failed to load gates');
635
+ setMessageState(document.getElementById('teamSummaryCards'), 'empty', e && e.message ? e.message : 'Failed to load team metrics');
636
+ setMessageState(document.getElementById('predictiveSummaryCards'), 'empty', e && e.message ? e.message : 'Failed to load predictive insights');
637
+ setMessageState(document.getElementById('predictiveAnomalies'), 'empty', e && e.message ? e.message : 'Failed to load predictive watchlist');
638
+ setMessageState(document.getElementById('generatedViewCanvas'), 'empty', e && e.message ? e.message : 'Failed to load generated view');
639
+ setMessageState(document.getElementById('settingsSummaryCards'), 'empty', e && e.message ? e.message : 'Failed to load policy origins');
640
+ setMessageState(document.getElementById('templateLibrary'), 'empty', e && e.message ? e.message : 'Failed to load template library');
641
+ }
642
+ }
643
+
644
+ async function loadDashboardData() {
645
+ await loadGates();
646
+ await loadGeneratedView(currentGeneratedView);
647
+ // Fetch full dashboard for insights charts
648
+ try {
649
+ var res = await fetch('/v1/dashboard', { headers: getHeaders() });
650
+ if (res.ok) {
651
+ var data = await res.json();
652
+ renderDashboardData(data);
653
+ }
654
+ } catch (e) { /* insights degrade gracefully */ }
655
+ }
656
+
657
+ function renderDashboardData(data) {
658
+ dashboardSnapshot = data;
659
+ const gates = data.gates || data.activeGates || [];
660
+ const gateStats = data.gateStats || {};
661
+ document.getElementById('statGates').textContent = gates.length || gateStats.totalGates || 0;
662
+ if (!gates.length) {
663
+ document.getElementById('gatesList').innerHTML = '<div class="empty">No active gates</div>';
664
+ } else {
665
+ document.getElementById('gatesList').innerHTML = gates.map(function(g) {
666
+ const action = g.action || 'block';
667
+ return '<div class="gate-card"><div><div class="gate-name">' + escHtml(g.name || g.id || 'Gate') + '</div>' +
668
+ '<div class="gate-pattern">' + escHtml(g.pattern || g.match || '') + '</div></div>' +
669
+ '<span class="gate-action ' + action + '">' + action.toUpperCase() + '</span></div>';
670
+ }).join('');
671
+ }
672
+
673
+ renderTeam(data.team || {}, data.analytics || {});
674
+ renderPredictive(data.predictive || {});
675
+ renderSettingsStatus(data.settingsStatus || {});
676
+ renderTemplates(data.templateLibrary || {});
677
+ renderInsights(data);
678
+ }
679
+
680
+ function renderGeneratedViewToolbar(spec) {
681
+ var views = Array.isArray(spec.availableViews) ? spec.availableViews : [];
682
+ document.getElementById('generatedViewToolbar').innerHTML = views.map(function(view) {
683
+ var activeClass = view.id === spec.view ? ' active' : '';
684
+ return '<button class="generated-view-btn' + activeClass + '" data-generated-view="' + escAttr(view.id) + '" onclick="loadGeneratedView(\'' + escJs(view.id) + '\')">' + escHtml(view.label || view.id) + '</button>';
685
+ }).join('');
686
+ }
687
+
688
+ function renderGeneratedStatGrid(component) {
689
+ var items = Array.isArray(component.items) ? component.items : [];
690
+ return '<div class="panel"><h3 class="generated-section-title">' + escHtml(component.title || 'Snapshot') + '</h3><div class="generated-grid">' + items.map(function(item) {
691
+ return '<div class="team-card"><div class="team-kicker">' + escHtml(item.label || 'Metric') + '</div><div class="team-value">' + escHtml(item.value || '0') + '</div><div class="team-note">' + escHtml(item.note || '') + '</div></div>';
692
+ }).join('') + '</div></div>';
693
+ }
694
+
695
+ function renderGeneratedList(component) {
696
+ var items = Array.isArray(component.items) ? component.items : [];
697
+ if (!items.length) {
698
+ return '<div class="panel"><h3 class="generated-section-title">' + escHtml(component.title || 'List') + '</h3><div class="empty" style="padding:20px 0;">' + escHtml(component.emptyMessage || 'No items.') + '</div></div>';
699
+ }
700
+ return '<div class="panel"><h3 class="generated-section-title">' + escHtml(component.title || 'List') + '</h3><div class="generated-list">' + items.map(function(item) {
701
+ return '<div class="generated-list-row"><div><div class="generated-list-title">' + escHtml(item.title || 'Item') + '</div><div class="generated-list-subtitle">' + escHtml(item.subtitle || '') + '</div></div><span class="generated-badge">' + escHtml(item.badge || '') + '</span></div>';
702
+ }).join('') + '</div></div>';
703
+ }
704
+
705
+ function renderGeneratedComponent(component) {
706
+ if (!component || !component.type) return '';
707
+ if (component.type === 'hero') {
708
+ return '<div class="panel"><h3 class="generated-section-title">' + escHtml(component.title || 'Generated view') + '</h3><p class="template-summary" style="margin-bottom:0;">' + escHtml(component.description || '') + '</p></div>';
709
+ }
710
+ if (component.type === 'stat_grid') {
711
+ return renderGeneratedStatGrid(component);
712
+ }
713
+ if (component.type === 'list') {
714
+ return renderGeneratedList(component);
715
+ }
716
+ if (component.type === 'callout') {
717
+ var tone = escAttr(component.tone || 'success');
718
+ return '<div class="panel generated-callout ' + tone + '"><h3 class="generated-section-title">' + escHtml(component.title || 'Callout') + '</h3><p class="template-summary" style="margin-bottom:0;">' + escHtml(component.body || '') + '</p></div>';
719
+ }
720
+ return '';
721
+ }
722
+
723
+ function renderGeneratedView(spec) {
724
+ currentGeneratedView = spec && spec.view ? spec.view : currentGeneratedView;
725
+ renderGeneratedViewToolbar(spec || {});
726
+ document.getElementById('generatedViewSummary').textContent = 'Approved component catalog: ' + ((spec && spec.allowedComponentTypes) ? spec.allowedComponentTypes.join(', ') : 'none');
727
+ var components = spec && Array.isArray(spec.components) ? spec.components : [];
728
+ document.getElementById('generatedViewCanvas').innerHTML = components.length
729
+ ? components.map(renderGeneratedComponent).join('')
730
+ : '<div class="empty">No generated view available.</div>';
731
+ }
732
+
733
+ function buildDemoGeneratedViewSpec(viewName) {
734
+ var base = {
735
+ version: '1.0.0',
736
+ catalog: 'thumbgate-dashboard-render-spec',
737
+ view: viewName,
738
+ availableViews: [
739
+ { id: 'team-review', label: 'Team review' },
740
+ { id: 'incident-review', label: 'Incident review' },
741
+ { id: 'workflow-rollout', label: 'Workflow rollout' }
742
+ ],
743
+ allowedComponentTypes: ['hero', 'stat_grid', 'list', 'callout']
744
+ };
745
+ if (viewName === 'incident-review') {
746
+ base.components = [
747
+ { type: 'hero', title: 'Generated Incident Review', description: 'Review blocked gates, root causes, and the next safest actions without hand-building a post-mortem page.' },
748
+ { type: 'stat_grid', title: 'Incident snapshot', items: [
749
+ { label: 'Active gates', value: '6', note: '4 manual / 2 auto-promoted' },
750
+ { label: 'Blocks per day', value: '1.7', note: 'warns/day 0.4' },
751
+ { label: 'Predictive alerts', value: '2', note: 'warning' },
752
+ { label: 'Buyer loss signals', value: '3', note: 'telemetry-backed' }
753
+ ] },
754
+ { type: 'list', title: 'Root cause clusters', emptyMessage: 'No root causes.', items: [
755
+ { title: 'verification_gap', subtitle: 'Claimed a change was complete before a proof run.', badge: '6 cases' },
756
+ { title: 'pricing_resistance', subtitle: 'Buyers showed intent but stopped at pricing.', badge: '2 cases' }
757
+ ] },
758
+ { type: 'list', title: 'Recommended next actions', emptyMessage: 'No actions.', items: [
759
+ { title: 'Audit evidence-before-done', subtitle: 'Top blocked gate is doing useful work and should stay explicit.', badge: '12 blocks' },
760
+ { title: 'Revisit team offer copy', subtitle: 'Predictive watchlist shows conversion drag despite traffic.', badge: 'warning' }
761
+ ] }
762
+ ];
763
+ return base;
764
+ }
765
+ if (viewName === 'workflow-rollout') {
766
+ base.components = [
767
+ { type: 'hero', title: 'Generated Workflow Rollout View', description: 'Turn funnel, attribution, and predictive data into a constrained operator dashboard for team rollout.' },
768
+ { type: 'stat_grid', title: 'Rollout pipeline', items: [
769
+ { label: 'Workflow sprint leads', value: '4', note: 'intake-first hosted funnel' },
770
+ { label: 'Qualified leads', value: '2', note: 'ready for proof-backed rollout' },
771
+ { label: 'Booked revenue', value: '$128.00', note: '1 paid order' },
772
+ { label: 'Team propensity', value: 'medium', note: 'score 0.54' }
773
+ ] },
774
+ { type: 'list', title: 'Top acquisition sources', emptyMessage: 'No sources.', items: [
775
+ { title: 'producthunt', subtitle: 'captured acquisition source', badge: '3 leads' },
776
+ { title: 'website', subtitle: 'captured acquisition source', badge: '1 lead' }
777
+ ] },
778
+ { type: 'list', title: 'Next rollout moves', emptyMessage: 'No rollout moves.', items: [
779
+ { title: 'Double down on reach_vb', subtitle: 'Best creator opportunity from predictive revenue scoring.', badge: '+$31.00' },
780
+ { title: 'Qualify pending sprint leads', subtitle: 'More leads than qualified workflows today.', badge: '4 total' }
781
+ ] }
782
+ ];
783
+ return base;
784
+ }
785
+ base.components = [
786
+ { type: 'hero', title: 'Generated Team Reliability Review', description: 'A constrained hosted view assembled from approved dashboard components.' },
787
+ { type: 'stat_grid', title: 'Team snapshot', items: [
788
+ { label: 'Active agents', value: '5', note: 'of 8 registered agents' },
789
+ { label: 'Org adherence', value: '92.4%', note: 'rolling 24h view' },
790
+ { label: 'Team propensity', value: 'medium', note: 'score 0.54' },
791
+ { label: 'Forecast revenue', value: '$128.00', note: 'opportunity $49.00' }
792
+ ] },
793
+ { type: 'list', title: 'Highest-risk agents', emptyMessage: 'No risky agents.', items: [
794
+ { title: 'claude-reviewer', subtitle: 'checkout-flow · fix/stripe-timeout', badge: '67.5% adherence' },
795
+ { title: 'codex-second-pass', subtitle: 'dashboard · feat/team-rollout', badge: '74.2% adherence' }
796
+ ] },
797
+ { type: 'list', title: 'Predictive watchlist', emptyMessage: 'No anomalies.', items: [
798
+ { title: 'pricing_resistance', subtitle: 'Price sensitivity dominates current loss reasons.', badge: 'warning' },
799
+ { title: 'creator_underperformance', subtitle: 'Creator reach_vb is generating intent without revenue conversion.', badge: 'warning' }
800
+ ] },
801
+ { type: 'callout', title: 'Commercial signal', body: 'Pro propensity is high and Team propensity is medium. Workflow sprint leads currently total 4.', tone: 'warning' }
802
+ ];
803
+ return base;
804
+ }
805
+
806
+ async function loadGeneratedView(viewName) {
807
+ currentGeneratedView = viewName || currentGeneratedView;
808
+ if (isDemo) {
809
+ renderGeneratedView(buildDemoGeneratedViewSpec(currentGeneratedView));
810
+ return;
811
+ }
812
+ try {
813
+ const res = await fetch('/v1/dashboard/render-spec?view=' + encodeURIComponent(currentGeneratedView), { headers: getHeaders() });
814
+ if (!res.ok) throw new Error('Failed to load generated view');
815
+ const spec = await res.json();
816
+ renderGeneratedView(spec);
817
+ } catch (e) {
818
+ setMessageState(document.getElementById('generatedViewCanvas'), 'empty', e && e.message ? e.message : 'Failed to load generated view');
819
+ }
820
+ }
821
+
822
+ function formatScope(scope) {
823
+ return escHtml(String(scope || 'unknown').replace(/_/g, ' '));
824
+ }
825
+
826
+ function formatSettingValue(value) {
827
+ if (value === undefined) return 'undefined';
828
+ if (typeof value === 'string') return value;
829
+ return JSON.stringify(value);
830
+ }
831
+
832
+ function renderSettingsStatus(settingsStatus) {
833
+ const resolvedSettings = settingsStatus.resolvedSettings || {};
834
+ const origins = Array.isArray(settingsStatus.origins) ? settingsStatus.origins : [];
835
+ const activeLayers = Array.isArray(settingsStatus.activeLayers) ? settingsStatus.activeLayers : [];
836
+ const routingPreview = settingsStatus.routingPreview || {};
837
+ const activeLayerNames = activeLayers.filter(function(layer) { return layer.exists; }).map(function(layer) { return layer.scope; });
838
+
839
+ document.getElementById('settingsSummary').textContent =
840
+ 'Managed > local > project > user > defaults. Active layers: ' + (activeLayerNames.length ? activeLayerNames.join(' → ') : 'defaults only') + '.';
841
+
842
+ const summaryCards = [
843
+ { label: 'Default MCP profile', value: resolvedSettings.mcp && resolvedSettings.mcp.defaultProfile ? resolvedSettings.mcp.defaultProfile : 'essential', note: 'baseline execution profile' },
844
+ { label: 'Read-only profile', value: resolvedSettings.mcp && resolvedSettings.mcp.readonlySessionProfile ? resolvedSettings.mcp.readonlySessionProfile : 'readonly', note: 'review sessions and no-write intent' },
845
+ { label: 'Harness runtime', value: resolvedSettings.harnesses && resolvedSettings.harnesses.allowRuntimeExecution ? 'enabled' : 'disabled', note: 'natural-language harness execution' },
846
+ { label: 'Policy origins', value: String(origins.length), note: 'resolved leaf settings with source metadata' }
847
+ ];
848
+
849
+ document.getElementById('settingsSummaryCards').innerHTML = summaryCards.map(function(card) {
850
+ return '<div class="settings-card">' +
851
+ '<div class="team-kicker">' + escHtml(card.label) + '</div>' +
852
+ '<div class="team-value">' + escHtml(card.value) + '</div>' +
853
+ '<div class="team-note">' + escHtml(card.note) + '</div>' +
854
+ '</div>';
855
+ }).join('');
856
+
857
+ document.getElementById('settingsLayers').innerHTML = activeLayers.length
858
+ ? activeLayers.map(function(layer) {
859
+ const source = layer.sourcePath ? layer.sourcePath : 'built-in defaults';
860
+ const state = layer.exists ? String(layer.leafCount || 0) + ' overrides' : 'not present';
861
+ return '<div class="layer-row"><div>' +
862
+ '<div class="layer-name">' + escHtml(source) + '</div>' +
863
+ '<div class="layer-note">' + escHtml(state) + '</div>' +
864
+ '</div><span class="scope-pill">' + formatScope(layer.scope) + '</span></div>';
865
+ }).join('')
866
+ : '<div class="empty" style="padding:20px 0;">No settings layers resolved.</div>';
867
+
868
+ const routingEntries = Object.keys(routingPreview);
869
+ document.getElementById('settingsRouting').innerHTML = routingEntries.length
870
+ ? routingEntries.map(function(key) {
871
+ const route = routingPreview[key] || {};
872
+ return '<div class="routing-row"><div>' +
873
+ '<div class="routing-name">' + escHtml(key) + '</div>' +
874
+ '<div class="routing-note">' + escHtml(route.reason || 'No routing reason available') + '</div>' +
875
+ '</div><span class="scope-pill">' + escHtml(route.profile || 'unknown') + '</span></div>';
876
+ }).join('')
877
+ : '<div class="empty" style="padding:20px 0;">No routing preview available.</div>';
878
+
879
+ document.getElementById('settingsOrigins').innerHTML = origins.length
880
+ ? origins.map(function(origin) {
881
+ return '<div class="origin-row"><div>' +
882
+ '<div class="origin-path">' + escHtml(origin.path || '') + '</div>' +
883
+ '<div class="origin-value">' + escHtml(formatSettingValue(origin.value)) + '</div>' +
884
+ '<div class="origin-note">' + escHtml(origin.sourcePath || 'built-in defaults') + '</div>' +
885
+ '</div><span class="scope-pill">' + formatScope(origin.scope) + '</span></div>';
886
+ }).join('')
887
+ : '<div class="empty" style="padding:20px 0;">No resolved setting origins.</div>';
888
+ }
889
+
890
+ function renderTeam(team, analytics) {
891
+ const northStar = analytics && analytics.northStar ? analytics.northStar : {};
892
+ const summaryCards = [
893
+ { label: 'Active agents', value: team.activeAgents || 0, note: 'of ' + (team.totalAgents || 0) + ' registered' },
894
+ { label: 'Org adherence', value: String(team.orgAdherenceRate || 0) + '%', note: 'last ' + (team.windowHours || 24) + ' hours' },
895
+ { label: 'Weekly teams', value: northStar.weeklyTeamsRunningProofBackedWorkflows || 0, note: 'proof-backed workflows' },
896
+ { label: 'Paid team runs', value: northStar.paidTeamRuns || 0, note: 'north-star proof' }
897
+ ];
898
+
899
+ document.getElementById('teamSummaryCards').innerHTML = summaryCards.map(function(card) {
900
+ return '<div class="team-card">' +
901
+ '<div class="team-kicker">' + escHtml(card.label) + '</div>' +
902
+ '<div class="team-value">' + escHtml(card.value) + '</div>' +
903
+ '<div class="team-note">' + escHtml(card.note) + '</div>' +
904
+ '</div>';
905
+ }).join('');
906
+
907
+ const riskAgents = Array.isArray(team.riskAgents) ? team.riskAgents : [];
908
+ document.getElementById('teamRiskAgents').innerHTML = riskAgents.length
909
+ ? riskAgents.map(function(agent) {
910
+ return '<div class="risk-row"><div>' +
911
+ '<div class="risk-name">' + escHtml(agent.id || 'agent') + '</div>' +
912
+ '<div class="risk-meta">' + escHtml((agent.project || 'unknown project') + (agent.branch ? ' · ' + agent.branch : '')) + '</div>' +
913
+ '</div><div class="risk-meta">' + escHtml(String(agent.adherenceRate || 0) + '% adherence') + '</div></div>';
914
+ }).join('')
915
+ : '<div class="empty" style="padding:20px 0;">No risky agents detected in this window.</div>';
916
+
917
+ const blocked = Array.isArray(team.topBlockedGates) ? team.topBlockedGates : [];
918
+ document.getElementById('teamBlockedGates').innerHTML = blocked.length
919
+ ? blocked.map(function(gate) {
920
+ return '<div class="blocked-row"><div>' +
921
+ '<div class="blocked-name">' + escHtml(gate.gateId || 'gate') + '</div>' +
922
+ '<div class="blocked-meta">' + escHtml(String(gate.warned || 0) + ' warns') + '</div>' +
923
+ '</div><div class="blocked-meta">' + escHtml(String(gate.blocked || 0) + ' blocks') + '</div></div>';
924
+ }).join('')
925
+ : '<div class="empty" style="padding:20px 0;">No blocked gates recorded yet.</div>';
926
+ }
927
+
928
+ function renderPredictive(predictive) {
929
+ const pro = predictive && predictive.upgradePropensity ? predictive.upgradePropensity.pro || {} : {};
930
+ const team = predictive && predictive.upgradePropensity ? predictive.upgradePropensity.team || {} : {};
931
+ const forecast = predictive && predictive.revenueForecast ? predictive.revenueForecast : {};
932
+ const anomalySummary = predictive && predictive.anomalySummary ? predictive.anomalySummary : {};
933
+ const topCreator = predictive && Array.isArray(predictive.topCreators) ? predictive.topCreators[0] : null;
934
+ const topSource = predictive && Array.isArray(predictive.topSources) ? predictive.topSources[0] : null;
935
+ const anomalies = predictive && Array.isArray(predictive.anomalies) ? predictive.anomalies : [];
936
+
937
+ const cards = [
938
+ { label: 'Pro propensity', value: pro.band || 'none', note: 'score ' + escHtml(String(pro.score || 0)) },
939
+ { label: 'Team propensity', value: team.band || 'none', note: 'score ' + escHtml(String(team.score || 0)) },
940
+ { label: 'Forecast revenue', value: '$' + (((forecast.predictedBookedRevenueCents || 0) / 100).toFixed(2)), note: 'opportunity +' + '$' + (((forecast.incrementalOpportunityCents || 0) / 100).toFixed(2)) },
941
+ { label: 'Predictive alerts', value: String(anomalySummary.count || 0), note: (anomalySummary.severity || 'healthy') + ' watchlist' }
942
+ ];
943
+
944
+ document.getElementById('predictiveSummaryCards').innerHTML = cards.map(function(card) {
945
+ return '<div class="team-card">' +
946
+ '<div class="team-kicker">' + escHtml(card.label) + '</div>' +
947
+ '<div class="team-value">' + escHtml(card.value) + '</div>' +
948
+ '<div class="team-note">' + escHtml(card.note) + '</div>' +
949
+ '</div>';
950
+ }).join('');
951
+
952
+ const lines = [];
953
+ if (topCreator) {
954
+ lines.push('<div class="blocked-row"><div><div class="blocked-name">Top creator opportunity</div><div class="blocked-meta">' + escHtml(topCreator.key || 'unknown') + '</div></div><div class="blocked-meta">+$' + escHtml(((topCreator.opportunityRevenueCents || 0) / 100).toFixed(2)) + '</div></div>');
955
+ }
956
+ if (topSource) {
957
+ lines.push('<div class="blocked-row"><div><div class="blocked-name">Top channel opportunity</div><div class="blocked-meta">' + escHtml(topSource.key || 'unknown') + '</div></div><div class="blocked-meta">+$' + escHtml(((topSource.opportunityRevenueCents || 0) / 100).toFixed(2)) + '</div></div>');
958
+ }
959
+ anomalies.slice(0, 5).forEach(function(anomaly) {
960
+ lines.push('<div class="blocked-row"><div><div class="blocked-name">' + escHtml(anomaly.type || 'anomaly') + '</div><div class="blocked-meta">' + escHtml(anomaly.message || '') + '</div></div><div class="blocked-meta">' + escHtml(anomaly.severity || 'warning') + '</div></div>');
961
+ });
962
+
963
+ document.getElementById('predictiveAnomalies').innerHTML = lines.length
964
+ ? lines.join('')
965
+ : '<div class="empty" style="padding:20px 0;">No predictive anomalies right now.</div>';
966
+ }
967
+
968
+ function renderTemplates(templateLibrary) {
969
+ const templates = Array.isArray(templateLibrary.templates) ? templateLibrary.templates : [];
970
+ const categories = templateLibrary.categories || {};
971
+ document.getElementById('templateSummary').textContent =
972
+ (templateLibrary.total || 0) + ' curated templates across ' + Object.keys(categories).length + ' categories. Start with the highest-ROI guardrails, then tune for your repos.';
973
+
974
+ document.getElementById('templateLibrary').innerHTML = templates.length
975
+ ? templates.map(function(template) {
976
+ return '<div class="template-card">' +
977
+ '<div class="template-meta"><div><h3>' + escHtml(template.name || 'Template') + '</h3></div><div class="blocked-meta">' + escHtml(template.category || 'Other') + '</div></div>' +
978
+ '<div><span class="template-pill">' + escHtml(template.signal || '•') + '</span><span class="template-pill">' + escHtml((template.defaultAction || 'unknown').toUpperCase()) + '</span><span class="template-pill">' + escHtml(template.severity || 'medium') + '</span></div>' +
979
+ '<div class="template-copy">' + escHtml(template.problem || '') + '</div>' +
980
+ '<div class="template-copy"><strong>ROI:</strong> ' + escHtml(template.roi || '') + '</div>' +
981
+ '<div class="template-copy"><strong>Rollout:</strong> ' + escHtml(template.rollout || '') + '</div>' +
982
+ '<div class="template-pattern">' + escHtml(template.pattern || '') + '</div>' +
983
+ '</div>';
984
+ }).join('')
985
+ : '<div class="empty">No gate templates available</div>';
986
+ }
987
+
988
+ document.addEventListener('click', function(event) {
989
+ var tagButton = event.target.closest('.tag[data-tag]');
990
+ if (!tagButton) return;
991
+ searchByTag(decodeURIComponent(tagButton.dataset.tag || ''));
992
+ });
993
+
994
+ function loadDemo() {
995
+ document.querySelector('.auth-bar').style.display = 'none';
996
+ document.getElementById('dashboardContent').style.display = 'block';
997
+ document.getElementById('demoBanner').style.display = 'flex';
998
+ // Demo badge in nav
999
+ var logo = document.querySelector('.nav-logo');
1000
+ if (!document.getElementById('demoBadge')) {
1001
+ logo.insertAdjacentHTML('afterend', '<span class="demo-badge" id="demoBadge">Demo Mode</span>');
1002
+ }
1003
+ // Stats
1004
+ document.getElementById('statTotal').textContent = '297';
1005
+ document.getElementById('statPositive').textContent = '37';
1006
+ document.getElementById('statNegative').textContent = '260';
1007
+ document.getElementById('statGates').textContent = '21';
1008
+ setSelectedCard('all');
1009
+ // Sample memories — realistic scenarios from real agent-driven development
1010
+ var demoResults = [
1011
+ { signal: 'down', title: 'Claimed fix worked without running tests', context: 'Agent announced "fixed and pushed" but never ran the test suite. CI failed on 3 tests. Gate now requires test evidence before any completion claim.', tags: ['anti-lying', 'verification-gap', 'ci', 'trust-breach'], timestamp: '2025-06-22T10:20:00Z' },
1012
+ { signal: 'down', title: 'Force-pushed to main and lost teammate commits', context: 'Used git push --force on main to fix a rebase. Overwrote 3 commits from another team member. Had to recover from reflog. Gate now blocks all --force pushes to protected branches.', tags: ['git', 'destructive', 'auto-blocked'], timestamp: '2025-06-20T09:15:00Z' },
1013
+ { signal: 'up', title: 'Pre-action gate caught .env commit', context: 'Gate blocked a git add that included .env with production API keys. Saved from leaking secrets to a public repo.', tags: ['security', 'prevention', 'secrets'], timestamp: '2025-06-19T11:30:00Z' },
1014
+ { signal: 'down', title: 'PR scope creep — 72 changed files for a 2-file fix', context: 'Agent included unrelated formatting changes, config files, and lock file updates in a PR that should have touched 2 files. User had to manually separate the changes.', tags: ['pr-scope', 'scope-creep', 'user-frustration', 'git-workflow'], timestamp: '2025-06-18T14:30:00Z' },
1015
+ { signal: 'up', title: 'Full PR review cycle with on-device verification', context: 'Fixed 3 review findings, verified on physical Android device with fresh debug build, confirmed Delete Account flow end-to-end before marking PR ready.', tags: ['pr-review', 'on-device-verification', 'evidence-based', 'metric:ROI'], timestamp: '2025-06-17T16:45:00Z' },
1016
+ { signal: 'down', title: 'Claimed Figma compliance without visual verification', context: 'Said UI matched Figma designs without actually checking. User pointed out wrong colors, missing spacing, and incorrect font weights. Should have used screenshot comparison.', tags: ['anti-lying', 'figma', 'visual-verification', 'trust-breach'], timestamp: '2025-06-16T08:05:00Z' },
1017
+ { signal: 'down', title: 'Deployed without running tests', context: 'Pushed a refactor to main without running the test suite. Two integration tests failed in CI, blocking the release for 3 hours.', tags: ['ci', 'testing', 'deployment'], timestamp: '2025-06-15T09:15:00Z' },
1018
+ { signal: 'up', title: 'Atomic commits improved bisect speed', context: 'Splitting a large feature into 8 atomic commits made git bisect find the regression in under 2 minutes instead of manual debugging.', tags: ['git', 'debugging', 'evidence-based'], timestamp: '2025-06-14T16:45:00Z' },
1019
+ { signal: 'down', title: 'Deleted production database table', context: 'AI agent ran DROP TABLE on a staging-named table that was actually aliased to production. Added a gate requiring explicit confirmation for any destructive SQL.', tags: ['database', 'destructive', 'critical', 'auto-blocked'], timestamp: '2025-06-13T08:05:00Z' },
1020
+ { signal: 'up', title: 'Read file before editing prevented breaking change', context: 'Always read the target file before making changes. Agent caught that the function signature had changed upstream and adapted the edit accordingly.', tags: ['code-quality', 'prevention', 'evidence-based'], timestamp: '2025-06-12T14:30:00Z' },
1021
+ { signal: 'down', title: 'Pushed to wrong branch — created new PR instead of updating existing', context: 'Agent pushed changes to a new branch instead of the open PR branch. Had to cherry-pick commits and force-close the duplicate PR.', tags: ['git-workflow', 'branch-strategy', 'delegation', 'user-frustration'], timestamp: '2025-06-11T10:20:00Z' },
1022
+ { signal: 'up', title: 'ADO tickets split correctly with parallel execution', context: 'Split frontend/backend tasks, corrected area path and iteration, created investigation subtask, and updated PR description — all done efficiently in parallel.', tags: ['ado-workflow', 'parallel-execution', 'triage', 'metric:ROI'], timestamp: '2025-06-10T13:00:00Z' },
1023
+ { signal: 'down', title: 'Delegated debugging to QA instead of investigating', context: 'Told user to ask QA engineer for error logs instead of investigating the issue directly. Wasted 30 minutes of back-and-forth when the fix was a one-line config change.', tags: ['delegation', 'user-frustration', 'debugging', 'speed'], timestamp: '2025-06-09T15:30:00Z' },
1024
+ { signal: 'down', title: 'iOS build failed — forgot pod install after adding dependency', context: 'Added a new npm package but did not run pod install or rebuild the native project. Build failed on iOS physical device. Metro bundler showed stale cache.', tags: ['ios-build', 'metro', 'speed', 'mobile'], timestamp: '2025-06-08T09:45:00Z' },
1025
+ { signal: 'up', title: 'Prevention rule stopped repeat mistake', context: 'Gate auto-generated from 3 prior "forgot pod install" failures now blocks any npm install that touches native modules without a follow-up pod install step.', tags: ['prevention', 'ios-build', 'auto-generated', 'metric:ROI'], timestamp: '2025-06-07T11:00:00Z' },
1026
+ { signal: 'down', title: 'Claimed performance fix without benchmarking', context: 'Said the optimization reduced render time by 40% but never ran a before/after benchmark. Actual measurement showed no improvement. Gate now requires metrics evidence.', tags: ['anti-lying', 'performance', 'verification-gap', 'measure-first'], timestamp: '2025-06-06T14:20:00Z' },
1027
+ { signal: 'up', title: 'DPO export caught systematic failure pattern', context: 'Exported 47 preference pairs revealing that 80% of negative feedback involved claiming work was done without verification. Led to a new mandatory evidence gate.', tags: ['dpo-export', 'evidence-based', 'prevention', 'metric:ROI'], timestamp: '2025-06-05T10:15:00Z' }
1028
+ ];
1029
+ isDemo = true;
1030
+ demoData = demoResults.slice(0, 3);
1031
+ var teaserHtml = demoData.map(renderResult).join('');
1032
+ var upgradeWall = '<div style="position:relative;margin-top:8px;">' +
1033
+ '<div style="filter:blur(4px);pointer-events:none;opacity:0.4;">' + demoResults.slice(3, 6).map(renderResult).join('') + '</div>' +
1034
+ '<div style="position:absolute;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;">' +
1035
+ '<div style="text-align:center;background:rgba(10,10,15,0.92);border:1px solid #333;border-radius:12px;padding:28px 36px;">' +
1036
+ '<div style="font-size:20px;font-weight:700;color:#fff;margin-bottom:8px;">Unlock your full dashboard</div>' +
1037
+ '<div style="color:#aaa;margin-bottom:16px;">Pro shows your real feedback, gates, and lessons — not sample data.</div>' +
1038
+ '<a href="https://buy.stripe.com/7sYcN5bmIf5IcSd8qf3sI0a" target="_blank" rel="noopener" ' +
1039
+ 'style="display:inline-block;background:#b85c2d;color:#fff;padding:10px 24px;border-radius:8px;text-decoration:none;font-weight:700;">Start 7-day free trial</a>' +
1040
+ '<div style="color:#666;font-size:12px;margin-top:10px;">npx thumbgate pro --activate --key=YOUR_KEY</div>' +
1041
+ '</div></div></div>';
1042
+ document.getElementById('searchResults').innerHTML = teaserHtml + upgradeWall;
1043
+ // Sample gates
1044
+ var demoGates = [
1045
+ { name: 'no-force-push', pattern: 'Block git push --force to main or master branches', action: 'block' },
1046
+ { name: 'read-before-edit', pattern: 'Must read file contents before any edit_file call', action: 'block' },
1047
+ { name: 'test-before-deploy', pattern: 'Run npm test before any deployment or push to main', action: 'block' },
1048
+ { name: 'no-secrets-in-commits', pattern: 'Block git add on .env, credentials, or API key files', action: 'block' },
1049
+ { name: 'evidence-before-claim', pattern: 'Run verification commands before claiming task completion', action: 'block' },
1050
+ { name: 'atomic-commits', pattern: 'Each commit should contain a single logical change', action: 'warn' }
1051
+ ];
1052
+ document.getElementById('gatesList').innerHTML = demoGates.map(function(g) {
1053
+ return '<div class="gate-card"><div><div class="gate-name">' + escHtml(g.name) + '</div>' +
1054
+ '<div class="gate-pattern">' + escHtml(g.pattern) + '</div></div>' +
1055
+ '<span class="gate-action ' + g.action + '">' + g.action.toUpperCase() + '</span></div>';
1056
+ }).join('');
1057
+ renderTeam({
1058
+ totalAgents: 8,
1059
+ activeAgents: 5,
1060
+ windowHours: 24,
1061
+ orgAdherenceRate: 92.4,
1062
+ riskAgents: [
1063
+ { id: 'claude-reviewer', project: 'checkout-flow', branch: 'fix/stripe-timeout', adherenceRate: 67.5 },
1064
+ { id: 'codex-second-pass', project: 'dashboard', branch: 'feat/team-rollout', adherenceRate: 74.2 }
1065
+ ],
1066
+ topBlockedGates: [
1067
+ { gateId: 'evidence-before-done', blocked: 12, warned: 1 },
1068
+ { gateId: 'never-force-push-main', blocked: 7, warned: 0 }
1069
+ ]
1070
+ }, {
1071
+ northStar: {
1072
+ weeklyTeamsRunningProofBackedWorkflows: 3,
1073
+ paidTeamRuns: 1
1074
+ }
1075
+ });
1076
+ renderPredictive({
1077
+ upgradePropensity: {
1078
+ pro: { band: 'high', score: 0.71 },
1079
+ team: { band: 'medium', score: 0.54 }
1080
+ },
1081
+ revenueForecast: {
1082
+ predictedBookedRevenueCents: 12800,
1083
+ incrementalOpportunityCents: 4900
1084
+ },
1085
+ anomalySummary: {
1086
+ count: 2,
1087
+ severity: 'warning'
1088
+ },
1089
+ topCreators: [
1090
+ { key: 'reach_vb', opportunityRevenueCents: 3100 }
1091
+ ],
1092
+ topSources: [
1093
+ { key: 'producthunt', opportunityRevenueCents: 1800 }
1094
+ ],
1095
+ anomalies: [
1096
+ { type: 'pricing_resistance', message: 'Price sensitivity dominates current loss reasons.', severity: 'warning' },
1097
+ { type: 'creator_underperformance', message: 'Creator reach_vb is generating intent without revenue conversion.', severity: 'warning' }
1098
+ ]
1099
+ });
1100
+ renderSettingsStatus({
1101
+ activeLayers: [
1102
+ { scope: 'defaults', exists: true, leafCount: 7, sourcePath: null },
1103
+ { scope: 'user', exists: true, leafCount: 2, sourcePath: '~/.thumbgate/settings.json' },
1104
+ { scope: 'project', exists: true, leafCount: 2, sourcePath: '.thumbgate/settings.json' },
1105
+ { scope: 'local', exists: false, leafCount: 0, sourcePath: '.thumbgate/settings.local.json' },
1106
+ { scope: 'managed', exists: true, leafCount: 3, sourcePath: 'config/thumbgate-settings.managed.json' }
1107
+ ],
1108
+ resolvedSettings: {
1109
+ mcp: { defaultProfile: 'essential', readonlySessionProfile: 'readonly' },
1110
+ harnesses: { enabled: true, allowRuntimeExecution: true }
1111
+ },
1112
+ routingPreview: {
1113
+ dashboardTool: { profile: 'readonly', reason: 'dashboard is available in the most restrictive profile that contains it' },
1114
+ defaultSession: { profile: 'essential', reason: 'default auto-routing — essential profile from settings hierarchy' },
1115
+ reviewSession: { profile: 'readonly', reason: 'read-only session detected — routing to readonly profile' }
1116
+ },
1117
+ origins: [
1118
+ { path: 'mcp.defaultProfile', value: 'essential', scope: 'project', sourcePath: '.thumbgate/settings.json' },
1119
+ { path: 'mcp.readonlySessionProfile', value: 'readonly', scope: 'project', sourcePath: '.thumbgate/settings.json' },
1120
+ { path: 'harnesses.allowRuntimeExecution', value: true, scope: 'project', sourcePath: '.thumbgate/settings.json' },
1121
+ { path: 'dashboard.showPolicyOrigins', value: true, scope: 'managed', sourcePath: 'config/thumbgate-settings.managed.json' }
1122
+ ]
1123
+ });
1124
+ renderTemplates({
1125
+ total: 6,
1126
+ categories: {
1127
+ 'Git Safety': 1,
1128
+ 'Verification': 1,
1129
+ 'Agent Honesty': 1,
1130
+ 'Database Safety': 1,
1131
+ 'Secrets Hygiene': 1,
1132
+ 'Positive Reinforcement': 1
1133
+ },
1134
+ templates: [
1135
+ { name: 'Never force-push to main', category: 'Git Safety', signal: '👎', defaultAction: 'block', severity: 'critical', problem: 'Stops destructive history rewrites on protected branches before they land.', roi: 'Protects every shared repo from the fastest irreversible mistake.', rollout: 'Enable on every team repo on day one.', pattern: 'git\\s+push\\s+(--force|-f)' },
1136
+ { name: 'Never skip tests before commit', category: 'Verification', signal: '👎', defaultAction: 'block', severity: 'high', problem: 'Requires proof before code leaves the laptop.', roi: 'Cuts review churn and CI rollback time across the team.', rollout: 'Pair with repository-specific test commands.', pattern: 'git\\s+commit' },
1137
+ { name: 'Require evidence before saying done', category: 'Agent Honesty', signal: '👎', defaultAction: 'block', severity: 'high', problem: 'Prevents unsupported completion claims.', roi: 'Raises trust in autonomous runs.', rollout: 'Use anywhere proof matters more than speed.', pattern: 'completion_claim_without_verification' },
1138
+ { name: 'Protect production SQL', category: 'Database Safety', signal: '👎', defaultAction: 'block', severity: 'critical', problem: 'Blocks destructive SQL operations on production-like targets.', roi: 'One saved incident pays for the rollout.', rollout: 'Turn on for any team touching live data.', pattern: '(drop|truncate|delete)\\s+.*production' }
1139
+ ]
1140
+ });
1141
+ renderGeneratedView(buildDemoGeneratedViewSpec(currentGeneratedView));
1142
+ }
1143
+
1144
+ // Auto-load demo on first visit so visitors see the product immediately
1145
+ window.addEventListener('DOMContentLoaded', function() {
1146
+ if (hasBootstrapKey()) {
1147
+ connect({ key: BOOTSTRAP_API_KEY, localPro: true });
1148
+ return;
1149
+ }
1150
+ if (!window.location.search.includes('noauto')) {
1151
+ loadDemo();
1152
+ }
1153
+ });
1154
+
1155
+ async function exportDpo() {
1156
+ const status = document.getElementById('exportStatus');
1157
+ status.textContent = 'Exporting...';
1158
+ try {
1159
+ const res = await fetch('/v1/dpo/export', { headers: getHeaders() });
1160
+ if (!res.ok) throw new Error('Export failed');
1161
+ const data = await res.json();
1162
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
1163
+ const url = URL.createObjectURL(blob);
1164
+ const a = document.createElement('a');
1165
+ a.href = url;
1166
+ a.download = 'thumbgate-dpo-pairs-' + new Date().toISOString().slice(0,10) + '.json';
1167
+ a.click();
1168
+ URL.revokeObjectURL(url);
1169
+ const count = data.pairs ? data.pairs.length : Array.isArray(data) ? data.length : 0;
1170
+ status.textContent = '✓ Exported ' + count + ' preference pairs';
1171
+ status.style.color = 'var(--green)';
1172
+ } catch (e) {
1173
+ status.textContent = '✗ ' + e.message;
1174
+ status.style.color = 'var(--red)';
1175
+ }
1176
+ }
1177
+
1178
+ // ---------------------------------------------------------------------------
1179
+ // Insights tab: charts + pipeline
1180
+ // ---------------------------------------------------------------------------
1181
+ var feedbackChart = null;
1182
+ var lessonChart = null;
1183
+ var gateAuditChart = null;
1184
+
1185
+ function renderInsights(data) {
1186
+ renderPipeline(data.lessonPipeline || {});
1187
+ renderFeedbackTrendChart(data.feedbackTimeSeries || {});
1188
+ renderLessonTrendChart(data.feedbackTimeSeries || {});
1189
+ renderGateAuditChartFromData(data.gateAudit || {});
1190
+ }
1191
+
1192
+ function renderPipeline(pipeline) {
1193
+ var stages = pipeline.stages || [];
1194
+ var rates = pipeline.rates || {};
1195
+ var container = document.getElementById('pipelineFlow');
1196
+ if (!stages.length) {
1197
+ container.innerHTML = '<div class="empty">No pipeline data yet. Give some thumbs-up/down feedback to get started.</div>';
1198
+ return;
1199
+ }
1200
+ var stageLinks = {
1201
+ feedback: '/lessons',
1202
+ lessons: '/lessons?category=error',
1203
+ gates: '#tab-gates',
1204
+ blocked: '#tab-gates',
1205
+ };
1206
+ var html = '';
1207
+ for (var i = 0; i < stages.length; i++) {
1208
+ var s = stages[i];
1209
+ var colors = { feedback: 'var(--cyan)', lessons: 'var(--green)', gates: '#fbbf24', blocked: 'var(--red)' };
1210
+ var color = colors[s.id] || 'var(--cyan)';
1211
+ var href = stageLinks[s.id] || '#';
1212
+ var isTabLink = href.startsWith('#tab-');
1213
+ var onclickAttr = isTabLink ? ' onclick="switchTab(\'' + href.slice(5) + '\');return false;"' : '';
1214
+ html += '<a href="' + escAttr(href) + '"' + onclickAttr + ' style="text-align:center;min-width:120px;cursor:pointer;text-decoration:none;color:inherit;display:block;border-radius:12px;padding:16px 12px;transition:background 0.15s,transform 0.1s;" title="' + escAttr(s.detail || '') + '" onmouseover="this.style.background=\'rgba(34,211,238,0.08)\';this.style.transform=\'translateY(-2px)\'" onmouseout="this.style.background=\'transparent\';this.style.transform=\'none\'">';
1215
+ html += '<div style="font-size:36px;font-weight:800;color:' + color + ';letter-spacing:-0.03em;">' + s.count + '</div>';
1216
+ html += '<div style="font-size:13px;font-weight:600;margin-top:4px;">' + escHtml(s.label) + '</div>';
1217
+ html += '<div style="font-size:11px;color:var(--text-muted);margin-top:2px;">' + escHtml(s.detail || '') + '</div>';
1218
+ html += '</a>';
1219
+ if (i < stages.length - 1) {
1220
+ html += '<div style="font-size:24px;color:var(--text-muted);padding:0 8px;">→</div>';
1221
+ }
1222
+ }
1223
+ container.innerHTML = html;
1224
+
1225
+ var ratesHtml = '';
1226
+ if (rates.feedbackToLesson !== undefined) {
1227
+ ratesHtml += '<span>Feedback → Lesson: <strong style="color:var(--cyan);">' + rates.feedbackToLesson + '%</strong></span>';
1228
+ }
1229
+ if (rates.lessonToGate !== undefined) {
1230
+ ratesHtml += '<span>Lesson → Gate: <strong style="color:#fbbf24;">' + rates.lessonToGate + '%</strong></span>';
1231
+ }
1232
+ document.getElementById('pipelineRates').innerHTML = ratesHtml;
1233
+ }
1234
+
1235
+ function chartDefaults() {
1236
+ return {
1237
+ color: '#8b8b96',
1238
+ borderColor: '#222225',
1239
+ backgroundColor: 'transparent',
1240
+ };
1241
+ }
1242
+
1243
+ function renderFeedbackTrendChart(ts) {
1244
+ var canvas = document.getElementById('feedbackTrendChart');
1245
+ if (!canvas) return;
1246
+ var days = ts.days || [];
1247
+ if (feedbackChart) feedbackChart.destroy();
1248
+
1249
+ var labels = days.map(function(d) { return d.dayKey.slice(5); });
1250
+ feedbackChart = new Chart(canvas, {
1251
+ type: 'line',
1252
+ data: {
1253
+ labels: labels,
1254
+ datasets: [
1255
+ {
1256
+ label: '👍 Up',
1257
+ data: days.map(function(d) { return d.up; }),
1258
+ borderColor: '#4ade80',
1259
+ backgroundColor: 'rgba(74,222,128,0.1)',
1260
+ fill: true,
1261
+ tension: 0.3,
1262
+ pointRadius: 2,
1263
+ pointHoverRadius: 5,
1264
+ },
1265
+ {
1266
+ label: '👎 Down',
1267
+ data: days.map(function(d) { return d.down; }),
1268
+ borderColor: '#f87171',
1269
+ backgroundColor: 'rgba(248,113,113,0.1)',
1270
+ fill: true,
1271
+ tension: 0.3,
1272
+ pointRadius: 2,
1273
+ pointHoverRadius: 5,
1274
+ },
1275
+ ],
1276
+ },
1277
+ options: {
1278
+ responsive: true,
1279
+ maintainAspectRatio: false,
1280
+ interaction: { intersect: false, mode: 'index' },
1281
+ plugins: {
1282
+ legend: { labels: { color: '#e8e8ec', font: { size: 12 } } },
1283
+ tooltip: { backgroundColor: '#161618', borderColor: '#222225', borderWidth: 1, titleColor: '#e8e8ec', bodyColor: '#8b8b96' },
1284
+ },
1285
+ scales: {
1286
+ x: { ticks: { color: '#8b8b96', font: { size: 10 }, maxRotation: 45 }, grid: { color: 'rgba(34,34,37,0.5)' } },
1287
+ y: { beginAtZero: true, ticks: { color: '#8b8b96', stepSize: 1 }, grid: { color: 'rgba(34,34,37,0.5)' } },
1288
+ },
1289
+ },
1290
+ });
1291
+ }
1292
+
1293
+ function renderLessonTrendChart(ts) {
1294
+ var canvas = document.getElementById('lessonTrendChart');
1295
+ if (!canvas) return;
1296
+ var days = ts.days || [];
1297
+ if (lessonChart) lessonChart.destroy();
1298
+
1299
+ var labels = days.map(function(d) { return d.dayKey.slice(5); });
1300
+ var cumulativeLessons = [];
1301
+ var runningTotal = 0;
1302
+ for (var i = 0; i < days.length; i++) {
1303
+ runningTotal += days[i].lessons || 0;
1304
+ cumulativeLessons.push(runningTotal);
1305
+ }
1306
+
1307
+ lessonChart = new Chart(canvas, {
1308
+ type: 'bar',
1309
+ data: {
1310
+ labels: labels,
1311
+ datasets: [
1312
+ {
1313
+ label: 'Lessons/day',
1314
+ data: days.map(function(d) { return d.lessons || 0; }),
1315
+ backgroundColor: 'rgba(34,211,238,0.4)',
1316
+ borderColor: '#22d3ee',
1317
+ borderWidth: 1,
1318
+ borderRadius: 3,
1319
+ yAxisID: 'y',
1320
+ },
1321
+ {
1322
+ label: 'Cumulative',
1323
+ data: cumulativeLessons,
1324
+ type: 'line',
1325
+ borderColor: '#4ade80',
1326
+ backgroundColor: 'transparent',
1327
+ tension: 0.3,
1328
+ pointRadius: 0,
1329
+ borderWidth: 2,
1330
+ yAxisID: 'y1',
1331
+ },
1332
+ ],
1333
+ },
1334
+ options: {
1335
+ responsive: true,
1336
+ maintainAspectRatio: false,
1337
+ interaction: { intersect: false, mode: 'index' },
1338
+ plugins: {
1339
+ legend: { labels: { color: '#e8e8ec', font: { size: 12 } } },
1340
+ tooltip: { backgroundColor: '#161618', borderColor: '#222225', borderWidth: 1, titleColor: '#e8e8ec', bodyColor: '#8b8b96' },
1341
+ },
1342
+ scales: {
1343
+ x: { ticks: { color: '#8b8b96', font: { size: 10 }, maxRotation: 45 }, grid: { color: 'rgba(34,34,37,0.5)' } },
1344
+ y: { beginAtZero: true, position: 'left', ticks: { color: '#22d3ee', stepSize: 1 }, grid: { color: 'rgba(34,34,37,0.5)' } },
1345
+ y1: { beginAtZero: true, position: 'right', ticks: { color: '#4ade80' }, grid: { drawOnChartArea: false } },
1346
+ },
1347
+ },
1348
+ });
1349
+ }
1350
+
1351
+ function renderGateAuditChartFromData(gateAudit) {
1352
+ var canvas = document.getElementById('gateAuditChart');
1353
+ if (!canvas) return;
1354
+ var days = gateAudit.days || [];
1355
+ if (gateAuditChart) gateAuditChart.destroy();
1356
+
1357
+ var labels = days.map(function(d) { return (d.dayKey || '').slice(5); });
1358
+ gateAuditChart = new Chart(canvas, {
1359
+ type: 'bar',
1360
+ data: {
1361
+ labels: labels,
1362
+ datasets: [
1363
+ {
1364
+ label: '🚫 Blocked',
1365
+ data: days.map(function(d) { return d.deny || 0; }),
1366
+ backgroundColor: 'rgba(248,113,113,0.6)',
1367
+ borderRadius: 3,
1368
+ },
1369
+ {
1370
+ label: '⚠️ Warned',
1371
+ data: days.map(function(d) { return d.warn || 0; }),
1372
+ backgroundColor: 'rgba(251,191,36,0.5)',
1373
+ borderRadius: 3,
1374
+ },
1375
+ {
1376
+ label: '✅ Allowed',
1377
+ data: days.map(function(d) { return d.allow || 0; }),
1378
+ backgroundColor: 'rgba(74,222,128,0.4)',
1379
+ borderRadius: 3,
1380
+ },
1381
+ ],
1382
+ },
1383
+ options: {
1384
+ responsive: true,
1385
+ maintainAspectRatio: false,
1386
+ plugins: {
1387
+ legend: { labels: { color: '#e8e8ec', font: { size: 12 } } },
1388
+ tooltip: { backgroundColor: '#161618', borderColor: '#222225', borderWidth: 1, titleColor: '#e8e8ec', bodyColor: '#8b8b96' },
1389
+ },
1390
+ scales: {
1391
+ x: { stacked: true, ticks: { color: '#8b8b96', font: { size: 10 } }, grid: { color: 'rgba(34,34,37,0.5)' } },
1392
+ y: { stacked: true, beginAtZero: true, ticks: { color: '#8b8b96', stepSize: 1 }, grid: { color: 'rgba(34,34,37,0.5)' } },
1393
+ },
1394
+ },
1395
+ });
1396
+ }
1397
+ </script>
1398
+ </body>
1399
+ </html>