@i4ctime/q-ring 0.9.8 → 0.11.0

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,1313 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ PACKAGE_VERSION,
4
+ checkDecay,
5
+ collapseEnvironment,
6
+ detectAnomalies,
7
+ getPolicySummary,
8
+ listApprovals,
9
+ listEntanglements,
10
+ listHooks,
11
+ listMemory,
12
+ listSecrets,
13
+ queryAudit,
14
+ readProjectConfig,
15
+ tunnelList
16
+ } from "./chunk-MQM4DLPI.js";
17
+
18
+ // src/core/dashboard.ts
19
+ import { createServer } from "http";
20
+
21
+ // src/core/dashboard-html.ts
22
+ function getDashboardHtml() {
23
+ return `<!DOCTYPE html>
24
+ <html lang="en">
25
+ <head>
26
+ <meta charset="utf-8"/>
27
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
28
+ <title>q-ring \u2014 quantum status</title>
29
+ <style>
30
+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
31
+ :root{
32
+ --bg-deep:#04080f;
33
+ --bg-section:#080e18;
34
+ --bg-card:#0f1a2e;
35
+ --bg-card-hover:#142240;
36
+ --border:#1a2d4a;
37
+ --border-glow:#0ea5e9;
38
+
39
+ --text-primary:#f8f8ff;
40
+ --text-secondary:#c8cfe0;
41
+ --text-dim:#8899b4;
42
+
43
+ --accent:#0ea5e9;
44
+ --accent-bright:#38bdf8;
45
+ --accent-dim:rgba(14,165,233,0.15);
46
+ --accent-glow:rgba(14,165,233,0.4);
47
+
48
+ --danger:#ff5e5b;
49
+ --warning:#fbbf24;
50
+ --green:#22c55e;
51
+ --violet:#a855f7;
52
+ --pink:#ff0055;
53
+
54
+ --font-display:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;
55
+ --font-mono:'SF Mono','Cascadia Code','Fira Code',Consolas,'Liberation Mono',monospace;
56
+
57
+ --radius:12px;
58
+ --radius-sm:8px;
59
+ --radius-lg:20px;
60
+
61
+ --glass-bg:rgba(15,26,46,0.65);
62
+ --glass-border:rgba(26,45,74,0.8);
63
+ --shadow-card:0 4px 24px -1px rgba(0,0,0,0.4),0 0 1px rgba(255,255,255,0.04);
64
+ --shadow-glow:0 0 20px rgba(14,165,233,0.12),0 0 40px rgba(168,85,247,0.08);
65
+ }
66
+ html{background:var(--bg-deep);color:var(--text-primary);font-family:var(--font-display);font-size:16px;line-height:1.5}
67
+ body{min-height:100vh;overflow-x:hidden;position:relative}
68
+
69
+ /* Hidden SVG defs for gradient icons */
70
+ .svg-defs{position:absolute;width:0;height:0;overflow:hidden}
71
+
72
+ /* Mesh blobs */
73
+ .blob{position:fixed;border-radius:50%;filter:blur(100px);opacity:.12;pointer-events:none;z-index:0}
74
+ .blob-1{width:600px;height:600px;top:-120px;left:-100px;background:radial-gradient(circle,var(--accent),transparent 70%);animation:drift1 22s ease-in-out infinite}
75
+ .blob-2{width:500px;height:500px;bottom:-80px;right:-60px;background:radial-gradient(circle,var(--violet),transparent 70%);animation:drift2 26s ease-in-out infinite}
76
+ .blob-3{width:350px;height:350px;top:40%;left:50%;background:radial-gradient(circle,var(--green),transparent 70%);animation:drift3 30s ease-in-out infinite;opacity:.06}
77
+ @keyframes drift1{0%,100%{transform:translate(0,0) scale(1)}33%{transform:translate(60px,-40px) scale(1.08)}66%{transform:translate(-30px,50px) scale(.95)}}
78
+ @keyframes drift2{0%,100%{transform:translate(0,0) scale(1)}33%{transform:translate(-50px,30px) scale(1.05)}66%{transform:translate(40px,-60px) scale(.92)}}
79
+ @keyframes drift3{0%,100%{transform:translate(-50%,-50%) scale(1)}50%{transform:translate(-40%,-60%) scale(1.1)}}
80
+
81
+ .container{position:relative;z-index:1;max-width:1320px;margin:0 auto;padding:20px 20px 48px}
82
+
83
+ /* Header */
84
+ .header{position:sticky;top:0;z-index:5;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px;margin-bottom:20px;padding:14px 18px;background:rgba(4,8,15,0.85);backdrop-filter:blur(16px) saturate(1.2);-webkit-backdrop-filter:blur(16px) saturate(1.2);border:1px solid var(--border);border-radius:var(--radius)}
85
+ .header-left{display:flex;align-items:center;gap:14px;flex-wrap:wrap;min-width:0}
86
+ .header h1{font-family:var(--font-display);font-size:1.45rem;font-weight:700;letter-spacing:-.02em;display:flex;align-items:center;gap:10px}
87
+ .header h1 .q-icon{display:flex;filter:drop-shadow(0 0 6px rgba(14,165,233,0.6))}
88
+ .header h1 .brand{background:linear-gradient(135deg,#00D1FF,var(--violet));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
89
+ .header h1 .sub{color:var(--text-dim);font-weight:400;font-size:1rem;-webkit-text-fill-color:var(--text-dim)}
90
+ .meta-chip{font-family:var(--font-mono);font-size:.72rem;color:var(--text-dim);background:rgba(255,255,255,.04);border:1px solid var(--border);padding:3px 8px;border-radius:99px;display:inline-flex;align-items:center;gap:6px;max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
91
+ .meta-chip svg{width:11px;height:11px;flex-shrink:0;opacity:.7}
92
+ .header-right{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
93
+ .status-dot{width:8px;height:8px;border-radius:50%;background:var(--green);box-shadow:0 0 8px var(--green);display:inline-block;animation:pulse 2s ease-in-out infinite}
94
+ .status-dot.disconnected{background:var(--danger);box-shadow:0 0 8px var(--danger);animation:none}
95
+ .status-dot.paused{background:var(--warning);box-shadow:0 0 8px var(--warning);animation:none}
96
+ @keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
97
+ .conn-label{font-size:.78rem;color:var(--text-dim);display:flex;align-items:center;gap:6px;font-family:var(--font-mono)}
98
+ .btn{font-family:var(--font-display);font-size:.78rem;font-weight:500;color:var(--text-secondary);background:rgba(255,255,255,.04);border:1px solid var(--border);padding:5px 11px;border-radius:var(--radius-sm);cursor:pointer;display:inline-flex;align-items:center;gap:5px;transition:background .2s,border-color .2s,color .2s}
99
+ .btn:hover{background:rgba(14,165,233,.08);border-color:var(--accent);color:var(--text-primary)}
100
+ .btn svg{width:13px;height:13px}
101
+ .btn.active{background:var(--accent-dim);color:var(--accent-bright);border-color:rgba(14,165,233,.4)}
102
+ .kbd{font-family:var(--font-mono);font-size:.65rem;color:var(--text-dim);background:rgba(255,255,255,.06);border:1px solid var(--border);border-bottom-width:2px;padding:1px 5px;border-radius:4px;margin-left:4px}
103
+
104
+ /* KPI strip */
105
+ .kpi-strip{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-bottom:20px}
106
+ .kpi{background:var(--glass-bg);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:12px 14px;display:flex;flex-direction:column;gap:2px;transition:border-color .25s,transform .25s}
107
+ .kpi:hover{border-color:var(--border-glow);transform:translateY(-2px)}
108
+ .kpi-label{font-size:.66rem;text-transform:uppercase;letter-spacing:.1em;color:var(--text-dim);font-weight:600;display:flex;align-items:center;gap:6px}
109
+ .kpi-label svg{width:12px;height:12px;flex-shrink:0}
110
+ .kpi-value{font-family:var(--font-display);font-size:1.5rem;font-weight:700;line-height:1.1;color:var(--text-primary)}
111
+ .kpi-value.warning{color:var(--warning)}
112
+ .kpi-value.danger{color:var(--danger)}
113
+ .kpi-value.green{color:var(--green)}
114
+ .kpi-value.dim{color:var(--text-dim)}
115
+ .kpi-sub{font-size:.7rem;color:var(--text-dim);font-family:var(--font-mono)}
116
+
117
+ /* Grid */
118
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(360px,1fr));gap:16px;margin-bottom:16px}
119
+ .grid-wide{grid-column:1/-1}
120
+
121
+ /* Cards \u2014 reveal animation */
122
+ .card{background:var(--glass-bg);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border:1px solid var(--glass-border);border-radius:var(--radius);padding:18px 20px;box-shadow:var(--shadow-card);transition:border-color .3s,box-shadow .3s,transform .3s;opacity:0;transform:translateY(16px);animation:cardReveal .5s cubic-bezier(0.16,1,0.3,1) forwards}
123
+ .card:hover{border-color:var(--border-glow);box-shadow:var(--shadow-card),var(--shadow-glow)}
124
+ @keyframes cardReveal{to{opacity:1;transform:translateY(0)}}
125
+
126
+ .card-title{font-family:var(--font-display);font-size:.78rem;text-transform:uppercase;letter-spacing:.1em;color:var(--text-dim);margin-bottom:14px;display:flex;align-items:center;gap:8px;font-weight:600}
127
+ .card-title svg{width:16px;height:16px;flex-shrink:0;filter:drop-shadow(0 0 4px rgba(14,165,233,0.4))}
128
+ .card-title .title-aside{margin-left:auto;font-size:.7rem;color:var(--text-dim);font-weight:400;letter-spacing:.04em;text-transform:none;display:flex;align-items:center;gap:6px}
129
+
130
+ /* Health donut */
131
+ .health-row{display:flex;align-items:center;gap:24px}
132
+ .donut-wrap{position:relative;width:100px;height:100px;flex-shrink:0}
133
+ .donut-wrap svg{transform:rotate(-90deg)}
134
+ .donut-wrap .donut-label{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;font-size:1.5rem;font-weight:700;line-height:1;font-family:var(--font-display)}
135
+ .donut-wrap .donut-label small{font-size:.7rem;color:var(--text-dim);font-weight:400;margin-top:2px;letter-spacing:.04em}
136
+ .health-legend{display:flex;flex-direction:column;gap:6px;font-family:var(--font-mono)}
137
+ .legend-item{display:flex;align-items:center;gap:8px;font-size:.82rem}
138
+ .legend-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
139
+ .scope-row{display:flex;gap:6px;margin-top:14px;flex-wrap:wrap;font-family:var(--font-mono);font-size:.72rem;color:var(--text-dim)}
140
+ .scope-pill{padding:2px 8px;border-radius:99px;background:rgba(255,255,255,.04);border:1px solid var(--border)}
141
+ .scope-pill strong{color:var(--text-primary);margin-right:4px;font-weight:600}
142
+
143
+ /* Decay bars */
144
+ .decay-list{display:flex;flex-direction:column;gap:8px;max-height:280px;overflow-y:auto}
145
+ .decay-item{display:flex;align-items:center;gap:10px}
146
+ .decay-key{font-family:var(--font-mono);font-size:.85rem;min-width:120px;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
147
+ .decay-bar{flex:1;height:6px;border-radius:3px;background:rgba(255,255,255,0.06);overflow:hidden;position:relative}
148
+ .decay-fill{height:100%;border-radius:3px;transition:width .6s ease}
149
+ .decay-time{font-size:.8rem;color:var(--text-dim);min-width:60px;text-align:right;font-family:var(--font-mono)}
150
+
151
+ /* Superposition pills */
152
+ .super-list{display:flex;flex-direction:column;gap:8px;max-height:280px;overflow-y:auto}
153
+ .super-item{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
154
+ .super-key{font-family:var(--font-mono);font-size:.85rem;min-width:100px}
155
+ .env-pill{font-size:.72rem;padding:2px 8px;border-radius:99px;font-weight:600;letter-spacing:.03em;font-family:var(--font-mono)}
156
+ .env-prod{background:rgba(255,0,85,0.2);color:var(--pink);border:1px solid rgba(255,0,85,0.3)}
157
+ .env-staging{background:rgba(251,191,36,0.15);color:var(--warning);border:1px solid rgba(251,191,36,0.25)}
158
+ .env-dev{background:rgba(34,197,94,0.15);color:var(--green);border:1px solid rgba(34,197,94,0.25)}
159
+ .env-default{background:rgba(168,85,247,0.15);color:var(--violet);border:1px solid rgba(168,85,247,0.25)}
160
+ .env-test{background:rgba(14,165,233,0.15);color:var(--accent-bright);border:1px solid rgba(14,165,233,0.25)}
161
+
162
+ /* Entanglement */
163
+ .entangle-list{display:flex;flex-direction:column;gap:6px;max-height:240px;overflow-y:auto}
164
+ .entangle-pair{display:flex;align-items:center;gap:8px;font-family:var(--font-mono);font-size:.83rem}
165
+ .entangle-arrow{color:var(--accent-bright)}
166
+
167
+ /* Tunnels */
168
+ .tunnel-list{display:flex;flex-direction:column;gap:8px;max-height:240px;overflow-y:auto}
169
+ .tunnel-card{background:rgba(168,85,247,0.06);border:1px solid rgba(168,85,247,0.15);border-radius:var(--radius-sm);padding:10px 12px;font-size:.83rem;font-family:var(--font-mono)}
170
+ .tunnel-meta{display:flex;gap:12px;margin-top:4px;font-size:.78rem;color:var(--text-dim)}
171
+
172
+ /* Audit feed */
173
+ .audit-toolbar{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;align-items:center}
174
+ .audit-actions-strip{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}
175
+ .audit-chip{font-family:var(--font-mono);font-size:.7rem;padding:2px 9px;border-radius:99px;background:rgba(255,255,255,.04);border:1px solid var(--border);color:var(--text-secondary);cursor:pointer;transition:all .2s}
176
+ .audit-chip:hover{border-color:var(--accent);color:var(--text-primary)}
177
+ .audit-chip.active{background:var(--accent-dim);color:var(--accent-bright);border-color:rgba(14,165,233,.4)}
178
+ .audit-chip strong{color:var(--text-primary);margin-left:5px;font-weight:600}
179
+ .audit-feed{display:flex;flex-direction:column;gap:2px;max-height:340px;overflow-y:auto;font-size:.82rem;font-family:var(--font-mono)}
180
+ .audit-row{display:grid;grid-template-columns:78px 76px 56px 1fr;gap:8px;padding:4px 0;border-bottom:1px solid rgba(255,255,255,0.03);align-items:baseline}
181
+ .audit-ts{color:var(--text-dim)}
182
+ .audit-action{font-weight:600}
183
+ .audit-action.read{color:var(--accent)}.audit-action.write{color:var(--green)}.audit-action.delete{color:var(--danger)}
184
+ .audit-action.entangle{color:var(--violet)}.audit-action.tunnel{color:var(--violet)}.audit-action.teleport{color:var(--warning)}
185
+ .audit-action.generate{color:var(--warning)}.audit-action.list{color:var(--text-dim)}.audit-action.export{color:var(--text-dim)}
186
+ .audit-action.collapse{color:var(--accent)}.audit-action.approve{color:var(--green)}.audit-action.revoke{color:var(--danger)}
187
+ .audit-action.policy_deny{color:var(--danger)}.audit-action.rotate{color:var(--violet)}
188
+ .audit-source{color:var(--text-dim);font-size:.72rem;text-transform:uppercase;letter-spacing:.04em}
189
+ .audit-detail{color:var(--text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
190
+ .audit-key{color:var(--text-secondary)}
191
+
192
+ /* Anomalies */
193
+ .anomaly-list{display:flex;flex-direction:column;gap:8px}
194
+ .anomaly-card{background:rgba(255,94,91,0.06);border:1px solid rgba(255,94,91,0.15);border-radius:var(--radius-sm);padding:10px 14px;animation:anomaly-pulse 3s ease-in-out infinite}
195
+ @keyframes anomaly-pulse{0%,100%{border-color:rgba(255,94,91,0.15)}50%{border-color:rgba(255,94,91,0.4)}}
196
+ .anomaly-type{font-size:.7rem;text-transform:uppercase;letter-spacing:.06em;color:var(--danger);font-weight:700;margin-bottom:2px;font-family:var(--font-display)}
197
+ .anomaly-desc{font-size:.86rem;color:var(--text-primary)}
198
+ .anomaly-hint{font-size:.74rem;color:var(--text-dim);margin-top:4px;font-family:var(--font-mono)}
199
+
200
+ /* Environment badge */
201
+ .env-status{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
202
+ .env-big{font-size:1rem;font-weight:700;padding:4px 14px;border-radius:var(--radius-sm)}
203
+ .env-source{font-size:.78rem;color:var(--text-dim);font-family:var(--font-mono)}
204
+
205
+ /* Manifest */
206
+ .manifest-bars{display:flex;flex-direction:column;gap:8px}
207
+ .manifest-row{display:flex;align-items:center;gap:8px;font-family:var(--font-mono);font-size:.78rem}
208
+ .manifest-bar{flex:1;height:6px;border-radius:3px;background:rgba(255,255,255,.06);overflow:hidden}
209
+ .manifest-fill{height:100%;border-radius:3px}
210
+ .manifest-list{margin-top:10px;display:flex;flex-direction:column;gap:3px;font-family:var(--font-mono);font-size:.78rem;color:var(--text-secondary)}
211
+ .manifest-list .label{color:var(--text-dim);text-transform:uppercase;font-size:.66rem;letter-spacing:.08em;margin-top:6px}
212
+ .manifest-list .key-pill{display:inline-block;padding:1px 6px;background:rgba(255,255,255,.04);border:1px solid var(--border);border-radius:4px;margin:1px 3px 1px 0;font-size:.74rem}
213
+ .manifest-list .key-pill.miss{color:var(--danger);border-color:rgba(255,94,91,.3)}
214
+ .manifest-list .key-pill.exp{color:var(--warning);border-color:rgba(251,191,36,.3)}
215
+
216
+ /* Policy */
217
+ .policy-rows{display:flex;flex-direction:column;gap:6px;font-family:var(--font-mono);font-size:.78rem;color:var(--text-secondary)}
218
+ .policy-row{display:flex;justify-content:space-between;padding:2px 0;border-bottom:1px solid rgba(255,255,255,.04)}
219
+ .policy-label{color:var(--text-dim)}
220
+ .policy-value{color:var(--text-primary)}
221
+ .policy-value.zero{color:var(--text-dim)}
222
+
223
+ /* Approvals */
224
+ .approval-list{display:flex;flex-direction:column;gap:8px;max-height:240px;overflow-y:auto}
225
+ .approval-card{background:rgba(34,197,94,.05);border:1px solid rgba(34,197,94,.2);border-radius:var(--radius-sm);padding:10px 12px;font-size:.82rem}
226
+ .approval-card.tampered{background:rgba(255,94,91,.06);border-color:rgba(255,94,91,.4)}
227
+ .approval-card.expiring{background:rgba(251,191,36,.06);border-color:rgba(251,191,36,.3)}
228
+ .approval-head{display:flex;justify-content:space-between;gap:8px;font-family:var(--font-mono);font-weight:600}
229
+ .approval-reason{color:var(--text-dim);font-size:.76rem;margin-top:3px}
230
+ .approval-meta{display:flex;gap:12px;margin-top:4px;font-size:.72rem;color:var(--text-dim);font-family:var(--font-mono)}
231
+
232
+ /* Hooks */
233
+ .hooks-list{display:flex;flex-direction:column;gap:6px;max-height:240px;overflow-y:auto}
234
+ .hook-row{display:flex;align-items:center;gap:8px;font-family:var(--font-mono);font-size:.8rem;padding:6px 10px;background:rgba(255,255,255,.03);border:1px solid var(--border);border-radius:var(--radius-sm)}
235
+ .hook-row.disabled{opacity:.5}
236
+ .hook-type{font-size:.7rem;text-transform:uppercase;font-weight:600;padding:1px 6px;border-radius:99px;letter-spacing:.04em}
237
+ .hook-type.shell{background:rgba(168,85,247,.15);color:var(--violet)}
238
+ .hook-type.http{background:rgba(14,165,233,.15);color:var(--accent-bright)}
239
+ .hook-type.signal{background:rgba(251,191,36,.15);color:var(--warning)}
240
+ .hook-summary{flex:1;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
241
+ .hook-id{color:var(--text-dim);font-size:.72rem}
242
+
243
+ /* Secrets table */
244
+ .secrets-toolbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px;align-items:center}
245
+ .search{flex:1;min-width:180px;display:flex;align-items:center;gap:6px;background:rgba(255,255,255,.04);border:1px solid var(--border);border-radius:var(--radius-sm);padding:5px 10px;transition:border-color .2s}
246
+ .search:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px rgba(14,165,233,.12)}
247
+ .search svg{width:13px;height:13px;color:var(--text-dim);flex-shrink:0}
248
+ .search input{flex:1;background:transparent;border:none;outline:none;color:var(--text-primary);font-family:var(--font-mono);font-size:.82rem}
249
+ .search input::placeholder{color:var(--text-dim)}
250
+ .secrets-table-wrap{max-height:380px;overflow:auto;border:1px solid var(--border);border-radius:var(--radius-sm);background:rgba(4,8,15,.4)}
251
+ .secrets-table{width:100%;border-collapse:collapse;font-family:var(--font-mono);font-size:.78rem}
252
+ .secrets-table thead th{position:sticky;top:0;background:rgba(8,14,24,.95);backdrop-filter:blur(8px);text-align:left;padding:8px 10px;color:var(--text-dim);font-weight:600;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;border-bottom:1px solid var(--border);cursor:pointer;user-select:none;white-space:nowrap}
253
+ .secrets-table thead th:hover{color:var(--text-primary)}
254
+ .secrets-table thead th .sort-arrow{display:inline-block;margin-left:4px;color:var(--accent-bright);opacity:0;font-size:.7rem}
255
+ .secrets-table thead th.sorted .sort-arrow{opacity:1}
256
+ .secrets-table tbody td{padding:6px 10px;border-bottom:1px solid rgba(255,255,255,.03);color:var(--text-secondary);vertical-align:middle}
257
+ .secrets-table tbody tr:hover td{background:rgba(14,165,233,.05);color:var(--text-primary)}
258
+ .secrets-table .col-key{color:var(--text-primary);font-weight:500;max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
259
+ .secrets-table .col-decay{min-width:90px}
260
+ .secrets-table .col-tags{max-width:200px;overflow:hidden}
261
+ .tag-pill{display:inline-block;font-size:.68rem;padding:1px 6px;background:rgba(168,85,247,.1);color:var(--violet);border:1px solid rgba(168,85,247,.2);border-radius:99px;margin-right:3px;font-family:var(--font-mono)}
262
+ .scope-tag{display:inline-block;font-size:.68rem;padding:1px 6px;border-radius:4px;letter-spacing:.04em;font-weight:600;text-transform:uppercase}
263
+ .scope-tag.global{background:rgba(14,165,233,.15);color:var(--accent-bright)}
264
+ .scope-tag.project{background:rgba(34,197,94,.15);color:var(--green)}
265
+ .scope-tag.team{background:rgba(168,85,247,.15);color:var(--violet)}
266
+ .scope-tag.org{background:rgba(251,191,36,.15);color:var(--warning)}
267
+ .type-tag{display:inline-block;font-size:.68rem;padding:1px 6px;border-radius:4px;letter-spacing:.04em;text-transform:uppercase;background:rgba(255,255,255,.05);color:var(--text-dim)}
268
+ .type-tag.superposition{background:rgba(168,85,247,.12);color:var(--violet)}
269
+ .protected-icon{color:var(--warning);margin-left:4px;display:inline-flex;vertical-align:middle}
270
+ .mini-decay{display:inline-flex;align-items:center;gap:6px;width:100%}
271
+ .mini-decay-bar{flex:1;height:4px;border-radius:2px;background:rgba(255,255,255,.06);overflow:hidden;min-width:30px}
272
+ .mini-decay-fill{height:100%;border-radius:2px}
273
+ .mini-decay-time{color:var(--text-dim);font-size:.7rem;min-width:38px;text-align:right}
274
+
275
+ /* Empty states */
276
+ .empty{color:var(--text-dim);font-size:.86rem;font-style:italic;padding:8px 0}
277
+ .empty-cta{margin-top:6px;display:block;font-style:normal;font-family:var(--font-mono);font-size:.78rem;color:var(--accent-bright)}
278
+
279
+ /* Footer */
280
+ .foot{margin-top:24px;text-align:center;color:var(--text-dim);font-size:.72rem;font-family:var(--font-mono)}
281
+ .foot a{color:var(--accent-bright);text-decoration:none}
282
+ .foot a:hover{text-decoration:underline}
283
+
284
+ /* Scrollbar */
285
+ ::-webkit-scrollbar{width:6px;height:6px}
286
+ ::-webkit-scrollbar-track{background:transparent}
287
+ ::-webkit-scrollbar-thumb{background:rgba(255,255,255,0.08);border-radius:3px}
288
+ ::-webkit-scrollbar-thumb:hover{background:rgba(255,255,255,0.15)}
289
+
290
+ /* Print */
291
+ @media print{
292
+ .blob,.header-right{display:none}
293
+ .header{position:static}
294
+ body{background:#fff;color:#000}
295
+ }
296
+ </style>
297
+ </head>
298
+ <body>
299
+
300
+ <!-- Shared SVG gradient definition -->
301
+ <svg class="svg-defs" aria-hidden="true" focusable="false">
302
+ <defs>
303
+ <linearGradient id="neon-grad" x1="0%" y1="0%" x2="100%" y2="100%">
304
+ <stop offset="0%" stop-color="#00D1FF"/>
305
+ <stop offset="100%" stop-color="#a855f7"/>
306
+ </linearGradient>
307
+ </defs>
308
+ </svg>
309
+
310
+ <div class="blob blob-1"></div>
311
+ <div class="blob blob-2"></div>
312
+ <div class="blob blob-3"></div>
313
+
314
+ <div class="container">
315
+ <header class="header">
316
+ <div class="header-left">
317
+ <h1>
318
+ <span class="q-icon"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="url(#neon-grad)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg></span>
319
+ <span class="brand">q-ring</span>
320
+ <span class="sub">quantum status</span>
321
+ </h1>
322
+ <span class="meta-chip" id="versionChip" title="q-ring version"></span>
323
+ <span class="meta-chip" id="projectChip" title="Project working directory"></span>
324
+ </div>
325
+ <div class="header-right">
326
+ <span class="conn-label" title="Last update from the live stream"><span id="lastUpdate">\u2014</span></span>
327
+ <button class="btn" id="pauseBtn" type="button" title="Pause / resume the live stream (P)">
328
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>
329
+ <span id="pauseLabel">Pause</span>
330
+ </button>
331
+ <button class="btn" id="refreshBtn" type="button" title="Force-refresh now (R)">
332
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3.5-7.1"/><polyline points="21 3 21 9 15 9"/></svg>
333
+ Refresh
334
+ </button>
335
+ <a class="btn" id="jsonLink" href="/api/status" target="_blank" rel="noopener" title="Open the raw JSON snapshot in a new tab">
336
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
337
+ JSON
338
+ </a>
339
+ <span class="conn-label"><span class="status-dot" id="connDot"></span><span id="connText">connecting\u2026</span></span>
340
+ </div>
341
+ </header>
342
+
343
+ <section class="kpi-strip" id="kpiStrip"></section>
344
+
345
+ <section class="grid" id="overviewGrid"></section>
346
+
347
+ <section id="secretsSection"></section>
348
+
349
+ <section class="grid" id="quantumGrid"></section>
350
+
351
+ <section class="grid" id="govGrid"></section>
352
+
353
+ <section class="grid" id="anomalyAuditGrid"></section>
354
+
355
+ <p class="foot">
356
+ <span id="footMeta">\u2014</span>
357
+ \xB7 keyboard: <span class="kbd">/</span> search \xB7 <span class="kbd">P</span> pause \xB7 <span class="kbd">R</span> refresh
358
+ </p>
359
+ </div>
360
+
361
+ <script>
362
+ (function(){
363
+ const $ = (id) => document.getElementById(id);
364
+
365
+ /* --- SVG icon library (matching gh-pages neon gradient) --- */
366
+ const ic = (path) => '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="url(#neon-grad)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">'+path+'</svg>';
367
+ const icons = {
368
+ health: ic('<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>'),
369
+ environment: ic('<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>'),
370
+ decay: ic('<path d="M5 22h14"/><path d="M5 2h14"/><path d="M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22"/><path d="M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2"/>'),
371
+ superposition: ic('<polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/>'),
372
+ entangle: ic('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'),
373
+ tunnel: ic('<path d="M9 10h.01"/><path d="M15 10h.01"/><path d="M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z"/>'),
374
+ anomaly: ic('<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>'),
375
+ audit: ic('<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>'),
376
+ key: ic('<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>'),
377
+ shield: ic('<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>'),
378
+ hook: ic('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'),
379
+ approve: ic('<path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>'),
380
+ manifest: ic('<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>'),
381
+ policy: ic('<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/>'),
382
+ memory: ic('<rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/><line x1="20" y1="9" x2="22" y2="9"/><line x1="20" y1="14" x2="22" y2="14"/><line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/>'),
383
+ folder: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>',
384
+ tag: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>',
385
+ search: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>',
386
+ lock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>'
387
+ };
388
+
389
+ function esc(s){ const d=document.createElement('div');d.textContent=s==null?'':String(s);return d.innerHTML; }
390
+
391
+ function envClass(e){
392
+ if(!e) return 'env-default';
393
+ const k=e.toLowerCase();
394
+ if(k==='prod'||k==='production') return 'env-prod';
395
+ if(k==='staging'||k==='stage') return 'env-staging';
396
+ if(k==='dev'||k==='development') return 'env-dev';
397
+ if(k==='test'||k==='testing') return 'env-test';
398
+ return 'env-default';
399
+ }
400
+
401
+ function decayColor(pct,expired){
402
+ if(expired) return 'var(--danger)';
403
+ if(pct>=90) return 'var(--danger)';
404
+ if(pct>=75) return 'var(--warning)';
405
+ return 'var(--accent)';
406
+ }
407
+
408
+ function fmtTime(ts){
409
+ const d=new Date(ts);
410
+ return d.getHours().toString().padStart(2,'0')+':'+d.getMinutes().toString().padStart(2,'0')+':'+d.getSeconds().toString().padStart(2,'0');
411
+ }
412
+
413
+ function fmtRelative(ts){
414
+ if(!ts) return '\u2014';
415
+ const diff=Math.floor((Date.now()-new Date(ts).getTime())/1000);
416
+ if(isNaN(diff)) return '\u2014';
417
+ if(diff<5) return 'just now';
418
+ if(diff<60) return diff+'s ago';
419
+ if(diff<3600) return Math.floor(diff/60)+'m ago';
420
+ if(diff<86400) return Math.floor(diff/3600)+'h ago';
421
+ return Math.floor(diff/86400)+'d ago';
422
+ }
423
+
424
+ function fmtDuration(seconds){
425
+ if(seconds==null) return '\u2014';
426
+ if(seconds<0) return 'expired';
427
+ if(seconds<60) return seconds+'s';
428
+ if(seconds<3600) return Math.floor(seconds/60)+'m';
429
+ if(seconds<86400) return Math.floor(seconds/3600)+'h';
430
+ return Math.floor(seconds/86400)+'d';
431
+ }
432
+
433
+ /* --- State --- */
434
+ const state = {
435
+ snapshot: null,
436
+ paused: false,
437
+ secretsQuery: '',
438
+ secretsSort: { col: 'lastAccessedAt', dir: 'desc' },
439
+ auditFilter: { action: '', source: '', text: '' }
440
+ };
441
+
442
+ /* --- Renderers --- */
443
+
444
+ function renderHeaderMeta(s){
445
+ $('versionChip').innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> v'+esc(s.version);
446
+ $('projectChip').innerHTML = icons.folder + ' ' + esc(s.projectPath);
447
+ }
448
+
449
+ function renderKpis(s){
450
+ const m = s.auditMetrics || { total:0, byAction:{}, topRead:[] };
451
+ const reads = m.byAction.read || 0;
452
+ const writes = (m.byAction.write||0) + (m.byAction.delete||0) + (m.byAction.rotate||0);
453
+ const denied = m.byAction.policy_deny || 0;
454
+ const enabledHooks = (s.hooks||[]).filter(h=>h.enabled).length;
455
+ const validApprovals = (s.approvals||[]).filter(a=>a.valid).length;
456
+
457
+ const items = [
458
+ { label: 'Secrets', icon: icons.key, value: s.health.total, sub: s.health.healthy+' healthy \xB7 '+s.health.stale+' stale \xB7 '+s.health.expired+' expired', cls: '' },
459
+ { label: 'Environment', icon: icons.environment, value: s.environment ? s.environment.env : 'none', sub: s.environment ? 'via '+s.environment.source : 'no env detected', cls: s.environment ? '' : 'dim' },
460
+ { label: 'Protected', icon: icons.lock, value: s.protectedCount, sub: 'require approval', cls: s.protectedCount>0 ? 'warning' : 'dim' },
461
+ { label: 'Approvals', icon: icons.approve, value: validApprovals, sub: 'active grants', cls: validApprovals>0 ? 'green' : 'dim' },
462
+ { label: 'Hooks', icon: icons.hook, value: enabledHooks, sub: 'enabled / '+(s.hooks||[]).length+' total', cls: enabledHooks>0 ? '' : 'dim' },
463
+ { label: 'Reads (24h)', icon: icons.audit, value: reads, sub: writes+' writes \xB7 '+denied+' denied', cls: '' },
464
+ { label: 'Anomalies', icon: icons.anomaly, value: (s.anomalies||[]).length, sub: (s.anomalies||[]).length ? 'investigate now' : 'all clear', cls: (s.anomalies||[]).length ? 'danger' : 'green' }
465
+ ];
466
+ $('kpiStrip').innerHTML = items.map(k =>
467
+ '<div class="kpi"><div class="kpi-label">'+k.icon+esc(k.label)+'</div><div class="kpi-value '+k.cls+'">'+esc(k.value)+'</div><div class="kpi-sub">'+esc(k.sub)+'</div></div>'
468
+ ).join('');
469
+ }
470
+
471
+ function renderHealthCard(s){
472
+ const h=s.health;
473
+ const total=h.total||1;
474
+ const r=42, circ=2*Math.PI*r;
475
+ const slices=[
476
+ {v:h.healthy,c:'var(--accent)'},
477
+ {v:h.stale,c:'var(--warning)'},
478
+ {v:h.expired,c:'var(--danger)'},
479
+ {v:h.noDecay,c:'var(--text-dim)'}
480
+ ];
481
+ let offset=0;
482
+ let rings='';
483
+ for(const sl of slices){
484
+ const pct=sl.v/total;
485
+ const len=pct*circ;
486
+ rings+='<circle cx="50" cy="50" r="'+r+'" fill="none" stroke="'+sl.c+'" stroke-width="12" stroke-dasharray="'+len+' '+(circ-len)+'" stroke-dashoffset="-'+offset+'" stroke-linecap="round" opacity="0.85"/>';
487
+ offset+=len;
488
+ }
489
+ const sc=s.scopes||{global:0,project:0,team:0,org:0};
490
+ const scopeRow = '<div class="scope-row">'+
491
+ ['global','project','team','org'].filter(k=>sc[k]).map(k =>
492
+ '<span class="scope-pill"><strong>'+sc[k]+'</strong>'+k+'</span>'
493
+ ).join('') + '</div>';
494
+
495
+ return '<div class="card-title">'+icons.health+'Health Summary'+
496
+ '<span class="title-aside">'+esc(h.healthy)+'/'+esc(h.total)+' healthy</span></div>'+
497
+ '<div class="health-row">'+
498
+ '<div class="donut-wrap">'+
499
+ '<svg viewBox="0 0 100 100" width="100" height="100">'+rings+'</svg>'+
500
+ '<div class="donut-label">'+h.total+'<small>secrets</small></div>'+
501
+ '</div>'+
502
+ '<div class="health-legend">'+
503
+ '<div class="legend-item"><span class="legend-dot" style="background:var(--accent)"></span>Healthy '+h.healthy+'</div>'+
504
+ '<div class="legend-item"><span class="legend-dot" style="background:var(--warning)"></span>Stale '+h.stale+'</div>'+
505
+ '<div class="legend-item"><span class="legend-dot" style="background:var(--danger)"></span>Expired '+h.expired+'</div>'+
506
+ '<div class="legend-item"><span class="legend-dot" style="background:var(--text-dim)"></span>No decay '+h.noDecay+'</div>'+
507
+ '</div>'+
508
+ '</div>'+ scopeRow;
509
+ }
510
+
511
+ function renderEnvCard(s){
512
+ const env=s.environment;
513
+ const body = env
514
+ ? '<div class="env-status"><span class="env-big env-pill '+envClass(env.env)+'">'+esc(env.env)+'</span><span class="env-source">detected via '+esc(env.source)+'</span></div>'
515
+ : '<div class="empty">No environment detected.<span class="empty-cta">$ qring env --project-path .</span></div>';
516
+ return '<div class="card-title">'+icons.environment+'Environment'+'</div>'+ body;
517
+ }
518
+
519
+ function renderManifestCard(s){
520
+ const m=s.manifest;
521
+ if(!m){
522
+ return '<div class="card-title">'+icons.manifest+'Manifest</div>'+
523
+ '<div class="empty">No <code>.q-ring.json</code> manifest in this project.<span class="empty-cta">$ qring wizard &lt;name&gt;</span></div>';
524
+ }
525
+ const ok = m.required - m.missing.length - m.expired.length - m.stale.length;
526
+ const okPct = m.required ? Math.max(0, Math.round((ok/m.required)*100)) : 100;
527
+ const fillCol = m.missing.length ? 'var(--danger)' : (m.expired.length||m.stale.length ? 'var(--warning)' : 'var(--green)');
528
+
529
+ const list = [];
530
+ if(m.missing.length){
531
+ list.push('<div class="label">Missing required ('+m.missing.length+')</div><div>'+m.missing.map(k=>'<span class="key-pill miss">'+esc(k)+'</span>').join('')+'</div>');
532
+ }
533
+ if(m.expired.length){
534
+ list.push('<div class="label">Expired ('+m.expired.length+')</div><div>'+m.expired.map(k=>'<span class="key-pill exp">'+esc(k)+'</span>').join('')+'</div>');
535
+ }
536
+ if(m.stale.length){
537
+ list.push('<div class="label">Stale ('+m.stale.length+')</div><div>'+m.stale.map(k=>'<span class="key-pill exp">'+esc(k)+'</span>').join('')+'</div>');
538
+ }
539
+ if(!list.length) list.push('<div class="label">All required keys present and healthy.</div>');
540
+
541
+ return '<div class="card-title">'+icons.manifest+'Manifest'+
542
+ '<span class="title-aside">'+esc(m.required)+' required / '+esc(m.declared)+' declared</span></div>'+
543
+ '<div class="manifest-bars">'+
544
+ '<div class="manifest-row"><span style="min-width:54px">healthy</span><div class="manifest-bar"><div class="manifest-fill" style="width:'+okPct+'%;background:'+fillCol+'"></div></div><span>'+okPct+'%</span></div>'+
545
+ '</div>'+
546
+ '<div class="manifest-list">'+list.join('')+'</div>';
547
+ }
548
+
549
+ function renderPolicyCard(s){
550
+ const p=s.policy||{counts:{}};
551
+ const c=p.counts||{};
552
+ const has = p.hasMcpPolicy || p.hasExecPolicy || p.hasSecretPolicy;
553
+ if(!has){
554
+ return '<div class="card-title">'+icons.policy+'Policy</div>'+
555
+ '<div class="empty">No governance policy declared.<span class="empty-cta">add <code>policy</code> to <code>.q-ring.json</code></span></div>';
556
+ }
557
+ const row = (label,value) => '<div class="policy-row"><span class="policy-label">'+esc(label)+'</span><span class="policy-value '+(value?'':'zero')+'">'+esc(value || '\u2014')+'</span></div>';
558
+ return '<div class="card-title">'+icons.policy+'Policy'+
559
+ '<span class="title-aside">'+esc([
560
+ p.hasMcpPolicy?'mcp':'', p.hasExecPolicy?'exec':'', p.hasSecretPolicy?'secrets':''
561
+ ].filter(Boolean).join(' \xB7 ') || 'none')+'</span></div>'+
562
+ '<div class="policy-rows">'+
563
+ row('MCP allow tools', c.allowTools)+
564
+ row('MCP deny tools', c.denyTools)+
565
+ row('Denied keys', c.deniedKeys)+
566
+ row('Denied tags', c.deniedTags)+
567
+ row('Exec allow', c.allowCommands)+
568
+ row('Exec deny', c.denyCommands)+
569
+ row('Tag \u2192 approval', c.requireApprovalForTags)+
570
+ row('Tag \u2192 rotation', c.requireRotationFormatForTags)+
571
+ (p.maxTtlSeconds ? row('Max TTL', fmtDuration(p.maxTtlSeconds)) : '')+
572
+ (p.maxRuntimeSeconds ? row('Max exec runtime', fmtDuration(p.maxRuntimeSeconds)) : '')+
573
+ '</div>';
574
+ }
575
+
576
+ function renderDecayCard(s){
577
+ const withDecay = (s.secrets||[]).filter(x=>x.decay && x.decay.timeRemaining)
578
+ .sort((a,b)=>(a.decay.secondsRemaining||0)-(b.decay.secondsRemaining||0));
579
+ const inner = !withDecay.length
580
+ ? '<div class="empty">No secrets with decay configured.<span class="empty-cta">$ qring set KEY --ttl 86400</span></div>'
581
+ : '<div class="decay-list">'+withDecay.slice(0,12).map(x=>{
582
+ const pct=Math.min(x.decay.lifetimePercent,100);
583
+ const col=decayColor(pct,x.decay.isExpired);
584
+ const label=x.decay.isExpired?'expired':x.decay.timeRemaining||'';
585
+ return '<div class="decay-item"><span class="decay-key" title="'+esc(x.key)+'">'+esc(x.key)+'</span>'+
586
+ '<div class="decay-bar"><div class="decay-fill" style="width:'+pct+'%;background:'+col+'"></div></div>'+
587
+ '<span class="decay-time" style="color:'+col+'">'+esc(label)+'</span></div>';
588
+ }).join('')+'</div>';
589
+ return '<div class="card-title">'+icons.decay+'Decay Timers'+
590
+ '<span class="title-aside">'+esc(withDecay.length)+' tracked</span></div>'+ inner;
591
+ }
592
+
593
+ function renderSuperpositionCard(s){
594
+ const sup = (s.secrets||[]).filter(x=>x.type==='superposition' && x.environments && x.environments.length);
595
+ const inner = !sup.length
596
+ ? '<div class="empty">No secrets in superposition.<span class="empty-cta">$ qring set KEY --env prod</span></div>'
597
+ : '<div class="super-list">'+sup.slice(0,14).map(x=>{
598
+ const pills=(x.environments||[]).map(e =>
599
+ '<span class="env-pill '+envClass(e)+'">'+esc(e)+(e===x.defaultEnv?' \u2713':'')+'</span>'
600
+ ).join('');
601
+ return '<div class="super-item"><span class="super-key">'+esc(x.key)+'</span>'+pills+'</div>';
602
+ }).join('')+'</div>';
603
+ return '<div class="card-title">'+icons.superposition+'Superposition'+
604
+ '<span class="title-aside">'+esc(sup.length)+' multi-env</span></div>'+ inner;
605
+ }
606
+
607
+ function renderEntanglementCard(s){
608
+ const pairs=s.entanglements||[];
609
+ const seen=new Set();
610
+ const unique=pairs.filter(p=>{
611
+ const id=[p.source.service,p.source.key,p.target.service,p.target.key].sort().join('|');
612
+ if(seen.has(id)) return false;
613
+ seen.add(id);return true;
614
+ });
615
+ const inner = !unique.length
616
+ ? '<div class="empty">No entangled secrets.<span class="empty-cta">$ qring entangle KEY_A KEY_B</span></div>'
617
+ : '<div class="entangle-list">'+unique.slice(0,12).map(p =>
618
+ '<div class="entangle-pair"><span>'+esc(p.source.key)+'</span><span class="entangle-arrow">\u2194</span><span>'+esc(p.target.key)+'</span></div>'
619
+ ).join('')+'</div>';
620
+ return '<div class="card-title">'+icons.entangle+'Entanglement'+
621
+ '<span class="title-aside">'+esc(unique.length)+' pair'+(unique.length===1?'':'s')+'</span></div>'+ inner;
622
+ }
623
+
624
+ function renderTunnelsCard(s){
625
+ const tunnels=s.tunnels||[];
626
+ const inner = !tunnels.length
627
+ ? '<div class="empty">No active tunnels.<span class="empty-cta">$ qring tunnel create &lt;value&gt;</span></div>'
628
+ : '<div class="tunnel-list">'+tunnels.map(t=>{
629
+ const rem=t.expiresAt?Math.max(0,Math.floor((t.expiresAt-Date.now())/1000)):null;
630
+ return '<div class="tunnel-card">'+esc(t.id)+'<div class="tunnel-meta">'+
631
+ '<span>reads: '+t.accessCount+(t.maxReads?'/'+t.maxReads:'')+'</span>'+
632
+ (rem!==null?'<span>expires: '+rem+'s</span>':'<span>no expiry</span>')+
633
+ '</div></div>';
634
+ }).join('')+'</div>';
635
+ return '<div class="card-title">'+icons.tunnel+'Quantum Tunnels'+
636
+ '<span class="title-aside">'+esc(tunnels.length)+' live</span></div>'+ inner;
637
+ }
638
+
639
+ function renderApprovalsCard(s){
640
+ const list=s.approvals||[];
641
+ const inner = !list.length
642
+ ? '<div class="empty">No active approvals.<span class="empty-cta">$ qring approve KEY --for 1800 --reason "..."</span></div>'
643
+ : '<div class="approval-list">'+list.slice(0,8).map(a => {
644
+ const cls = a.tampered ? 'tampered' : (a.secondsRemaining < 300 ? 'expiring' : '');
645
+ return '<div class="approval-card '+cls+'">'+
646
+ '<div class="approval-head"><span>'+esc(a.key)+(a.tampered?' \u26A0 TAMPERED':'')+'</span><span>'+esc(fmtDuration(a.secondsRemaining))+' left</span></div>'+
647
+ '<div class="approval-reason">'+esc(a.reason||'(no reason)')+'</div>'+
648
+ '<div class="approval-meta"><span>scope:'+esc(a.scope)+'</span><span>by:'+esc(a.grantedBy)+'</span></div>'+
649
+ '</div>';
650
+ }).join('')+'</div>';
651
+ return '<div class="card-title">'+icons.approve+'Approvals'+
652
+ '<span class="title-aside">'+esc(list.filter(a=>a.valid).length)+' valid</span></div>'+ inner;
653
+ }
654
+
655
+ function renderHooksCard(s){
656
+ const list=s.hooks||[];
657
+ const inner = !list.length
658
+ ? '<div class="empty">No hooks registered.<span class="empty-cta">$ qring hook add --tag payments --action rotate --exec "..."</span></div>'
659
+ : '<div class="hooks-list">'+list.slice(0,8).map(h =>
660
+ '<div class="hook-row '+(h.enabled?'':'disabled')+'">'+
661
+ '<span class="hook-type '+esc(h.type)+'">'+esc(h.type)+'</span>'+
662
+ '<span class="hook-summary" title="'+esc(h.matchSummary)+'">'+esc(h.description||h.matchSummary)+'</span>'+
663
+ '<span class="hook-id">'+esc(h.id)+'</span>'+
664
+ '</div>'
665
+ ).join('')+'</div>';
666
+ return '<div class="card-title">'+icons.hook+'Hooks'+
667
+ '<span class="title-aside">'+esc(list.filter(h=>h.enabled).length)+' enabled / '+esc(list.length)+'</span></div>'+ inner;
668
+ }
669
+
670
+ function renderMemoryCard(s){
671
+ const inner = '<div class="empty" style="display:flex;align-items:baseline;gap:8px;font-style:normal">'+
672
+ '<span style="font-size:1.6rem;font-weight:700;color:var(--text-primary);font-family:var(--font-display)">'+esc(s.memoryKeys||0)+'</span>'+
673
+ '<span>memory key'+(s.memoryKeys===1?'':'s')+' encrypted at <code>~/.config/q-ring/agent-memory.enc</code></span>'+
674
+ '</div>';
675
+ return '<div class="card-title">'+icons.memory+'Agent Memory</div>'+ inner;
676
+ }
677
+
678
+ function renderAnomalies(s){
679
+ const list=s.anomalies||[];
680
+ if(!list.length) return '<div class="card-title">'+icons.anomaly+'Anomaly Alerts<span class="title-aside" style="color:var(--green)">all clear</span></div>'+
681
+ '<div class="empty">No anomalies detected \u2014 quantum field is stable.</div>';
682
+ return '<div class="card-title">'+icons.anomaly+'Anomaly Alerts'+
683
+ '<span class="title-aside" style="color:var(--danger)">'+esc(list.length)+' active</span></div>'+
684
+ '<div class="anomaly-list">'+list.map(a=>{
685
+ const hint = a.type==='tampered' ? '$ qring audit:verify' :
686
+ a.type==='burst' ? '$ qring audit --key \u2026 --action read' :
687
+ a.type==='unusual-hour' ? '$ qring audit --action read --since "1am"' :
688
+ '$ qring audit --limit 100';
689
+ return '<div class="anomaly-card"><div class="anomaly-type">'+esc(a.type)+'</div><div class="anomaly-desc">'+esc(a.description)+'</div><div class="anomaly-hint">'+esc(hint)+'</div></div>';
690
+ }).join('')+'</div>';
691
+ }
692
+
693
+ /* --- Secrets table --- */
694
+
695
+ function renderSecretsSection(){
696
+ const s = state.snapshot;
697
+ if(!s) return '';
698
+ const filtered = filterSecrets(s.secrets||[]);
699
+ sortRows(filtered, state.secretsSort);
700
+
701
+ return '<div class="card grid-wide" style="margin-bottom:16px">'+
702
+ '<div class="card-title">'+icons.key+'Secrets'+
703
+ '<span class="title-aside">'+filtered.length+' of '+(s.secrets||[]).length+'</span></div>'+
704
+ '<div class="secrets-toolbar">'+
705
+ '<label class="search">'+icons.search+'<input id="secretsSearch" type="search" placeholder="Filter by key, scope, env, tag, provider\u2026" autocomplete="off" value="'+esc(state.secretsQuery)+'"/></label>'+
706
+ '<button class="btn" type="button" data-quick="expired">'+esc((s.health.expired||0))+' expired</button>'+
707
+ '<button class="btn" type="button" data-quick="stale">'+esc((s.health.stale||0))+' stale</button>'+
708
+ '<button class="btn" type="button" data-quick="protected">'+esc(s.protectedCount||0)+' protected</button>'+
709
+ '<button class="btn" type="button" data-quick="">clear</button>'+
710
+ '</div>'+
711
+ '<div class="secrets-table-wrap">'+ renderTable(filtered) +'</div>'+
712
+ '</div>';
713
+ }
714
+
715
+ function renderTable(rows){
716
+ if(!rows.length) return '<div class="empty" style="padding:18px;text-align:center">No secrets match the filter.</div>';
717
+ const cols = [
718
+ { id:'key', label:'Key' },
719
+ { id:'scope', label:'Scope' },
720
+ { id:'env', label:'Env' },
721
+ { id:'type', label:'Type' },
722
+ { id:'decay', label:'Decay' },
723
+ { id:'tags', label:'Tags' },
724
+ { id:'lastAccessedAt', label:'Last read' }
725
+ ];
726
+ const sort = state.secretsSort;
727
+ const head = '<thead><tr>'+cols.map(c =>
728
+ '<th data-sort="'+c.id+'" class="'+(sort.col===c.id?'sorted':'')+'">'+esc(c.label)+'<span class="sort-arrow">'+(sort.dir==='asc'?'\u25B2':'\u25BC')+'</span></th>'
729
+ ).join('')+'</tr></thead>';
730
+ const body = '<tbody>'+rows.map(r=>{
731
+ const env = r.type==='superposition'
732
+ ? (r.environments||[]).map(e=>'<span class="env-pill '+envClass(e)+'" style="margin-right:3px">'+esc(e)+(e===r.defaultEnv?' \u2713':'')+'</span>').join('')
733
+ : '<span class="env-pill env-default">\u2014</span>';
734
+ const decayHtml = r.decay && r.decay.timeRemaining
735
+ ? (function(){
736
+ const pct=Math.min(r.decay.lifetimePercent,100);
737
+ const col=decayColor(pct,r.decay.isExpired);
738
+ return '<span class="mini-decay"><span class="mini-decay-bar"><span class="mini-decay-fill" style="width:'+pct+'%;background:'+col+'"></span></span><span class="mini-decay-time" style="color:'+col+'">'+esc(r.decay.isExpired?'expired':r.decay.timeRemaining)+'</span></span>';
739
+ })()
740
+ : '<span class="mini-decay-time">\u2014</span>';
741
+ const tags = (r.tags||[]).slice(0,3).map(t=>'<span class="tag-pill">'+esc(t)+'</span>').join('') + ((r.tags||[]).length>3?'+'+((r.tags||[]).length-3):'');
742
+ const protectedIcon = r.requiresApproval ? '<span class="protected-icon" title="requires approval for MCP read">'+icons.lock+'</span>' : '';
743
+ return '<tr>'+
744
+ '<td class="col-key" title="'+esc(r.key)+'">'+esc(r.key)+protectedIcon+'</td>'+
745
+ '<td><span class="scope-tag '+esc(r.scope)+'">'+esc(r.scope)+'</span></td>'+
746
+ '<td>'+env+'</td>'+
747
+ '<td><span class="type-tag '+esc(r.type)+'">'+esc(r.type)+'</span></td>'+
748
+ '<td class="col-decay">'+decayHtml+'</td>'+
749
+ '<td class="col-tags">'+tags+'</td>'+
750
+ '<td>'+esc(fmtRelative(r.lastAccessedAt))+'</td>'+
751
+ '</tr>';
752
+ }).join('')+'</tbody>';
753
+ return '<table class="secrets-table">'+head+body+'</table>';
754
+ }
755
+
756
+ function filterSecrets(rows){
757
+ const q=state.secretsQuery.trim().toLowerCase();
758
+ if(!q) return rows.slice();
759
+ if(q==='expired') return rows.filter(r=>r.decay && r.decay.isExpired);
760
+ if(q==='stale') return rows.filter(r=>r.decay && r.decay.isStale && !r.decay.isExpired);
761
+ if(q==='protected') return rows.filter(r=>r.requiresApproval);
762
+ return rows.filter(r=>{
763
+ const hay = [r.key, r.scope, r.type, r.provider||'', r.defaultEnv||'',
764
+ (r.environments||[]).join(' '), (r.tags||[]).join(' ')].join(' ').toLowerCase();
765
+ return hay.indexOf(q)!==-1;
766
+ });
767
+ }
768
+
769
+ function sortRows(rows, sort){
770
+ const dir = sort.dir==='asc' ? 1 : -1;
771
+ rows.sort((a,b)=>{
772
+ let av, bv;
773
+ switch(sort.col){
774
+ case 'key': av=a.key; bv=b.key; break;
775
+ case 'scope': av=a.scope; bv=b.scope; break;
776
+ case 'env': av=a.defaultEnv||(a.environments||[])[0]||''; bv=b.defaultEnv||(b.environments||[])[0]||''; break;
777
+ case 'type': av=a.type; bv=b.type; break;
778
+ case 'decay': av=a.decay && a.decay.secondsRemaining!=null?a.decay.secondsRemaining:Infinity; bv=b.decay && b.decay.secondsRemaining!=null?b.decay.secondsRemaining:Infinity; break;
779
+ case 'tags': av=(a.tags||[]).join(','); bv=(b.tags||[]).join(','); break;
780
+ case 'lastAccessedAt':
781
+ default: av=a.lastAccessedAt?new Date(a.lastAccessedAt).getTime():0; bv=b.lastAccessedAt?new Date(b.lastAccessedAt).getTime():0;
782
+ }
783
+ if(av<bv) return -1*dir;
784
+ if(av>bv) return 1*dir;
785
+ return 0;
786
+ });
787
+ }
788
+
789
+ /* --- Audit feed --- */
790
+
791
+ function renderAuditCard(s){
792
+ const events = s.audit || [];
793
+ const m = s.auditMetrics || { byAction:{}, bySource:{} };
794
+ const filtered = events.filter(e =>{
795
+ if(state.auditFilter.action && e.action !== state.auditFilter.action) return false;
796
+ if(state.auditFilter.source && e.source !== state.auditFilter.source) return false;
797
+ const txt=state.auditFilter.text.trim().toLowerCase();
798
+ if(txt){
799
+ const hay = [e.key||'', e.action, e.source, e.detail||'', e.scope||'', e.env||''].join(' ').toLowerCase();
800
+ if(hay.indexOf(txt)===-1) return false;
801
+ }
802
+ return true;
803
+ });
804
+
805
+ const allActions = ['read','write','delete','rotate','generate','entangle','tunnel','teleport','approve','revoke','policy_deny','collapse','export'];
806
+ const actionChips = allActions.filter(a=>m.byAction[a])
807
+ .map(a=>'<span class="audit-chip '+(state.auditFilter.action===a?'active':'')+'" data-act="'+a+'">'+a+'<strong>'+m.byAction[a]+'</strong></span>')
808
+ .join('');
809
+ const allSources = ['cli','mcp','agent','ci','hook','api'];
810
+ const sourceChips = allSources.filter(src=>m.bySource[src])
811
+ .map(src=>'<span class="audit-chip '+(state.auditFilter.source===src?'active':'')+'" data-src="'+src+'">'+src+'<strong>'+m.bySource[src]+'</strong></span>')
812
+ .join('');
813
+
814
+ const feed = !filtered.length
815
+ ? '<div class="empty">No audit events match the filter.</div>'
816
+ : '<div class="audit-feed">'+filtered.slice(0,80).map(e =>
817
+ '<div class="audit-row">'+
818
+ '<span class="audit-ts" title="'+esc(e.timestamp)+'">'+esc(fmtTime(e.timestamp))+'</span>'+
819
+ '<span class="audit-action '+esc(e.action)+'">'+esc(e.action)+'</span>'+
820
+ '<span class="audit-source">'+esc(e.source)+'</span>'+
821
+ '<span><span class="audit-key">'+esc(e.key||'\u2014')+'</span> <span class="audit-detail">'+esc(e.detail||'')+'</span></span>'+
822
+ '</div>'
823
+ ).join('')+'</div>';
824
+
825
+ return '<div class="card-title">'+icons.audit+'Audit Log (24h)'+
826
+ '<span class="title-aside">'+esc(filtered.length)+' of '+esc(events.length)+' shown \xB7 window '+esc((s.auditMetrics?.windowSeconds||86400)/3600)+'h</span></div>'+
827
+ '<div class="audit-actions-strip">'+(actionChips||'<span class="empty" style="padding:0">no actions</span>')+'</div>'+
828
+ (sourceChips ? '<div class="audit-actions-strip">'+sourceChips+'</div>' : '')+
829
+ '<div class="audit-toolbar">'+
830
+ '<label class="search">'+icons.search+'<input id="auditSearch" type="search" placeholder="Filter by key, detail, scope\u2026" autocomplete="off" value="'+esc(state.auditFilter.text)+'"/></label>'+
831
+ '<button class="btn" type="button" id="auditClear">clear</button>'+
832
+ '</div>'+ feed;
833
+ }
834
+
835
+ /* --- Top-level layout render --- */
836
+
837
+ /**
838
+ * Replace innerHTML on a host element while preserving the focused
839
+ * input/textarea inside it, including caret position. Without this guard
840
+ * each 5-second SSE snapshot would reset whatever the user is typing in
841
+ * the secrets / audit search boxes.
842
+ */
843
+ function setHtmlPreservingFocus(host, html){
844
+ const active = document.activeElement;
845
+ const insideHost = active && host.contains(active);
846
+ let focusId, selStart, selEnd, scrollTop;
847
+ if(insideHost && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA')){
848
+ focusId = active.id;
849
+ try { selStart = active.selectionStart; selEnd = active.selectionEnd; } catch(_) { /* type lacks selection */ }
850
+ }
851
+ if(insideHost){
852
+ const scroller = active && active.closest && active.closest('.audit-feed,.secrets-table-wrap,.decay-list,.super-list,.entangle-list,.tunnel-list,.approval-list,.hooks-list');
853
+ if(scroller) scrollTop = scroller.scrollTop;
854
+ }
855
+ host.innerHTML = html;
856
+ if(focusId){
857
+ const next = document.getElementById(focusId);
858
+ if(next){
859
+ next.focus();
860
+ try { if(selStart != null) next.setSelectionRange(selStart, selEnd ?? selStart); } catch(_) { /* ignore */ }
861
+ }
862
+ }
863
+ if(scrollTop != null){
864
+ const scroller = host.querySelector('.audit-feed,.secrets-table-wrap,.decay-list,.super-list,.entangle-list,.tunnel-list,.approval-list,.hooks-list');
865
+ if(scroller) scroller.scrollTop = scrollTop;
866
+ }
867
+ }
868
+
869
+ function render(snap){
870
+ state.snapshot = snap;
871
+ renderHeaderMeta(snap);
872
+ renderKpis(snap);
873
+
874
+ setHtmlPreservingFocus($('overviewGrid'), [
875
+ '<div class="card" style="animation-delay:0ms">'+renderHealthCard(snap)+'</div>',
876
+ '<div class="card" style="animation-delay:60ms">'+renderEnvCard(snap)+'</div>',
877
+ '<div class="card" style="animation-delay:120ms">'+renderManifestCard(snap)+'</div>',
878
+ '<div class="card" style="animation-delay:180ms">'+renderPolicyCard(snap)+'</div>'
879
+ ].join(''));
880
+
881
+ setHtmlPreservingFocus($('secretsSection'), renderSecretsSection());
882
+
883
+ setHtmlPreservingFocus($('quantumGrid'), [
884
+ '<div class="card" style="animation-delay:0ms">'+renderDecayCard(snap)+'</div>',
885
+ '<div class="card" style="animation-delay:60ms">'+renderSuperpositionCard(snap)+'</div>',
886
+ '<div class="card" style="animation-delay:120ms">'+renderEntanglementCard(snap)+'</div>',
887
+ '<div class="card" style="animation-delay:180ms">'+renderTunnelsCard(snap)+'</div>'
888
+ ].join(''));
889
+
890
+ setHtmlPreservingFocus($('govGrid'), [
891
+ '<div class="card" style="animation-delay:0ms">'+renderApprovalsCard(snap)+'</div>',
892
+ '<div class="card" style="animation-delay:60ms">'+renderHooksCard(snap)+'</div>',
893
+ '<div class="card" style="animation-delay:120ms">'+renderMemoryCard(snap)+'</div>'
894
+ ].join(''));
895
+
896
+ setHtmlPreservingFocus($('anomalyAuditGrid'), [
897
+ '<div class="card grid-wide" style="animation-delay:0ms">'+renderAnomalies(snap)+'</div>',
898
+ '<div class="card grid-wide" style="animation-delay:60ms">'+renderAuditCard(snap)+'</div>'
899
+ ].join(''));
900
+
901
+ bindDelegated();
902
+
903
+ $('lastUpdate').textContent = 'updated '+fmtRelative(snap.timestamp);
904
+ const m = snap.auditMetrics || { total:0 };
905
+ $('footMeta').textContent = 'q-ring v'+snap.version+' \xB7 snapshot '+fmtTime(snap.timestamp)+' \xB7 '+m.total+' audit events in last 24h';
906
+ }
907
+
908
+ /* --- Event delegation --- */
909
+
910
+ let bound = false;
911
+ function bindDelegated(){
912
+ if(bound) return;
913
+ bound = true;
914
+
915
+ document.addEventListener('input', (e)=>{
916
+ const t = e.target;
917
+ if(t.id === 'secretsSearch'){
918
+ state.secretsQuery = t.value;
919
+ setHtmlPreservingFocus($('secretsSection'), renderSecretsSection());
920
+ } else if(t.id === 'auditSearch'){
921
+ state.auditFilter.text = t.value;
922
+ rerenderAudit();
923
+ }
924
+ });
925
+
926
+ document.addEventListener('click', (e)=>{
927
+ const t = e.target.closest('[data-quick],[data-act],[data-src],th[data-sort],#auditClear');
928
+ if(!t) return;
929
+ if(t.matches('[data-quick]')){
930
+ state.secretsQuery = t.getAttribute('data-quick');
931
+ setHtmlPreservingFocus($('secretsSection'), renderSecretsSection());
932
+ } else if(t.matches('[data-act]')){
933
+ const a = t.getAttribute('data-act');
934
+ state.auditFilter.action = state.auditFilter.action === a ? '' : a;
935
+ rerenderAudit();
936
+ } else if(t.matches('[data-src]')){
937
+ const src = t.getAttribute('data-src');
938
+ state.auditFilter.source = state.auditFilter.source === src ? '' : src;
939
+ rerenderAudit();
940
+ } else if(t.matches('th[data-sort]')){
941
+ const col = t.getAttribute('data-sort');
942
+ if(state.secretsSort.col === col){
943
+ state.secretsSort.dir = state.secretsSort.dir === 'asc' ? 'desc' : 'asc';
944
+ } else {
945
+ state.secretsSort = { col, dir: col==='key' ? 'asc' : 'desc' };
946
+ }
947
+ setHtmlPreservingFocus($('secretsSection'), renderSecretsSection());
948
+ } else if(t.id === 'auditClear'){
949
+ state.auditFilter = { action:'', source:'', text:'' };
950
+ rerenderAudit();
951
+ }
952
+ });
953
+ }
954
+
955
+ function rerenderAudit(){
956
+ if(!state.snapshot) return;
957
+ setHtmlPreservingFocus($('anomalyAuditGrid'), [
958
+ '<div class="card grid-wide">'+renderAnomalies(state.snapshot)+'</div>',
959
+ '<div class="card grid-wide">'+renderAuditCard(state.snapshot)+'</div>'
960
+ ].join(''));
961
+ }
962
+
963
+ /* --- Pause / refresh / shortcuts --- */
964
+
965
+ $('pauseBtn').addEventListener('click', togglePause);
966
+ $('refreshBtn').addEventListener('click', forceRefresh);
967
+ document.addEventListener('keydown', (e)=>{
968
+ if(e.target && (e.target.tagName==='INPUT' || e.target.tagName==='TEXTAREA')){
969
+ if(e.key==='Escape'){ e.target.blur(); }
970
+ return;
971
+ }
972
+ if(e.key==='/'){
973
+ e.preventDefault();
974
+ const f=$('secretsSearch'); if(f) f.focus();
975
+ } else if(e.key==='p' || e.key==='P'){
976
+ togglePause();
977
+ } else if(e.key==='r' || e.key==='R'){
978
+ forceRefresh();
979
+ }
980
+ });
981
+
982
+ function togglePause(){
983
+ state.paused = !state.paused;
984
+ $('pauseLabel').textContent = state.paused ? 'Resume' : 'Pause';
985
+ $('connDot').classList.toggle('paused', state.paused);
986
+ $('connText').textContent = state.paused ? 'paused' : 'live';
987
+ }
988
+
989
+ function forceRefresh(){
990
+ fetch('/api/status', {cache:'no-store'}).then(r=>r.json()).then(s=>render(s)).catch(()=>{});
991
+ }
992
+
993
+ /* --- SSE connection --- */
994
+
995
+ const dot = $('connDot');
996
+ const connText = $('connText');
997
+
998
+ function connect(){
999
+ const es=new EventSource('/events');
1000
+ es.onopen=()=>{
1001
+ dot.classList.remove('disconnected');
1002
+ if(!state.paused){
1003
+ dot.classList.remove('paused');
1004
+ connText.textContent='live';
1005
+ }
1006
+ };
1007
+ es.onmessage=(e)=>{
1008
+ if(state.paused) return;
1009
+ try{ render(JSON.parse(e.data)); }catch(err){ console.error('render error',err); }
1010
+ };
1011
+ es.onerror=()=>{
1012
+ dot.classList.add('disconnected');
1013
+ connText.textContent='reconnecting\u2026';
1014
+ };
1015
+ }
1016
+
1017
+ connect();
1018
+
1019
+ // refresh the relative timestamp every 5s so it stays accurate while paused
1020
+ setInterval(()=>{
1021
+ if(state.snapshot){
1022
+ $('lastUpdate').textContent = 'updated '+fmtRelative(state.snapshot.timestamp);
1023
+ }
1024
+ }, 5000);
1025
+ })();
1026
+ </script>
1027
+ </body>
1028
+ </html>`;
1029
+ }
1030
+
1031
+ // src/core/dashboard.ts
1032
+ var AUDIT_WINDOW_SECONDS = 24 * 60 * 60;
1033
+ function toSecretSnapshot(entry) {
1034
+ const envelope = entry.envelope;
1035
+ const decay = envelope ? checkDecay(envelope) : {
1036
+ isExpired: false,
1037
+ isStale: false,
1038
+ lifetimePercent: 0,
1039
+ secondsRemaining: null,
1040
+ timeRemaining: null
1041
+ };
1042
+ return {
1043
+ key: entry.key,
1044
+ scope: entry.scope,
1045
+ type: envelope?.states ? "superposition" : "collapsed",
1046
+ environments: envelope?.states ? Object.keys(envelope.states) : void 0,
1047
+ defaultEnv: envelope?.defaultEnv,
1048
+ decay,
1049
+ accessCount: envelope?.meta.accessCount ?? 0,
1050
+ lastAccessedAt: envelope?.meta.lastAccessedAt,
1051
+ createdAt: envelope?.meta.createdAt ?? "",
1052
+ updatedAt: envelope?.meta.updatedAt ?? "",
1053
+ description: envelope?.meta.description,
1054
+ tags: envelope?.meta.tags,
1055
+ entangled: envelope?.meta.entangled,
1056
+ provider: envelope?.meta.provider,
1057
+ requiresApproval: envelope?.meta.requiresApproval,
1058
+ jitProvider: envelope?.meta.jitProvider,
1059
+ hasRotationFormat: !!envelope?.meta.rotationFormat
1060
+ };
1061
+ }
1062
+ function summariseHookMatch(match) {
1063
+ const parts = [];
1064
+ if (match.key) parts.push(`key=${match.key}`);
1065
+ if (match.keyPattern) parts.push(`pattern=${match.keyPattern}`);
1066
+ if (match.tag) parts.push(`tag=${match.tag}`);
1067
+ if (match.scope) parts.push(`scope=${match.scope}`);
1068
+ if (match.action?.length) parts.push(`on=${match.action.join("|")}`);
1069
+ return parts.length ? parts.join(" \xB7 ") : "any change";
1070
+ }
1071
+ function buildManifest(projectPath, secrets) {
1072
+ const config = readProjectConfig(projectPath);
1073
+ if (!config?.secrets) return null;
1074
+ const declared = Object.keys(config.secrets);
1075
+ const projectSecrets = new Map(
1076
+ secrets.filter((s) => s.scope === "project").map((s) => [s.key, s])
1077
+ );
1078
+ const required = [];
1079
+ const missing = [];
1080
+ const expired = [];
1081
+ const stale = [];
1082
+ for (const key of declared) {
1083
+ const entry = config.secrets[key];
1084
+ if (entry.required) required.push(key);
1085
+ const present = projectSecrets.get(key);
1086
+ if (!present) {
1087
+ if (entry.required) missing.push(key);
1088
+ continue;
1089
+ }
1090
+ if (present.decay.isExpired) expired.push(key);
1091
+ else if (present.decay.isStale) stale.push(key);
1092
+ }
1093
+ return {
1094
+ declared: declared.length,
1095
+ required: required.length,
1096
+ missing,
1097
+ expired,
1098
+ stale
1099
+ };
1100
+ }
1101
+ function buildPolicySnapshot(projectPath) {
1102
+ const summary = getPolicySummary(projectPath);
1103
+ const mcp = summary.details.mcp ?? {};
1104
+ const exec = summary.details.exec ?? {};
1105
+ const sec = summary.details.secrets ?? {};
1106
+ return {
1107
+ hasMcpPolicy: summary.hasMcpPolicy,
1108
+ hasExecPolicy: summary.hasExecPolicy,
1109
+ hasSecretPolicy: summary.hasSecretPolicy,
1110
+ counts: {
1111
+ allowTools: mcp.allowTools?.length ?? 0,
1112
+ denyTools: mcp.denyTools?.length ?? 0,
1113
+ deniedKeys: mcp.deniedKeys?.length ?? 0,
1114
+ deniedTags: mcp.deniedTags?.length ?? 0,
1115
+ allowCommands: exec.allowCommands?.length ?? 0,
1116
+ denyCommands: exec.denyCommands?.length ?? 0,
1117
+ requireApprovalForTags: sec.requireApprovalForTags?.length ?? 0,
1118
+ requireRotationFormatForTags: sec.requireRotationFormatForTags?.length ?? 0
1119
+ },
1120
+ maxTtlSeconds: sec.maxTtlSeconds,
1121
+ maxRuntimeSeconds: exec.maxRuntimeSeconds
1122
+ };
1123
+ }
1124
+ function buildAuditMetrics(events) {
1125
+ const byAction = {};
1126
+ const bySource = {};
1127
+ const readCounts = /* @__PURE__ */ new Map();
1128
+ for (const e of events) {
1129
+ byAction[e.action] = (byAction[e.action] ?? 0) + 1;
1130
+ bySource[e.source] = (bySource[e.source] ?? 0) + 1;
1131
+ if (e.action === "read" && e.key) {
1132
+ readCounts.set(e.key, (readCounts.get(e.key) ?? 0) + 1);
1133
+ }
1134
+ }
1135
+ const topRead = [...readCounts.entries()].map(([key, reads]) => ({ key, reads })).sort((a, b) => b.reads - a.reads).slice(0, 10);
1136
+ return {
1137
+ byAction,
1138
+ bySource,
1139
+ topRead,
1140
+ total: events.length,
1141
+ windowSeconds: AUDIT_WINDOW_SECONDS
1142
+ };
1143
+ }
1144
+ function collectSnapshot() {
1145
+ const projectPath = process.cwd();
1146
+ const entries = listSecrets({ source: "api", silent: true, projectPath });
1147
+ const secrets = entries.map(toSecretSnapshot);
1148
+ let healthy = 0;
1149
+ let stale = 0;
1150
+ let expired = 0;
1151
+ let noDecay = 0;
1152
+ let protectedCount = 0;
1153
+ const scopes = { global: 0, project: 0, team: 0, org: 0 };
1154
+ for (const s of secrets) {
1155
+ if (!s.decay.timeRemaining) noDecay++;
1156
+ else if (s.decay.isExpired) expired++;
1157
+ else if (s.decay.isStale) stale++;
1158
+ else healthy++;
1159
+ if (s.requiresApproval) protectedCount++;
1160
+ if (s.scope === "global") scopes.global++;
1161
+ else if (s.scope === "project") scopes.project++;
1162
+ else if (s.scope === "team") scopes.team++;
1163
+ else if (s.scope === "org") scopes.org++;
1164
+ }
1165
+ const auditWindow = queryAudit({
1166
+ since: new Date(Date.now() - AUDIT_WINDOW_SECONDS * 1e3).toISOString()
1167
+ }).filter((e) => e.action !== "list");
1168
+ const recent = auditWindow.slice(0, 80);
1169
+ const approvals = listApprovals().map((a) => ({
1170
+ id: a.id,
1171
+ key: a.key,
1172
+ scope: a.scope,
1173
+ reason: a.reason,
1174
+ grantedBy: a.grantedBy,
1175
+ grantedAt: a.grantedAt,
1176
+ expiresAt: a.expiresAt,
1177
+ secondsRemaining: Math.floor(
1178
+ (new Date(a.expiresAt).getTime() - Date.now()) / 1e3
1179
+ ),
1180
+ valid: a.valid && !a.tampered,
1181
+ tampered: a.tampered
1182
+ }));
1183
+ const hookEntries = listHooks().map((h) => ({
1184
+ id: h.id,
1185
+ type: h.type,
1186
+ description: h.description,
1187
+ enabled: h.enabled,
1188
+ match: h.match,
1189
+ matchSummary: summariseHookMatch(h.match)
1190
+ }));
1191
+ return {
1192
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1193
+ version: PACKAGE_VERSION,
1194
+ projectPath,
1195
+ secrets,
1196
+ health: { healthy, stale, expired, noDecay, total: secrets.length },
1197
+ scopes,
1198
+ protectedCount,
1199
+ entanglements: listEntanglements(),
1200
+ tunnels: tunnelList(),
1201
+ audit: recent,
1202
+ auditMetrics: buildAuditMetrics(auditWindow),
1203
+ anomalies: detectAnomalies(),
1204
+ environment: collapseEnvironment({ projectPath }),
1205
+ manifest: buildManifest(projectPath, secrets),
1206
+ policy: buildPolicySnapshot(projectPath),
1207
+ approvals,
1208
+ hooks: hookEntries,
1209
+ memoryKeys: listMemory().length
1210
+ };
1211
+ }
1212
+ function startDashboardServer(options = {}) {
1213
+ const port = options.port ?? 9876;
1214
+ const clients = /* @__PURE__ */ new Set();
1215
+ let intervalHandle = null;
1216
+ const html = getDashboardHtml();
1217
+ function broadcast() {
1218
+ const snapshot = collectSnapshot();
1219
+ const data = `data: ${JSON.stringify(snapshot)}
1220
+
1221
+ `;
1222
+ for (const res of clients) {
1223
+ if (res.writableEnded || res.destroyed) {
1224
+ clients.delete(res);
1225
+ continue;
1226
+ }
1227
+ try {
1228
+ const ok = res.write(data);
1229
+ if (!ok) {
1230
+ clients.delete(res);
1231
+ try {
1232
+ res.end();
1233
+ } catch {
1234
+ try {
1235
+ res.destroy();
1236
+ } catch {
1237
+ }
1238
+ }
1239
+ }
1240
+ } catch {
1241
+ clients.delete(res);
1242
+ try {
1243
+ res.end();
1244
+ } catch {
1245
+ try {
1246
+ res.destroy();
1247
+ } catch {
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ }
1253
+ const server = createServer((req, res) => {
1254
+ let pathname;
1255
+ try {
1256
+ ({ pathname } = new URL(req.url ?? "/", "http://127.0.0.1"));
1257
+ } catch {
1258
+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
1259
+ res.end("Bad Request: invalid URL");
1260
+ return;
1261
+ }
1262
+ if (pathname === "/events") {
1263
+ res.writeHead(200, {
1264
+ "Content-Type": "text/event-stream",
1265
+ "Cache-Control": "no-cache",
1266
+ Connection: "keep-alive"
1267
+ });
1268
+ const snapshot = collectSnapshot();
1269
+ res.write(`data: ${JSON.stringify(snapshot)}
1270
+
1271
+ `);
1272
+ clients.add(res);
1273
+ req.on("close", () => clients.delete(res));
1274
+ return;
1275
+ }
1276
+ if (pathname === "/api/status") {
1277
+ const snapshot = collectSnapshot();
1278
+ res.writeHead(200, {
1279
+ "Content-Type": "application/json"
1280
+ });
1281
+ res.end(JSON.stringify(snapshot, null, 2));
1282
+ return;
1283
+ }
1284
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1285
+ res.end(html);
1286
+ });
1287
+ server.listen(port, "127.0.0.1", () => {
1288
+ intervalHandle = setInterval(broadcast, 5e3);
1289
+ if (intervalHandle && typeof intervalHandle === "object" && "unref" in intervalHandle) {
1290
+ intervalHandle.unref();
1291
+ }
1292
+ });
1293
+ return {
1294
+ port,
1295
+ close: () => {
1296
+ if (intervalHandle) clearInterval(intervalHandle);
1297
+ for (const res of clients) {
1298
+ try {
1299
+ res.end();
1300
+ } catch {
1301
+ }
1302
+ }
1303
+ clients.clear();
1304
+ server.close();
1305
+ },
1306
+ server
1307
+ };
1308
+ }
1309
+ export {
1310
+ collectSnapshot,
1311
+ startDashboardServer
1312
+ };
1313
+ //# sourceMappingURL=dashboard-FSCJDLJX.js.map