datapi-selfheal 0.3.0__py3-none-any.whl

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,1094 @@
1
+ """Self-contained XSS-safe HTML5 Drift Console dashboard renderer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import time
7
+ import urllib.parse
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+
13
+ class DashboardSnapshot(BaseModel, frozen=True):
14
+ """Immutable snapshot of tenant drift telemetry and quota state for the Drift Console."""
15
+
16
+ org_id: str
17
+ plan: str
18
+ requests_per_minute_limit: int
19
+ llm_calls_limit: int
20
+ total_events: int
21
+ drifted_events: int
22
+ unique_fingerprints: int
23
+ prs_opened: int
24
+ recent_events: list[dict[str, Any]] = Field(default_factory=list)
25
+ status_filter: str = "all"
26
+
27
+
28
+ def _esc(value: object) -> str:
29
+ """Escape any dynamic value for safe HTML5 text and attribute interpolation."""
30
+ return html.escape(str(value), quote=True)
31
+
32
+
33
+ def _format_event_field_summary(event: dict[str, Any]) -> str:
34
+ """Summarize redacted drift field metadata from an event record."""
35
+ parts: list[str] = []
36
+ missing = event.get("missing_fields")
37
+ if isinstance(missing, list) and missing:
38
+ joined = ", ".join(_esc(item) for item in missing)
39
+ parts.append(f"missing: [{joined}]")
40
+ extra = event.get("extra_fields")
41
+ if isinstance(extra, list) and extra:
42
+ joined = ", ".join(_esc(item) for item in extra)
43
+ parts.append(f"extra: [{joined}]")
44
+ detail = event.get("detail") or event.get("summary")
45
+ if detail and not parts:
46
+ parts.append(_esc(detail))
47
+ if not parts and "issue_count" in event:
48
+ kinds = event.get("issue_kinds")
49
+ if isinstance(kinds, (list, tuple)) and kinds:
50
+ joined = ", ".join(_esc(k) for k in kinds)
51
+ parts.append(f"{_esc(event.get('issue_count', 0))} issues ({joined})")
52
+ else:
53
+ parts.append(f"{_esc(event.get('issue_count', 0))} issues")
54
+ return "; ".join(parts) if parts else "—"
55
+
56
+
57
+ def _render_event_row(event: dict[str, Any]) -> str:
58
+ """Render a single redacted drift event as an escaped HTML table row."""
59
+ timestamp = _esc(event.get("timestamp") or event.get("created_at") or "—")
60
+ model_name = _esc(event.get("model_name") or "unknown")
61
+ fingerprint = _esc(event.get("fingerprint") or "—")
62
+ fingerprint_short = (
63
+ f"{fingerprint[:18]}…" if len(fingerprint) > 18 else fingerprint
64
+ )
65
+ drifted = bool(event.get("drifted", event.get("has_drift", False)))
66
+ status_class = "status-drifted" if drifted else "status-ok"
67
+ status_label = "DRIFTED" if drifted else "OK"
68
+ pr_value = event.get("pr_url") or event.get("pr_number") or event.get("pr_opened")
69
+ if pr_value is True:
70
+ pr_cell = '<span class="badge badge-pr">Opened</span>'
71
+ elif isinstance(pr_value, str) and pr_value.startswith(("https://", "http://")):
72
+ safe_url = _esc(pr_value)
73
+ pr_cell = (
74
+ f'<a class="pr-link mono" href="{safe_url}" '
75
+ 'target="_blank" rel="noopener noreferrer">'
76
+ f"{safe_url}</a>"
77
+ )
78
+ elif pr_value:
79
+ pr_cell = f'<span class="mono">{_esc(pr_value)}</span>'
80
+ else:
81
+ pr_cell = "—"
82
+ fields_summary = _format_event_field_summary(event)
83
+
84
+ return (
85
+ "<tr>"
86
+ f'<td class="mono">{timestamp}</td>'
87
+ f'<td class="mono">{model_name}</td>'
88
+ f'<td class="mono" title="{fingerprint}">{fingerprint_short}</td>'
89
+ f'<td><span class="badge {status_class}">{status_label}</span></td>'
90
+ f"<td>{fields_summary}</td>"
91
+ f"<td>{pr_cell}</td>"
92
+ "</tr>"
93
+ )
94
+
95
+
96
+ class ConsoleSnapshot(BaseModel, frozen=True):
97
+ """Per-org integration health console data (EXP-15/T16)."""
98
+
99
+ org_id: str
100
+ plan: str
101
+ bindings: list[dict[str, Any]] = Field(default_factory=list)
102
+ total_events: int = 0
103
+ drifted_events: int = 0
104
+ recent_events: list[dict[str, Any]] = Field(default_factory=list)
105
+ repair_runs: list[dict[str, Any]] = Field(default_factory=list)
106
+ patch_correctness: float | None = None
107
+ regression_rate: float | None = None
108
+ ttr_seconds_mean: float | None = None
109
+ watched_specs: list[dict[str, Any]] = Field(default_factory=list)
110
+ spec_events: list[dict[str, Any]] = Field(default_factory=list)
111
+
112
+
113
+ _STATUS_BADGE_CLASS = {
114
+ "pr_opened": "badge-pr",
115
+ "escalated": "status-drifted",
116
+ "failed_verification": "status-drifted",
117
+ "reverted": "status-ok",
118
+ }
119
+
120
+
121
+ def _fmt_ts(value: object) -> str:
122
+ if isinstance(value, (int, float)):
123
+ return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(value)))
124
+ if isinstance(value, str):
125
+ try:
126
+ return time.strftime(
127
+ "%Y-%m-%d %H:%M:%S", time.gmtime(float(value))
128
+ )
129
+ except ValueError:
130
+ pass
131
+ return _esc(value) if value else "—"
132
+
133
+
134
+ def _render_binding_row(binding: dict[str, Any]) -> str:
135
+ repo = _esc(binding.get("repo") or "—")
136
+ base = _esc(binding.get("base_branch") or "—")
137
+ inst = _esc(binding.get("installation_id") or "—")
138
+ models_map = binding.get("models_map")
139
+ if isinstance(models_map, dict) and models_map:
140
+ models = ", ".join(_esc(k) for k in sorted(models_map))
141
+ elif isinstance(models_map, list) and models_map:
142
+ models = ", ".join(_esc(m) for m in models_map)
143
+ else:
144
+ models = "—"
145
+ return (
146
+ "<tr>"
147
+ f'<td class="mono">{repo}</td>'
148
+ f'<td class="mono">{base}</td>'
149
+ f'<td class="mono">{inst}</td>'
150
+ f"<td>{models}</td>"
151
+ "</tr>"
152
+ )
153
+
154
+
155
+ def _render_spec_row(spec: dict[str, Any]) -> str:
156
+ repo = _esc(spec.get("repo") or "—")
157
+ url = str(spec.get("spec_url") or "")
158
+ safe_url = _esc(url)
159
+ url_cell = (
160
+ f'<a class="pr-link mono" href="{safe_url}" '
161
+ 'target="_blank" rel="noopener noreferrer">spec</a>'
162
+ if url.startswith(("https://", "http://"))
163
+ else '<span class="mono">—</span>'
164
+ )
165
+ version = _esc(spec.get("last_seen_version") or "—")
166
+ updated = _fmt_ts(spec.get("updated_at"))
167
+ return (
168
+ "<tr>"
169
+ f'<td class="mono">{repo}</td>'
170
+ f"<td>{url_cell}</td>"
171
+ f'<td class="mono">{version}</td>'
172
+ f'<td class="mono">{updated}</td>'
173
+ "</tr>"
174
+ )
175
+
176
+
177
+ def _render_spec_event_row(event: dict[str, Any]) -> str:
178
+ ts = _fmt_ts(event.get("detected_at"))
179
+ repo = _esc(event.get("repo") or "—")
180
+ url = _esc(event.get("spec_url") or "—")
181
+ old_v = _esc(event.get("old_version") or "—")
182
+ new_v = _esc(event.get("new_version") or "unversioned")
183
+ return (
184
+ "<tr>"
185
+ f'<td class="mono">{ts}</td>'
186
+ f'<td class="mono">{repo}</td>'
187
+ f'<td class="mono">{url}</td>'
188
+ f'<td class="mono">{old_v} → {new_v}</td>'
189
+ "</tr>"
190
+ )
191
+
192
+
193
+ def _render_repair_run_row(run: dict[str, Any]) -> str:
194
+ ts = _fmt_ts(run.get("created_at"))
195
+ repo = _esc(run.get("repo") or "—")
196
+ model = _esc(run.get("model_name") or "—")
197
+ status = str(run.get("status") or "unknown")
198
+ badge_class = _STATUS_BADGE_CLASS.get(status, "status-drifted")
199
+ status_label = _esc(status.replace("_", " "))
200
+ fingerprint = _esc(str(run.get("fingerprint") or "—")[:18])
201
+ pr_url = run.get("pr_url")
202
+ if isinstance(pr_url, str) and pr_url.startswith(("https://", "http://")):
203
+ safe = _esc(pr_url)
204
+ pr_cell = (
205
+ f'<a class="pr-link mono" href="{safe}" '
206
+ 'target="_blank" rel="noopener noreferrer">PR</a>'
207
+ )
208
+ else:
209
+ pr_cell = "—"
210
+ return (
211
+ "<tr>"
212
+ f'<td class="mono">{ts}</td>'
213
+ f'<td class="mono">{repo}</td>'
214
+ f'<td class="mono">{model}</td>'
215
+ f'<td class="mono" title="{_esc(run.get("fingerprint") or "")}">{fingerprint}</td>'
216
+ f'<td><span class="badge {badge_class}">{status_label}</span></td>'
217
+ f"<td>{pr_cell}</td>"
218
+ "</tr>"
219
+ )
220
+
221
+
222
+ def render_console_html(snapshot: ConsoleSnapshot) -> str:
223
+ """Render the per-org integration health console (EXP-15)."""
224
+ org_id = _esc(snapshot.org_id)
225
+ plan = _esc(snapshot.plan)
226
+ plan_slug = _esc(snapshot.plan.strip().lower().replace(" ", "-"))
227
+ drift_rate = (
228
+ f"{(snapshot.drifted_events / snapshot.total_events) * 100:.1f}%"
229
+ if snapshot.total_events > 0
230
+ else "0.0%"
231
+ )
232
+ escalated = sum(
233
+ 1 for r in snapshot.repair_runs if r.get("status") == "escalated"
234
+ )
235
+ prs_opened = sum(
236
+ 1 for r in snapshot.repair_runs if r.get("status") == "pr_opened"
237
+ )
238
+
239
+ def _pct(value: float | None) -> str:
240
+ return f"{value * 100:.0f}%" if value is not None else "—"
241
+
242
+ def _secs(value: float | None) -> str:
243
+ if value is None:
244
+ return "—"
245
+ return f"{value / 60:.1f}m" if value >= 90 else f"{value:.0f}s"
246
+
247
+ patch_correctness_label = _pct(snapshot.patch_correctness)
248
+ regression_rate_label = _pct(snapshot.regression_rate)
249
+ ttr_label = _secs(snapshot.ttr_seconds_mean)
250
+
251
+ if snapshot.bindings:
252
+ bindings_rows = "\n".join(
253
+ _render_binding_row(b) for b in snapshot.bindings
254
+ )
255
+ else:
256
+ bindings_rows = (
257
+ '<tr><td colspan="4" class="empty-state">'
258
+ "No repositories bound. Connect a repo with "
259
+ '<span class="mono">selfheal connect bind</span>.'
260
+ "</td></tr>"
261
+ )
262
+
263
+ if snapshot.recent_events:
264
+ events_rows = "\n".join(
265
+ _render_event_row(ev) for ev in snapshot.recent_events
266
+ )
267
+ else:
268
+ events_rows = (
269
+ '<tr><td colspan="6" class="empty-state">'
270
+ "No drift events recorded for this organization."
271
+ "</td></tr>"
272
+ )
273
+
274
+ if snapshot.repair_runs:
275
+ runs_rows = "\n".join(
276
+ _render_repair_run_row(r) for r in snapshot.repair_runs
277
+ )
278
+ else:
279
+ runs_rows = (
280
+ '<tr><td colspan="6" class="empty-state">'
281
+ "No auto-heal runs yet. Enable auto-heal in org settings to "
282
+ "generate verified remediation proposals."
283
+ "</td></tr>"
284
+ )
285
+
286
+ if snapshot.watched_specs:
287
+ specs_rows = "\n".join(
288
+ _render_spec_row(s) for s in snapshot.watched_specs
289
+ )
290
+ else:
291
+ specs_rows = (
292
+ '<tr><td colspan="4" class="empty-state">'
293
+ "No upstream specs watched. Register one with "
294
+ '<span class="mono">POST /connect/specs</span>.'
295
+ "</td></tr>"
296
+ )
297
+
298
+ if snapshot.spec_events:
299
+ spec_events_rows = "\n".join(
300
+ _render_spec_event_row(e) for e in snapshot.spec_events
301
+ )
302
+ else:
303
+ spec_events_rows = (
304
+ '<tr><td colspan="4" class="empty-state">'
305
+ "No contract version changes detected yet."
306
+ "</td></tr>"
307
+ )
308
+
309
+ return f"""<!DOCTYPE html>
310
+ <html lang="en">
311
+ <head>
312
+ <meta charset="utf-8" />
313
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
314
+ <title>Datapi SelfHeal Console — {org_id}</title>
315
+ <style>
316
+ :root {{
317
+ --bg: #09090b;
318
+ --surface: #111114;
319
+ --surface-alt: #18181b;
320
+ --border: rgba(255, 255, 255, 0.09);
321
+ --text: #fafafa;
322
+ --muted: #a1a1aa;
323
+ --accent: #6366f1;
324
+ --ok-bg: rgba(16, 185, 129, 0.14);
325
+ --ok-fg: #34d399;
326
+ --warn-bg: rgba(245, 158, 11, 0.16);
327
+ --warn-fg: #fbbf24;
328
+ --pr-bg: rgba(99, 102, 241, 0.16);
329
+ --pr-fg: #818cf8;
330
+ }}
331
+ @media (prefers-color-scheme: light) {{
332
+ :root {{
333
+ --bg: #fafafa;
334
+ --surface: #ffffff;
335
+ --surface-alt: #f4f4f5;
336
+ --border: rgba(9, 9, 11, 0.1);
337
+ --text: #09090b;
338
+ --muted: #71717a;
339
+ --accent: #4f46e5;
340
+ --ok-bg: rgba(16, 185, 129, 0.12);
341
+ --ok-fg: #059669;
342
+ --warn-bg: rgba(245, 158, 11, 0.14);
343
+ --warn-fg: #d97706;
344
+ --pr-bg: rgba(79, 70, 229, 0.12);
345
+ --pr-fg: #4f46e5;
346
+ }}
347
+ }}
348
+ .pr-link {{ color: var(--pr-fg); text-decoration: none; }}
349
+ .pr-link:hover {{ text-decoration: underline; }}
350
+ .card-value, .mono {{ font-variant-numeric: tabular-nums; }}
351
+ * {{ box-sizing: border-box; }}
352
+ body {{
353
+ margin: 0;
354
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
355
+ background: var(--bg);
356
+ color: var(--text);
357
+ line-height: 1.5;
358
+ }}
359
+ .container {{
360
+ max-width: 1120px;
361
+ margin: 0 auto;
362
+ padding: 2rem 1.25rem 3rem;
363
+ }}
364
+ .header {{
365
+ display: flex;
366
+ flex-wrap: wrap;
367
+ justify-content: space-between;
368
+ align-items: center;
369
+ gap: 1rem;
370
+ padding-bottom: 1.5rem;
371
+ border-bottom: 1px solid var(--border);
372
+ }}
373
+ .title {{
374
+ margin: 0;
375
+ font-size: 1.5rem;
376
+ font-weight: 700;
377
+ letter-spacing: -0.01em;
378
+ }}
379
+ .subtitle {{
380
+ margin: 0.25rem 0 0;
381
+ color: var(--muted);
382
+ font-size: 0.9rem;
383
+ }}
384
+ .header-meta {{
385
+ display: flex;
386
+ flex-wrap: wrap;
387
+ align-items: center;
388
+ gap: 0.75rem;
389
+ }}
390
+ .badge {{
391
+ display: inline-block;
392
+ padding: 0.25rem 0.65rem;
393
+ border-radius: 9999px;
394
+ font-size: 0.75rem;
395
+ font-weight: 600;
396
+ letter-spacing: 0.03em;
397
+ text-transform: uppercase;
398
+ }}
399
+ .badge-plan {{
400
+ background: rgba(56, 189, 248, 0.18);
401
+ color: var(--accent);
402
+ border: 1px solid rgba(56, 189, 248, 0.35);
403
+ }}
404
+ .status-drifted {{
405
+ background: var(--warn-bg);
406
+ color: var(--warn-fg);
407
+ }}
408
+ .status-ok {{
409
+ background: var(--ok-bg);
410
+ color: var(--ok-fg);
411
+ }}
412
+ .badge-pr {{
413
+ background: var(--pr-bg);
414
+ color: var(--pr-fg);
415
+ }}
416
+ .quota-bar {{
417
+ display: flex;
418
+ flex-wrap: wrap;
419
+ gap: 1rem;
420
+ margin: 1.25rem 0 1.5rem;
421
+ }}
422
+ .quota-pill {{
423
+ background: var(--surface);
424
+ border: 1px solid var(--border);
425
+ border-radius: 0.5rem;
426
+ padding: 0.6rem 0.9rem;
427
+ font-size: 0.85rem;
428
+ color: var(--muted);
429
+ }}
430
+ .quota-pill strong {{
431
+ color: var(--text);
432
+ margin-left: 0.35rem;
433
+ }}
434
+ .grid {{
435
+ display: grid;
436
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
437
+ gap: 1rem;
438
+ margin-bottom: 2rem;
439
+ }}
440
+ .card {{
441
+ background: var(--surface);
442
+ border: 1px solid var(--border);
443
+ border-radius: 0.75rem;
444
+ padding: 1.1rem 1.25rem;
445
+ }}
446
+ .card-label {{
447
+ font-size: 0.8rem;
448
+ text-transform: uppercase;
449
+ letter-spacing: 0.04em;
450
+ color: var(--muted);
451
+ }}
452
+ .card-value {{
453
+ margin-top: 0.4rem;
454
+ font-size: 1.85rem;
455
+ font-weight: 700;
456
+ color: var(--text);
457
+ }}
458
+ .panel {{
459
+ background: var(--surface);
460
+ border: 1px solid var(--border);
461
+ border-radius: 0.75rem;
462
+ overflow: hidden;
463
+ margin-bottom: 1.5rem;
464
+ }}
465
+ .panel-header {{
466
+ padding: 1rem 1.25rem;
467
+ border-bottom: 1px solid var(--border);
468
+ display: flex;
469
+ justify-content: space-between;
470
+ align-items: center;
471
+ }}
472
+ .panel-title {{
473
+ margin: 0;
474
+ font-size: 1rem;
475
+ font-weight: 600;
476
+ }}
477
+ .table-wrap {{
478
+ overflow-x: auto;
479
+ }}
480
+ table {{
481
+ width: 100%;
482
+ border-collapse: collapse;
483
+ font-size: 0.875rem;
484
+ }}
485
+ th, td {{
486
+ text-align: left;
487
+ padding: 0.75rem 1rem;
488
+ border-bottom: 1px solid var(--border);
489
+ vertical-align: top;
490
+ }}
491
+ th {{
492
+ background: var(--surface-alt);
493
+ color: var(--muted);
494
+ font-size: 0.75rem;
495
+ text-transform: uppercase;
496
+ letter-spacing: 0.04em;
497
+ font-weight: 600;
498
+ }}
499
+ tbody tr:last-child td {{
500
+ border-bottom: none;
501
+ }}
502
+ .mono {{
503
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
504
+ font-size: 0.82rem;
505
+ }}
506
+ .empty-state {{
507
+ text-align: center;
508
+ color: var(--muted);
509
+ padding: 2rem 1rem;
510
+ }}
511
+ .skip-link {{
512
+ position: absolute;
513
+ left: -9999px;
514
+ top: auto;
515
+ width: 1px;
516
+ height: 1px;
517
+ overflow: hidden;
518
+ }}
519
+ .skip-link:focus {{
520
+ position: static;
521
+ width: auto;
522
+ height: auto;
523
+ display: inline-block;
524
+ margin: 0.5rem 1rem;
525
+ padding: 0.4rem 0.75rem;
526
+ background: var(--accent);
527
+ color: #ffffff;
528
+ border-radius: 6px;
529
+ text-decoration: none;
530
+ }}
531
+ :focus-visible {{
532
+ outline: 2px solid var(--accent);
533
+ outline-offset: 2px;
534
+ }}
535
+ .action-link {{
536
+ display: inline-block;
537
+ padding: 0.3rem 0.65rem;
538
+ border: 1px solid var(--border);
539
+ border-radius: 6px;
540
+ color: var(--text);
541
+ text-decoration: none;
542
+ font-size: 0.8rem;
543
+ background: var(--surface);
544
+ }}
545
+ .action-link:hover {{
546
+ border-color: var(--accent);
547
+ }}
548
+ </style>
549
+ </head>
550
+ <body>
551
+ <a class="skip-link" href="#main-content">Skip to main content</a>
552
+ <main id="main-content" class="container">
553
+ <header class="header">
554
+ <div>
555
+ <h1 class="title">Datapi SelfHeal Integration Console</h1>
556
+ <p class="subtitle">
557
+ Monitored dependencies, drift events &amp; verified remediation —
558
+ Org: <span class="mono">{org_id}</span>
559
+ </p>
560
+ </div>
561
+ <div class="header-meta">
562
+ <span class="badge badge-plan plan-{plan_slug}">Plan: {plan}</span>
563
+ </div>
564
+ </header>
565
+
566
+ <section class="quota-bar" aria-label="Integration Health">
567
+ <div class="quota-pill">Drift Rate:<strong>{drift_rate}</strong></div>
568
+ <div class="quota-pill">PRs Opened:<strong>{prs_opened}</strong></div>
569
+ <div class="quota-pill">Escalated:<strong>{escalated}</strong></div>
570
+ <div class="quota-pill">Patch Correctness:<strong>{patch_correctness_label}</strong></div>
571
+ <div class="quota-pill">Regression Rate:<strong>{regression_rate_label}</strong></div>
572
+ <div class="quota-pill">Mean TTR:<strong>{ttr_label}</strong></div>
573
+ </section>
574
+
575
+ <section class="grid" aria-label="Integration Metrics">
576
+ <article class="card">
577
+ <div class="card-label">Monitored Repos</div>
578
+ <div class="card-value">{_esc(len(snapshot.bindings))}</div>
579
+ </article>
580
+ <article class="card">
581
+ <div class="card-label">Drift Events</div>
582
+ <div class="card-value">{_esc(snapshot.drifted_events)}</div>
583
+ </article>
584
+ <article class="card">
585
+ <div class="card-label">Total Events</div>
586
+ <div class="card-value">{_esc(snapshot.total_events)}</div>
587
+ </article>
588
+ <article class="card">
589
+ <div class="card-label">Repair Runs</div>
590
+ <div class="card-value">{_esc(len(snapshot.repair_runs))}</div>
591
+ </article>
592
+ </section>
593
+
594
+ <section class="panel" aria-label="Monitored Dependencies">
595
+ <div class="panel-header">
596
+ <h2 class="panel-title">Monitored Dependencies</h2>
597
+ </div>
598
+ <div class="table-wrap">
599
+ <table>
600
+ <thead>
601
+ <tr>
602
+ <th scope="col">Repository</th>
603
+ <th scope="col">Base Branch</th>
604
+ <th scope="col">Installation</th>
605
+ <th scope="col">Models</th>
606
+ </tr>
607
+ </thead>
608
+ <tbody>
609
+ {bindings_rows}
610
+ </tbody>
611
+ </table>
612
+ </div>
613
+ </section>
614
+
615
+ <section class="panel" aria-label="Recent Drift Events">
616
+ <div class="panel-header">
617
+ <h2 class="panel-title">Recent Drift Events</h2>
618
+ </div>
619
+ <div class="table-wrap">
620
+ <table>
621
+ <thead>
622
+ <tr>
623
+ <th scope="col">Timestamp</th>
624
+ <th scope="col">Model</th>
625
+ <th scope="col">Fingerprint</th>
626
+ <th scope="col">Status</th>
627
+ <th scope="col">Redacted Field Summary</th>
628
+ <th scope="col">PR</th>
629
+ </tr>
630
+ </thead>
631
+ <tbody>
632
+ {events_rows}
633
+ </tbody>
634
+ </table>
635
+ </div>
636
+ </section>
637
+
638
+ <section class="panel" aria-label="Remediation Proposals">
639
+ <div class="panel-header">
640
+ <h2 class="panel-title">Remediation Proposals &amp; PR Status</h2>
641
+ </div>
642
+ <div class="table-wrap">
643
+ <table>
644
+ <thead>
645
+ <tr>
646
+ <th scope="col">Timestamp</th>
647
+ <th scope="col">Repo</th>
648
+ <th scope="col">Model</th>
649
+ <th scope="col">Fingerprint</th>
650
+ <th scope="col">Status</th>
651
+ <th scope="col">PR</th>
652
+ </tr>
653
+ </thead>
654
+ <tbody>
655
+ {runs_rows}
656
+ </tbody>
657
+ </table>
658
+ </div>
659
+ </section>
660
+
661
+ <section class="panel" aria-label="Watched Upstream Specs">
662
+ <div class="panel-header">
663
+ <h2 class="panel-title">Watched Upstream Specs</h2>
664
+ </div>
665
+ <div class="table-wrap">
666
+ <table>
667
+ <thead>
668
+ <tr>
669
+ <th scope="col">Repository</th>
670
+ <th scope="col">Spec</th>
671
+ <th scope="col">Version</th>
672
+ <th scope="col">Updated</th>
673
+ </tr>
674
+ </thead>
675
+ <tbody>
676
+ {specs_rows}
677
+ </tbody>
678
+ </table>
679
+ </div>
680
+ </section>
681
+
682
+ <section class="panel" aria-label="Contract Version Events">
683
+ <div class="panel-header">
684
+ <h2 class="panel-title">Contract Version Events</h2>
685
+ </div>
686
+ <div class="table-wrap">
687
+ <table>
688
+ <thead>
689
+ <tr>
690
+ <th scope="col">Detected</th>
691
+ <th scope="col">Repo</th>
692
+ <th scope="col">Spec</th>
693
+ <th scope="col">Version Change</th>
694
+ </tr>
695
+ </thead>
696
+ <tbody>
697
+ {spec_events_rows}
698
+ </tbody>
699
+ </table>
700
+ </div>
701
+ </section>
702
+ </main>
703
+ </body>
704
+ </html>
705
+ """
706
+
707
+
708
+ def render_dashboard_html(snapshot: DashboardSnapshot) -> str:
709
+ """Render a self-contained, responsive, XSS-safe HTML5 Drift Console page."""
710
+ org_id = _esc(snapshot.org_id)
711
+ org_q = urllib.parse.quote(snapshot.org_id, safe="")
712
+ plan = _esc(snapshot.plan)
713
+ plan_slug = _esc(snapshot.plan.strip().lower().replace(" ", "-"))
714
+ rpm_limit = _esc(snapshot.requests_per_minute_limit)
715
+ llm_limit = _esc(snapshot.llm_calls_limit)
716
+ total_events = _esc(snapshot.total_events)
717
+ drifted_events = _esc(snapshot.drifted_events)
718
+ unique_fingerprints = _esc(snapshot.unique_fingerprints)
719
+ prs_opened = _esc(snapshot.prs_opened)
720
+ drift_rate = (
721
+ f"{(snapshot.drifted_events / snapshot.total_events) * 100:.1f}%"
722
+ if snapshot.total_events > 0
723
+ else "0.0%"
724
+ )
725
+
726
+ if snapshot.recent_events:
727
+ rows_html = "\n".join(_render_event_row(event) for event in snapshot.recent_events)
728
+ else:
729
+ rows_html = (
730
+ '<tr><td colspan="6" class="empty-state">'
731
+ "No recent redacted drift events recorded for this organization."
732
+ "</td></tr>"
733
+ )
734
+
735
+ return f"""<!DOCTYPE html>
736
+ <html lang="en">
737
+ <head>
738
+ <meta charset="utf-8" />
739
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
740
+ <title>Datapi SelfHeal Drift Console — {org_id}</title>
741
+ <style>
742
+ :root {{
743
+ --bg: #09090b;
744
+ --surface: #111114;
745
+ --surface-alt: #18181b;
746
+ --border: rgba(255, 255, 255, 0.09);
747
+ --text: #fafafa;
748
+ --muted: #a1a1aa;
749
+ --accent: #6366f1;
750
+ --ok-bg: rgba(16, 185, 129, 0.14);
751
+ --ok-fg: #34d399;
752
+ --warn-bg: rgba(245, 158, 11, 0.16);
753
+ --warn-fg: #fbbf24;
754
+ --pr-bg: rgba(99, 102, 241, 0.16);
755
+ --pr-fg: #818cf8;
756
+ }}
757
+ @media (prefers-color-scheme: light) {{
758
+ :root {{
759
+ --bg: #fafafa;
760
+ --surface: #ffffff;
761
+ --surface-alt: #f4f4f5;
762
+ --border: rgba(9, 9, 11, 0.1);
763
+ --text: #09090b;
764
+ --muted: #71717a;
765
+ --accent: #4f46e5;
766
+ --ok-bg: rgba(16, 185, 129, 0.12);
767
+ --ok-fg: #059669;
768
+ --warn-bg: rgba(245, 158, 11, 0.14);
769
+ --warn-fg: #d97706;
770
+ --pr-bg: rgba(79, 70, 229, 0.12);
771
+ --pr-fg: #4f46e5;
772
+ }}
773
+ }}
774
+ .icon {{
775
+ width: 15px;
776
+ height: 15px;
777
+ vertical-align: -2px;
778
+ stroke: currentColor;
779
+ fill: none;
780
+ stroke-width: 1.75;
781
+ stroke-linecap: round;
782
+ stroke-linejoin: round;
783
+ }}
784
+ .pr-link {{ color: var(--pr-fg); text-decoration: none; }}
785
+ .pr-link:hover {{ text-decoration: underline; }}
786
+ .card-value, .mono {{ font-variant-numeric: tabular-nums; }}
787
+ * {{ box-sizing: border-box; }}
788
+ body {{
789
+ margin: 0;
790
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
791
+ background: var(--bg);
792
+ color: var(--text);
793
+ line-height: 1.5;
794
+ }}
795
+ .container {{
796
+ max-width: 1120px;
797
+ margin: 0 auto;
798
+ padding: 2rem 1.25rem 3rem;
799
+ }}
800
+ .header {{
801
+ display: flex;
802
+ flex-wrap: wrap;
803
+ justify-content: space-between;
804
+ align-items: center;
805
+ gap: 1rem;
806
+ padding-bottom: 1.5rem;
807
+ border-bottom: 1px solid var(--border);
808
+ }}
809
+ .title {{
810
+ margin: 0;
811
+ font-size: 1.5rem;
812
+ font-weight: 700;
813
+ letter-spacing: -0.01em;
814
+ }}
815
+ .subtitle {{
816
+ margin: 0.25rem 0 0;
817
+ color: var(--muted);
818
+ font-size: 0.9rem;
819
+ }}
820
+ .header-meta {{
821
+ display: flex;
822
+ flex-wrap: wrap;
823
+ align-items: center;
824
+ gap: 0.75rem;
825
+ }}
826
+ .badge {{
827
+ display: inline-block;
828
+ padding: 0.25rem 0.65rem;
829
+ border-radius: 9999px;
830
+ font-size: 0.75rem;
831
+ font-weight: 600;
832
+ letter-spacing: 0.03em;
833
+ text-transform: uppercase;
834
+ }}
835
+ .badge-plan {{
836
+ background: rgba(56, 189, 248, 0.18);
837
+ color: var(--accent);
838
+ border: 1px solid rgba(56, 189, 248, 0.35);
839
+ }}
840
+ .status-drifted {{
841
+ background: var(--warn-bg);
842
+ color: var(--warn-fg);
843
+ }}
844
+ .status-ok {{
845
+ background: var(--ok-bg);
846
+ color: var(--ok-fg);
847
+ }}
848
+ .badge-pr {{
849
+ background: var(--pr-bg);
850
+ color: var(--pr-fg);
851
+ }}
852
+ .quota-bar {{
853
+ display: flex;
854
+ flex-wrap: wrap;
855
+ gap: 1rem;
856
+ margin: 1.25rem 0 1.5rem;
857
+ }}
858
+ .quota-pill {{
859
+ background: var(--surface);
860
+ border: 1px solid var(--border);
861
+ border-radius: 0.5rem;
862
+ padding: 0.6rem 0.9rem;
863
+ font-size: 0.85rem;
864
+ color: var(--muted);
865
+ }}
866
+ .quota-pill strong {{
867
+ color: var(--text);
868
+ margin-left: 0.35rem;
869
+ }}
870
+ .grid {{
871
+ display: grid;
872
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
873
+ gap: 1rem;
874
+ margin-bottom: 2rem;
875
+ }}
876
+ .card {{
877
+ background: var(--surface);
878
+ border: 1px solid var(--border);
879
+ border-radius: 0.75rem;
880
+ padding: 1.1rem 1.25rem;
881
+ }}
882
+ .card-label {{
883
+ font-size: 0.8rem;
884
+ text-transform: uppercase;
885
+ letter-spacing: 0.04em;
886
+ color: var(--muted);
887
+ }}
888
+ .card-value {{
889
+ margin-top: 0.4rem;
890
+ font-size: 1.85rem;
891
+ font-weight: 700;
892
+ color: var(--text);
893
+ }}
894
+ .panel {{
895
+ background: var(--surface);
896
+ border: 1px solid var(--border);
897
+ border-radius: 0.75rem;
898
+ overflow: hidden;
899
+ }}
900
+ .panel-header {{
901
+ padding: 1rem 1.25rem;
902
+ border-bottom: 1px solid var(--border);
903
+ display: flex;
904
+ justify-content: space-between;
905
+ align-items: center;
906
+ }}
907
+ .panel-title {{
908
+ margin: 0;
909
+ font-size: 1rem;
910
+ font-weight: 600;
911
+ }}
912
+ .table-wrap {{
913
+ overflow-x: auto;
914
+ }}
915
+ table {{
916
+ width: 100%;
917
+ border-collapse: collapse;
918
+ font-size: 0.875rem;
919
+ }}
920
+ th, td {{
921
+ text-align: left;
922
+ padding: 0.75rem 1rem;
923
+ border-bottom: 1px solid var(--border);
924
+ vertical-align: top;
925
+ }}
926
+ th {{
927
+ background: var(--surface-alt);
928
+ color: var(--muted);
929
+ font-size: 0.75rem;
930
+ text-transform: uppercase;
931
+ letter-spacing: 0.04em;
932
+ font-weight: 600;
933
+ }}
934
+ tbody tr:last-child td {{
935
+ border-bottom: none;
936
+ }}
937
+ .mono {{
938
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
939
+ font-size: 0.82rem;
940
+ }}
941
+ .empty-state {{
942
+ text-align: center;
943
+ color: var(--muted);
944
+ padding: 2rem 1rem;
945
+ }}
946
+ .skip-link {{
947
+ position: absolute;
948
+ left: -9999px;
949
+ top: auto;
950
+ width: 1px;
951
+ height: 1px;
952
+ overflow: hidden;
953
+ }}
954
+ .skip-link:focus {{
955
+ position: static;
956
+ width: auto;
957
+ height: auto;
958
+ display: inline-block;
959
+ margin: 0.5rem 1rem;
960
+ padding: 0.4rem 0.75rem;
961
+ background: var(--accent);
962
+ color: #ffffff;
963
+ border-radius: 6px;
964
+ text-decoration: none;
965
+ }}
966
+ :focus-visible {{
967
+ outline: 2px solid var(--accent);
968
+ outline-offset: 2px;
969
+ }}
970
+ .action-link {{
971
+ display: inline-block;
972
+ padding: 0.3rem 0.65rem;
973
+ border: 1px solid var(--border);
974
+ border-radius: 6px;
975
+ color: var(--text);
976
+ text-decoration: none;
977
+ font-size: 0.8rem;
978
+ background: var(--surface);
979
+ }}
980
+ .action-link:hover {{
981
+ border-color: var(--accent);
982
+ }}
983
+ .filter-bar {{
984
+ display: flex;
985
+ gap: 0.4rem;
986
+ flex-wrap: wrap;
987
+ }}
988
+ .filter-link {{
989
+ padding: 0.2rem 0.55rem;
990
+ border-radius: 999px;
991
+ border: 1px solid var(--border);
992
+ color: var(--muted);
993
+ text-decoration: none;
994
+ font-size: 0.75rem;
995
+ }}
996
+ .filter-link[aria-current="page"] {{
997
+ border-color: var(--accent);
998
+ color: var(--text);
999
+ background: var(--pr-bg);
1000
+ }}
1001
+ </style>
1002
+ </head>
1003
+ <body>
1004
+ <a class="skip-link" href="#main-content">Skip to main content</a>
1005
+ <main id="main-content" class="container">
1006
+ <header class="header">
1007
+ <div>
1008
+ <h1 class="title">Datapi SelfHeal Drift Console</h1>
1009
+ <p class="subtitle">
1010
+ Zero-PII Schema Drift Telemetry &amp; Verified Remediation —
1011
+ Org: <span class="mono">{org_id}</span>
1012
+ </p>
1013
+ </div>
1014
+ <div class="header-meta">
1015
+ <a
1016
+ class="action-link"
1017
+ href="/api/v1/events/export?org_id={org_q}&amp;format=csv"
1018
+ >Export CSV</a>
1019
+ <a
1020
+ class="action-link"
1021
+ href="/api/v1/events/export?org_id={org_q}&amp;format=jsonl"
1022
+ >Export JSONL</a>
1023
+ <span class="badge badge-plan plan-{plan_slug}">Plan: {plan}</span>
1024
+ </div>
1025
+ </header>
1026
+
1027
+ <section class="quota-bar" aria-label="Plan Quotas">
1028
+ <div class="quota-pill">Rate Limit:<strong>{rpm_limit} req/min</strong></div>
1029
+ <div class="quota-pill">LLM Synthesis Quota:<strong>{llm_limit} calls</strong></div>
1030
+ <div class="quota-pill">Drift Rate:<strong>{drift_rate}</strong></div>
1031
+ </section>
1032
+
1033
+ <section class="grid" aria-label="Drift Metrics">
1034
+ <article class="card">
1035
+ <div class="card-label">Total Events</div>
1036
+ <div class="card-value">{total_events}</div>
1037
+ </article>
1038
+ <article class="card">
1039
+ <div class="card-label">Drifted Events</div>
1040
+ <div class="card-value">{drifted_events}</div>
1041
+ </article>
1042
+ <article class="card">
1043
+ <div class="card-label">Unique Fingerprints</div>
1044
+ <div class="card-value">{unique_fingerprints}</div>
1045
+ </article>
1046
+ <article class="card">
1047
+ <div class="card-label">PRs Opened</div>
1048
+ <div class="card-value">{prs_opened}</div>
1049
+ </article>
1050
+ </section>
1051
+
1052
+ <section class="panel" aria-label="Recent Redacted Drift Events">
1053
+ <div class="panel-header">
1054
+ <h2 class="panel-title">Recent Redacted Drift Events</h2>
1055
+ <nav class="filter-bar" aria-label="Filter events by status">
1056
+ <a
1057
+ class="filter-link"
1058
+ href="/dashboard?org_id={org_q}&amp;status=all"
1059
+ {"aria-current=\"page\"" if snapshot.status_filter == "all" else ""}
1060
+ >All</a>
1061
+ <a
1062
+ class="filter-link"
1063
+ href="/dashboard?org_id={org_q}&amp;status=drifted"
1064
+ {"aria-current=\"page\"" if snapshot.status_filter == "drifted" else ""}
1065
+ >Drifted</a>
1066
+ <a
1067
+ class="filter-link"
1068
+ href="/dashboard?org_id={org_q}&amp;status=ok"
1069
+ {"aria-current=\"page\"" if snapshot.status_filter == "ok" else ""}
1070
+ >OK</a>
1071
+ </nav>
1072
+ </div>
1073
+ <div class="table-wrap">
1074
+ <table>
1075
+ <thead>
1076
+ <tr>
1077
+ <th scope="col">Timestamp</th>
1078
+ <th scope="col">Model</th>
1079
+ <th scope="col">Fingerprint</th>
1080
+ <th scope="col">Status</th>
1081
+ <th scope="col">Redacted Field Summary</th>
1082
+ <th scope="col">PR</th>
1083
+ </tr>
1084
+ </thead>
1085
+ <tbody>
1086
+ {rows_html}
1087
+ </tbody>
1088
+ </table>
1089
+ </div>
1090
+ </section>
1091
+ </main>
1092
+ </body>
1093
+ </html>
1094
+ """