adre-cli 0.1.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.
Files changed (48) hide show
  1. adre/__init__.py +5 -0
  2. adre/analyzers/__init__.py +1 -0
  3. adre/analyzers/architecture.py +253 -0
  4. adre/analyzers/findings.py +457 -0
  5. adre/analyzers/inference.py +163 -0
  6. adre/cli.py +923 -0
  7. adre/core/__init__.py +1 -0
  8. adre/core/accepted.py +225 -0
  9. adre/core/adaptive.py +221 -0
  10. adre/core/baseline.py +1165 -0
  11. adre/core/config.py +60 -0
  12. adre/core/decision_engine.py +361 -0
  13. adre/core/declared.py +313 -0
  14. adre/core/evolution_intelligence.py +390 -0
  15. adre/core/explainer.py +413 -0
  16. adre/core/git_intelligence.py +392 -0
  17. adre/core/github_check.py +212 -0
  18. adre/core/incremental.py +288 -0
  19. adre/core/layers.py +306 -0
  20. adre/core/pr_intelligence.py +261 -0
  21. adre/core/pr_review.py +454 -0
  22. adre/core/prioritization.py +196 -0
  23. adre/core/project.py +41 -0
  24. adre/core/refactor_intelligence.py +201 -0
  25. adre/core/repositories.py +312 -0
  26. adre/core/review.py +96 -0
  27. adre/core/rules_shared.py +75 -0
  28. adre/core/sarif.py +141 -0
  29. adre/core/scope.py +141 -0
  30. adre/core/snapshots.py +242 -0
  31. adre/core/stability_intelligence.py +361 -0
  32. adre/graph/__init__.py +0 -0
  33. adre/graph/dependencies.py +379 -0
  34. adre/parsers/__init__.py +87 -0
  35. adre/parsers/go.py +140 -0
  36. adre/parsers/javascript.py +364 -0
  37. adre/parsers/jvm.py +127 -0
  38. adre/parsers/python.py +153 -0
  39. adre/reports/__init__.py +1 -0
  40. adre/reports/architecture.py +349 -0
  41. adre/rules.py +12 -0
  42. adre/web.py +3731 -0
  43. adre_cli-0.1.0.dist-info/METADATA +343 -0
  44. adre_cli-0.1.0.dist-info/RECORD +48 -0
  45. adre_cli-0.1.0.dist-info/WHEEL +5 -0
  46. adre_cli-0.1.0.dist-info/entry_points.txt +2 -0
  47. adre_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
  48. adre_cli-0.1.0.dist-info/top_level.txt +1 -0
adre/web.py ADDED
@@ -0,0 +1,3731 @@
1
+ import hmac
2
+ import json
3
+ import os
4
+ import platform
5
+ import secrets
6
+ import shutil
7
+ import subprocess
8
+ from datetime import datetime, timezone
9
+ from html import escape
10
+ from urllib.parse import parse_qs, quote, unquote, urlsplit
11
+
12
+ from fastapi import FastAPI, Request
13
+ from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse
14
+
15
+ from adre.analyzers.architecture import (
16
+ analyze_project_architecture,
17
+ count_severities,
18
+ )
19
+ from adre.core.baseline import (
20
+ load_architecture_baseline,
21
+ resolve_baseline_path,
22
+ save_architecture_baseline,
23
+ )
24
+ from adre.core.git_intelligence import run_git
25
+ from adre.core.pr_review import review_pull_request
26
+ from adre.core.review import review_working_tree
27
+ from adre.core.decision_engine import generate_architecture_decisions
28
+ from adre.core.evolution_intelligence import analyze_architecture_evolution
29
+ from adre.core.explainer import attach_explanation_context_to_decisions, generate_architecture_explanation
30
+ from adre.core.git_intelligence import extract_git_snapshots
31
+ from adre.core.project import analyze_project_drift, scan_project_structure
32
+ from adre.core.repositories import (
33
+ allowed_source_roots,
34
+ ensure_repository_context,
35
+ get_pinned_repositories,
36
+ get_recent_repositories,
37
+ list_browsable_directories,
38
+ normalize_local_path,
39
+ register_github_repository,
40
+ register_local_repository,
41
+ repository_display_context,
42
+ toggle_repository_pin,
43
+ )
44
+ from adre.core.stability_intelligence import analyze_architecture_stability
45
+ from adre.core.snapshots import (
46
+ build_architecture_history,
47
+ compare_snapshot_data,
48
+ load_snapshot_file,
49
+ save_architecture_snapshot,
50
+ )
51
+ from adre.graph.dependencies import build_dependency_graph
52
+ from adre.reports.architecture import build_architecture_report
53
+
54
+ app = FastAPI()
55
+
56
+ # --- Local-only security -----------------------------------------------------
57
+ #
58
+ # The web UI runs on the user's machine and can save files, clone
59
+ # repositories and launch the editor. Three layers keep other websites from
60
+ # driving it through the user's browser:
61
+ # 1. Host check: only localhost names are served, which defeats DNS
62
+ # rebinding (a malicious domain re-pointed at 127.0.0.1).
63
+ # 2. Fetch metadata: requests a browser marks as cross-site are refused.
64
+ # 3. Every state-changing action is a POST that must carry a per-process
65
+ # token embedded only in this app's own pages.
66
+
67
+ SESSION_TOKEN = secrets.token_urlsafe(32)
68
+ LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
69
+ MAX_FORM_BYTES = 64 * 1024
70
+
71
+
72
+ def allowed_hosts():
73
+ hosts = set(LOCAL_HOSTS)
74
+ for item in os.environ.get("ADRE_WEB_ALLOWED_HOSTS", "").split(","):
75
+ item = item.strip().lower()
76
+ if item:
77
+ hosts.add(item)
78
+ return hosts
79
+
80
+
81
+ def _hostname(value):
82
+ value = (value or "").strip().lower()
83
+ if not value:
84
+ return ""
85
+ if value.startswith("["): # [::1]:8000
86
+ return value[1:].split("]", 1)[0]
87
+ if value.count(":") == 1:
88
+ return value.split(":", 1)[0]
89
+ return value
90
+
91
+
92
+ def request_is_allowed(method, headers):
93
+ """Return None if the request may proceed, otherwise a reason string."""
94
+ if _hostname(headers.get("host")) not in allowed_hosts():
95
+ return "Unexpected Host header. The ADRE web UI only answers on localhost."
96
+ site = (headers.get("sec-fetch-site") or "").lower()
97
+ if site and site not in {"same-origin", "none"}:
98
+ return "Cross-site requests to the ADRE web UI are not allowed."
99
+ if method not in {"GET", "HEAD", "OPTIONS"}:
100
+ origin = headers.get("origin")
101
+ if origin and origin != "null" and _hostname(urlsplit(origin).netloc) not in allowed_hosts():
102
+ return "Cross-origin form submissions are not allowed."
103
+ return None
104
+
105
+
106
+ @app.middleware("http")
107
+ async def local_only_guard(request: Request, call_next):
108
+ reason = request_is_allowed(request.method, request.headers)
109
+ if reason:
110
+ return PlainTextResponse(reason, status_code=403)
111
+ return await call_next(request)
112
+
113
+
114
+ async def read_form(request: Request):
115
+ """Parse a urlencoded POST body and verify the session token.
116
+
117
+ Returns (fields, error_response). Parsed without python-multipart so the
118
+ web extra needs no further dependencies.
119
+ """
120
+ body = await request.body()
121
+ if len(body) > MAX_FORM_BYTES:
122
+ return None, PlainTextResponse("Form too large.", status_code=413)
123
+ parsed = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)
124
+ fields = {key: values[-1] for key, values in parsed.items()}
125
+ token = fields.get("csrf_token") or request.headers.get("x-adre-token") or ""
126
+ if not hmac.compare_digest(token, SESSION_TOKEN):
127
+ return None, PlainTextResponse(
128
+ "Missing or invalid form token. Reload the page and try again.", status_code=403
129
+ )
130
+ return fields, None
131
+
132
+
133
+ def csrf_input():
134
+ return '<input type="hidden" name="csrf_token" value="{0}">'.format(escape(SESSION_TOKEN, quote=True))
135
+
136
+
137
+ def post_button(action, fields, label, button_class, form_class="contents", confirm=None):
138
+ """A button that submits a token-protected POST form (replaces GET links)."""
139
+ hidden = "".join(
140
+ '<input type="hidden" name="{0}" value="{1}">'.format(escape(str(name), quote=True), escape(str(value), quote=True))
141
+ for name, value in fields.items()
142
+ if value is not None
143
+ )
144
+ onsubmit = ' onsubmit="return confirm({0})"'.format(escape(json.dumps(confirm), quote=True)) if confirm else ""
145
+ return (
146
+ '<form method="post" action="{action}" class="{form_class}"{onsubmit}>{csrf}{hidden}'
147
+ '<button type="submit" class="{button_class}">{label}</button></form>'
148
+ ).format(
149
+ action=escape(action, quote=True),
150
+ form_class=escape(form_class, quote=True),
151
+ onsubmit=onsubmit,
152
+ csrf=csrf_input(),
153
+ hidden=hidden,
154
+ button_class=escape(button_class, quote=True),
155
+ label=label,
156
+ )
157
+
158
+
159
+
160
+ SOURCE_ROOT = os.path.realpath(os.getcwd())
161
+ DEFAULT_EXAMPLE_PATH = os.path.join(SOURCE_ROOT, "examples", "test_project")
162
+ VSCODE_INSTALL_URL = "https://code.visualstudio.com/docs/setup/mac"
163
+
164
+
165
+ def resolve_repository_path(path):
166
+ if not path:
167
+ raise ValueError("Repository path is required.")
168
+ return normalize_local_path(path)
169
+
170
+
171
+ def default_repository_path():
172
+ recent = get_recent_repositories(limit=1)
173
+ if recent:
174
+ return recent[0]["path"]
175
+ if os.path.isdir(DEFAULT_EXAMPLE_PATH):
176
+ return DEFAULT_EXAMPLE_PATH
177
+ return SOURCE_ROOT
178
+
179
+
180
+ def parse_select_query(select):
181
+ if not select:
182
+ return None
183
+ parts = [part.strip() for part in select.replace(";", ",").split(",") if part.strip()]
184
+ return parts or None
185
+
186
+
187
+ def vscode_cli_candidates():
188
+ candidates = ["code"]
189
+ if platform.system() == "Darwin":
190
+ candidates.extend([
191
+ "/usr/local/bin/code",
192
+ "/opt/homebrew/bin/code",
193
+ os.path.expanduser("~/bin/code"),
194
+ "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code",
195
+ ])
196
+ elif platform.system() == "Windows":
197
+ candidates.extend([
198
+ os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs", "Microsoft VS Code", "bin", "code.cmd"),
199
+ ])
200
+ return candidates
201
+
202
+
203
+ def vscode_cli_path():
204
+ for candidate in vscode_cli_candidates():
205
+ if os.path.isabs(candidate):
206
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
207
+ return candidate
208
+ continue
209
+ found = shutil.which(candidate)
210
+ if found:
211
+ return found
212
+ return None
213
+
214
+
215
+ def open_in_vscode(file_path, line=1):
216
+ target = f"{file_path}:{max(1, int(line or 1))}"
217
+ cli = vscode_cli_path()
218
+ if cli:
219
+ subprocess.run([cli, "-g", target], check=True, capture_output=True, text=True)
220
+ return "cli"
221
+
222
+ if platform.system() == "Darwin":
223
+ subprocess.run(
224
+ ["open", "-a", "Visual Studio Code", "--args", "-g", target],
225
+ check=True,
226
+ capture_output=True,
227
+ text=True,
228
+ )
229
+ return "app"
230
+
231
+ raise FileNotFoundError("VS Code CLI unavailable")
232
+
233
+
234
+ def reveal_in_file_manager(file_path):
235
+ absolute_path = os.path.realpath(file_path)
236
+ system = platform.system()
237
+ if system == "Darwin":
238
+ subprocess.run(["open", "-R", absolute_path], check=True, capture_output=True, text=True)
239
+ return "finder"
240
+ if system == "Windows":
241
+ subprocess.run(["explorer", "/select,", absolute_path], check=True, capture_output=True, text=True)
242
+ return "explorer"
243
+ parent = os.path.dirname(absolute_path)
244
+ opener = shutil.which("xdg-open")
245
+ if opener:
246
+ subprocess.run([opener, parent], check=True, capture_output=True, text=True)
247
+ return "file-manager"
248
+ raise FileNotFoundError("No supported file manager command found.")
249
+
250
+
251
+ def safe_source_path(file_path):
252
+ if not file_path:
253
+ return None
254
+ if os.path.isabs(file_path):
255
+ candidate = file_path
256
+ else:
257
+ candidate = os.path.join(SOURCE_ROOT, file_path)
258
+ absolute_path = os.path.realpath(candidate)
259
+ source_roots = allowed_source_roots()
260
+ if not any(absolute_path == root or absolute_path.startswith(root + os.sep) for root in source_roots):
261
+ return None
262
+ if not os.path.isfile(absolute_path):
263
+ return None
264
+ return absolute_path
265
+
266
+
267
+ def open_result_page(title, message, file_path=None, line=None, vscode_available=False, show_vscode_help=False):
268
+ safe_line = max(1, int(line or 1))
269
+ actions_html = ""
270
+ install_help = ""
271
+ if file_path:
272
+ encoded_file = quote(file_path)
273
+ finder_label = "Open in Finder" if platform.system() == "Darwin" else "Reveal in File Manager"
274
+ retry_vscode_html = ""
275
+ if not vscode_available:
276
+ retry_vscode_html = post_button(
277
+ "/open",
278
+ {"path": file_path, "line": safe_line},
279
+ "Retry VS Code",
280
+ "glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200",
281
+ )
282
+ actions_html = f"""
283
+ <div class="mt-5 flex flex-wrap gap-2">
284
+ <button
285
+ type="button"
286
+ class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200"
287
+ data-copy-path-button
288
+ data-copy-path="{escape(file_path, quote=True)}"
289
+ >
290
+ Copy Path
291
+ </button>
292
+ {post_button("/open-folder", {"path": file_path}, escape(finder_label), "glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200")}
293
+ {retry_vscode_html}
294
+ </div>
295
+ <div class="mt-4 glass rounded-xl px-4 py-3">
296
+ <div class="text-xs uppercase tracking-wide text-slate-500">Source path</div>
297
+ <div class="mt-2 break-all font-mono text-sm text-slate-200">{escape(file_path)}</div>
298
+ <div class="mt-2 text-xs text-slate-500">Line {escape(str(safe_line))}</div>
299
+ </div>
300
+ """
301
+ if show_vscode_help:
302
+ install_help = f"""
303
+ <div class="mt-4 glass rounded-xl px-4 py-3 text-sm leading-6 text-slate-400">
304
+ Install the VS Code shell command from the Command Palette:
305
+ <span class="font-mono text-slate-200">Shell Command: Install 'code' command in PATH</span>.
306
+ <a href="{escape(VSCODE_INSTALL_URL)}" class="ml-1 text-slate-200 underline">VS Code setup guide</a>
307
+ </div>
308
+ """
309
+
310
+ return f"""
311
+ <!doctype html>
312
+ <html lang="en">
313
+ <head>
314
+ <meta charset="utf-8">
315
+ <meta name="viewport" content="width=device-width, initial-scale=1">
316
+ <title>{escape(title)}</title>
317
+ <script src="https://cdn.tailwindcss.com"></script>
318
+ {liquid_glass_styles()}
319
+ </head>
320
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
321
+ {product_nav(quote(default_repository_path()))}
322
+ <main class="mx-auto max-w-3xl px-6 py-10">
323
+ <section class="glass glass-card p-6">
324
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Source navigation</p>
325
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">{escape(title)}</h1>
326
+ <p class="mt-4 text-sm leading-6 text-slate-400">{escape(message)}</p>
327
+ {install_help}
328
+ {actions_html}
329
+ <button type="button" onclick="history.back()" class="glass-btn mt-5 rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
330
+ Back
331
+ </button>
332
+ </section>
333
+ </main>
334
+ <script>
335
+ document.querySelectorAll('[data-copy-path-button]').forEach((button) => {{
336
+ button.addEventListener('click', async () => {{
337
+ const copyPath = button.dataset.copyPath;
338
+ const originalLabel = button.textContent;
339
+ try {{
340
+ await navigator.clipboard.writeText(copyPath);
341
+ button.textContent = 'Path Copied';
342
+ }} catch (error) {{
343
+ button.textContent = 'Copy Failed';
344
+ }}
345
+ window.setTimeout(() => {{ button.textContent = originalLabel; }}, 1400);
346
+ }});
347
+ }});
348
+ </script>
349
+ </body>
350
+ </html>
351
+ """
352
+
353
+
354
+ def liquid_glass_styles():
355
+ return """
356
+ <style>
357
+ :root {
358
+ --bg: #16181c;
359
+ --panel: rgba(255,255,255,0.05);
360
+ --panel-hover: rgba(255,255,255,0.08);
361
+ --border: rgba(255,255,255,0.10);
362
+ --text: #e5e7eb;
363
+ --app-bg: var(--bg);
364
+ --glass-border: rgba(255,255,255,0.12);
365
+ --glass-border-strong: rgba(255,255,255,0.18);
366
+ --glass-top: rgba(255,255,255,0.08);
367
+ --glass-bottom: rgba(255,255,255,0.03);
368
+ }
369
+ body {
370
+ background: var(--bg);
371
+ color: var(--text);
372
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
373
+ }
374
+ .app-bg {
375
+ background:
376
+ radial-gradient(circle at 20% 0%, rgba(255,255,255,0.055), transparent 32%),
377
+ radial-gradient(circle at 90% 10%, rgba(255,255,255,0.035), transparent 28%),
378
+ radial-gradient(rgba(255,255,255,0.04) 1px, transparent 1px),
379
+ var(--app-bg);
380
+ background-size: auto, auto, 22px 22px, auto;
381
+ }
382
+ .glass {
383
+ position: relative;
384
+ border: 1px solid rgba(255,255,255,0.10);
385
+ background: linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.03));
386
+ box-shadow:
387
+ 0 8px 24px rgba(0,0,0,0.35),
388
+ inset 0 1px 0 rgba(255,255,255,0.06);
389
+ backdrop-filter: blur(18px) saturate(140%);
390
+ -webkit-backdrop-filter: blur(18px) saturate(140%);
391
+ }
392
+ .glass-card {
393
+ width: 100%;
394
+ border-radius: 16px;
395
+ overflow: hidden;
396
+ color: #e5e7eb;
397
+ transition: border-color 180ms ease, background 180ms ease, box-shadow 180ms ease;
398
+ }
399
+ .glass-card:hover {
400
+ border-color: rgba(255,255,255,0.14);
401
+ background: linear-gradient(180deg, rgba(255,255,255,0.07), rgba(255,255,255,0.035));
402
+ box-shadow:
403
+ 0 10px 26px rgba(0,0,0,0.36),
404
+ inset 0 1px 0 rgba(255,255,255,0.07);
405
+ }
406
+ .glass-btn {
407
+ display: inline-flex;
408
+ align-items: center;
409
+ justify-content: center;
410
+ border: 1px solid rgba(255,255,255,0.11);
411
+ background: linear-gradient(180deg, rgba(255,255,255,0.08), rgba(255,255,255,0.035));
412
+ box-shadow:
413
+ inset 0 1px 0 rgba(255,255,255,0.06),
414
+ 0 6px 18px rgba(0,0,0,0.20);
415
+ backdrop-filter: blur(16px) saturate(135%);
416
+ -webkit-backdrop-filter: blur(16px) saturate(135%);
417
+ transition: transform 170ms ease, border-color 170ms ease, background 170ms ease;
418
+ cursor: pointer;
419
+ white-space: nowrap;
420
+ }
421
+ .glass-btn:hover {
422
+ transform: translateY(-1px) scale(1.02);
423
+ border-color: rgba(255,255,255,0.20);
424
+ background: linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0.045));
425
+ }
426
+ .glass-btn:active {
427
+ transform: scale(0.98);
428
+ }
429
+ .glass-nav {
430
+ border-bottom: 1px solid rgba(255,255,255,0.09);
431
+ background: linear-gradient(180deg, rgba(255,255,255,0.055), rgba(255,255,255,0.02));
432
+ backdrop-filter: blur(26px) saturate(170%);
433
+ -webkit-backdrop-filter: blur(26px) saturate(170%);
434
+ box-shadow: inset 0 1px 0 rgba(255,255,255,0.07), 0 14px 40px rgba(0,0,0,0.24);
435
+ }
436
+ .issue-card {
437
+ border-left: 1px solid rgba(255,255,255,0.16);
438
+ }
439
+ .severity-badge {
440
+ display: inline-flex;
441
+ align-items: center;
442
+ border-radius: 999px;
443
+ border: 1px solid rgba(255,255,255,0.12);
444
+ padding: 4px 10px;
445
+ font-size: 0.72rem;
446
+ font-weight: 700;
447
+ text-transform: uppercase;
448
+ letter-spacing: 0.04em;
449
+ }
450
+ .severity-critical {
451
+ color: #fecaca;
452
+ background: rgba(127,29,29,0.24);
453
+ border-color: rgba(248,113,113,0.24);
454
+ }
455
+ .severity-high {
456
+ color: #fed7aa;
457
+ background: rgba(124,45,18,0.22);
458
+ border-color: rgba(251,146,60,0.24);
459
+ }
460
+ .severity-medium {
461
+ color: #fde68a;
462
+ background: rgba(113,63,18,0.20);
463
+ border-color: rgba(245,158,11,0.22);
464
+ }
465
+ .severity-low {
466
+ color: #cbd5e1;
467
+ background: rgba(51,65,85,0.28);
468
+ border-color: rgba(148,163,184,0.20);
469
+ }
470
+ .source-btn {
471
+ border-color: rgba(148,163,184,0.26);
472
+ background: linear-gradient(180deg, rgba(226,232,240,0.18), rgba(148,163,184,0.08));
473
+ color: #f8fafc;
474
+ }
475
+ .code-preview {
476
+ display: grid;
477
+ grid-template-rows: 0fr;
478
+ opacity: 0;
479
+ transition: grid-template-rows 180ms ease, opacity 180ms ease, margin-top 180ms ease;
480
+ margin-top: 0;
481
+ }
482
+ .code-preview.is-open {
483
+ grid-template-rows: 1fr;
484
+ opacity: 1;
485
+ margin-top: 16px;
486
+ }
487
+ .code-preview-inner {
488
+ min-height: 0;
489
+ overflow: hidden;
490
+ }
491
+ .code-block {
492
+ border-radius: 14px;
493
+ border: 1px solid rgba(255,255,255,0.09);
494
+ background: rgba(10,12,15,0.58);
495
+ color: #d1d5db;
496
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
497
+ font-size: 12px;
498
+ line-height: 1.65;
499
+ overflow-x: auto;
500
+ }
501
+ .code-line {
502
+ display: grid;
503
+ grid-template-columns: 4.25rem minmax(0, 1fr);
504
+ gap: 1rem;
505
+ padding: 0 14px;
506
+ white-space: pre;
507
+ }
508
+ .code-line-number {
509
+ color: rgba(148,163,184,0.68);
510
+ text-align: right;
511
+ user-select: none;
512
+ }
513
+ .code-line.is-highlighted {
514
+ background: rgba(245,158,11,0.13);
515
+ box-shadow: inset 2px 0 0 rgba(245,158,11,0.48);
516
+ }
517
+ .code-empty {
518
+ border-radius: 14px;
519
+ border: 1px solid rgba(255,255,255,0.09);
520
+ background: rgba(10,12,15,0.40);
521
+ padding: 14px;
522
+ color: #94a3b8;
523
+ font-size: 0.86rem;
524
+ }
525
+ .canvas-bg {
526
+ background:
527
+ radial-gradient(circle at 20% 0%, rgba(255,255,255,0.045), transparent 32%),
528
+ radial-gradient(circle at 90% 10%, rgba(255,255,255,0.035), transparent 28%),
529
+ radial-gradient(rgba(255,255,255,0.05) 1px, transparent 1px),
530
+ var(--app-bg);
531
+ background-size: auto, auto, 22px 22px, auto;
532
+ }
533
+ .liquid-action {
534
+ position: relative;
535
+ display: inline-flex;
536
+ align-items: center;
537
+ justify-content: center;
538
+ min-height: 48px;
539
+ min-width: 152px;
540
+ overflow: hidden;
541
+ isolation: isolate;
542
+ padding: 13px 26px;
543
+ border-radius: 28px;
544
+ border: 1px solid rgba(255,255,255,0.24);
545
+ color: #0f172a;
546
+ font-weight: 700;
547
+ letter-spacing: 0;
548
+ box-shadow:
549
+ 0 18px 42px rgba(0,0,0,0.38),
550
+ 0 1px 0 rgba(255,255,255,0.18),
551
+ inset 0 1px 0 rgba(255,255,255,0.42);
552
+ transform: translateZ(0);
553
+ transition: transform 180ms ease, border-color 180ms ease, box-shadow 180ms ease;
554
+ cursor: pointer;
555
+ white-space: nowrap;
556
+ }
557
+ .liquid-action::before {
558
+ content: "";
559
+ position: absolute;
560
+ inset: 1px;
561
+ z-index: 4;
562
+ border-radius: inherit;
563
+ background:
564
+ linear-gradient(180deg, rgba(255,255,255,0.62), rgba(255,255,255,0.08) 38%, rgba(255,255,255,0.0) 64%),
565
+ radial-gradient(circle at 26% 20%, rgba(255,255,255,0.72), transparent 20%);
566
+ opacity: 0.72;
567
+ mix-blend-mode: screen;
568
+ pointer-events: none;
569
+ transition: opacity 180ms ease, transform 180ms ease;
570
+ }
571
+ .liquid-action::after {
572
+ content: "";
573
+ position: absolute;
574
+ inset: 0;
575
+ z-index: 5;
576
+ border-radius: inherit;
577
+ background:
578
+ radial-gradient(ellipse at 50% 0%, rgba(255,255,255,0.85), transparent 45%),
579
+ linear-gradient(180deg, rgba(255,255,255,0.16), rgba(255,255,255,0.0));
580
+ opacity: 0.34;
581
+ pointer-events: none;
582
+ }
583
+ .liquid-action:hover {
584
+ transform: translateY(-2px) scale(1.025);
585
+ border-color: rgba(255,255,255,0.34);
586
+ box-shadow:
587
+ 0 22px 48px rgba(0,0,0,0.42),
588
+ 0 1px 0 rgba(255,255,255,0.20),
589
+ inset 0 1px 0 rgba(255,255,255,0.48);
590
+ }
591
+ .liquid-action:hover::before {
592
+ opacity: 0.88;
593
+ transform: translateY(-1px);
594
+ }
595
+ .liquid-action:active {
596
+ transform: scale(0.975);
597
+ }
598
+ .liquid-action:active .liquid-depth {
599
+ filter: saturate(1.04) brightness(0.98);
600
+ }
601
+ .liquid-depth,
602
+ .liquid-layer,
603
+ .liquid-shine,
604
+ .liquid-shadow,
605
+ .text-overlay {
606
+ position: absolute;
607
+ inset: 0;
608
+ border-radius: inherit;
609
+ }
610
+ .liquid-depth {
611
+ z-index: 1;
612
+ overflow: hidden;
613
+ background:
614
+ radial-gradient(circle at 22% 20%, rgba(255,255,255,0.95), transparent 26%),
615
+ linear-gradient(120deg, rgba(255,255,255,0.95), rgba(180,200,255,0.95));
616
+ }
617
+ .liquid-layer {
618
+ z-index: 1;
619
+ inset: -42%;
620
+ background:
621
+ conic-gradient(
622
+ from 0deg,
623
+ rgba(255,255,255,0.95),
624
+ rgba(180,200,255,0.95),
625
+ rgba(226,232,240,0.92),
626
+ rgba(255,255,255,0.95),
627
+ rgba(180,200,255,0.95)
628
+ );
629
+ filter: blur(9px) saturate(145%);
630
+ mix-blend-mode: soft-light;
631
+ animation: liquidRotate 7.5s linear infinite;
632
+ opacity: 0.92;
633
+ }
634
+ .liquid-layer.layer-b {
635
+ inset: -54%;
636
+ animation-duration: 11s;
637
+ animation-direction: reverse;
638
+ opacity: 0.58;
639
+ filter: blur(14px) saturate(155%);
640
+ transform-origin: 46% 52%;
641
+ }
642
+ .liquid-layer.layer-c {
643
+ inset: -30%;
644
+ animation-duration: 5.8s;
645
+ opacity: 0.38;
646
+ filter: blur(20px);
647
+ mix-blend-mode: overlay;
648
+ }
649
+ .liquid-shine {
650
+ z-index: 3;
651
+ background:
652
+ radial-gradient(circle at 18% 18%, rgba(255,255,255,0.92), transparent 19%),
653
+ linear-gradient(105deg, rgba(255,255,255,0.62), rgba(255,255,255,0.10) 36%, rgba(255,255,255,0.0) 62%);
654
+ opacity: 0.58;
655
+ transform: translateX(-10%);
656
+ animation: liquidHighlight 4.8s ease-in-out infinite;
657
+ mix-blend-mode: screen;
658
+ }
659
+ .liquid-shadow {
660
+ z-index: 2;
661
+ background:
662
+ radial-gradient(circle at 72% 78%, rgba(15,23,42,0.22), transparent 32%),
663
+ linear-gradient(180deg, rgba(255,255,255,0.18), rgba(15,23,42,0.10));
664
+ mix-blend-mode: multiply;
665
+ opacity: 0.45;
666
+ }
667
+ .text-overlay {
668
+ z-index: 6;
669
+ display: flex;
670
+ align-items: center;
671
+ justify-content: center;
672
+ padding: 0 24px;
673
+ color: rgba(15,23,42,0.92);
674
+ text-shadow: 0 1px 0 rgba(255,255,255,0.46);
675
+ transition: color 180ms ease, transform 180ms ease, text-shadow 180ms ease;
676
+ }
677
+ .liquid-action:hover .text-overlay {
678
+ color: rgba(2,6,23,0.96);
679
+ transform: translateY(-1px);
680
+ text-shadow: 0 1px 0 rgba(255,255,255,0.62);
681
+ }
682
+ .liquid-action:active .text-overlay {
683
+ transform: translateY(1px);
684
+ }
685
+ @keyframes liquidRotate {
686
+ from { transform: rotate(0deg) scale(1.02); }
687
+ to { transform: rotate(360deg) scale(1.02); }
688
+ }
689
+ @keyframes liquidHighlight {
690
+ 0%, 100% { transform: translateX(-12%) translateY(-2%); opacity: 0.50; }
691
+ 50% { transform: translateX(10%) translateY(3%); opacity: 0.74; }
692
+ }
693
+ @media (prefers-reduced-motion: reduce) {
694
+ .liquid-layer,
695
+ .liquid-shine {
696
+ animation: none;
697
+ }
698
+ }
699
+ </style>
700
+ """
701
+
702
+
703
+ def landing_visual_styles():
704
+ return """
705
+ <style>
706
+ .hero-visual {
707
+ min-height: 520px;
708
+ perspective: 1200px;
709
+ }
710
+ .local-folder-entry {
711
+ min-height: 260px;
712
+ border-radius: 16px;
713
+ transition: border-color 180ms ease, background 180ms ease, box-shadow 180ms ease;
714
+ }
715
+ .local-folder-entry:hover {
716
+ border-color: rgba(245, 158, 11, 0.24);
717
+ background:
718
+ radial-gradient(circle at 50% 26%, rgba(245,158,11,0.08), transparent 38%),
719
+ linear-gradient(180deg, rgba(255,255,255,0.07), rgba(255,255,255,0.035));
720
+ box-shadow:
721
+ 0 14px 32px rgba(0,0,0,0.38),
722
+ 0 0 34px rgba(245,158,11,0.08),
723
+ inset 0 1px 0 rgba(255,255,255,0.07);
724
+ }
725
+ .file {
726
+ transition: transform 220ms ease;
727
+ }
728
+ .local-folder-entry:hover .file,
729
+ .file:focus-visible {
730
+ transform: translateY(-4px) rotateX(5deg);
731
+ outline: none;
732
+ }
733
+ .work-5,
734
+ .work-4,
735
+ .work-3,
736
+ .work-2,
737
+ .work-1 {
738
+ transition: transform 260ms ease, filter 260ms ease, opacity 260ms ease;
739
+ box-shadow: 0 18px 28px rgba(0,0,0,0.22);
740
+ }
741
+ .work-5::before {
742
+ content: "";
743
+ position: absolute;
744
+ left: 0;
745
+ top: -18px;
746
+ width: 96px;
747
+ height: 34px;
748
+ border-radius: 16px 16px 0 0;
749
+ background: rgb(217 119 6);
750
+ }
751
+ .local-folder-entry:hover .work-5 {
752
+ transform: rotateX(-15deg);
753
+ filter: brightness(1.05);
754
+ }
755
+ .local-folder-entry:hover .work-4 {
756
+ transform: translateY(-8px) rotateX(-18deg);
757
+ }
758
+ .local-folder-entry:hover .work-3 {
759
+ transform: translateY(-14px) rotateX(-22deg);
760
+ }
761
+ .local-folder-entry:hover .work-2 {
762
+ transform: translateY(-20px) rotateX(-26deg);
763
+ }
764
+ .local-folder-entry:hover .work-1 {
765
+ transform: translateY(2px) rotateX(-8deg);
766
+ filter: brightness(1.04);
767
+ }
768
+ .architecture-orbit {
769
+ position: relative;
770
+ height: 520px;
771
+ transform-style: preserve-3d;
772
+ animation: architectureOrbit 28s linear infinite;
773
+ }
774
+ .architecture-node {
775
+ position: absolute;
776
+ left: 50%;
777
+ top: 50%;
778
+ width: 168px;
779
+ min-height: 88px;
780
+ display: flex;
781
+ align-items: center;
782
+ justify-content: center;
783
+ padding: 18px;
784
+ border-radius: 16px;
785
+ border: 1px solid rgba(255,255,255,0.15);
786
+ background:
787
+ linear-gradient(180deg, rgba(255,255,255,0.12), rgba(255,255,255,0.035)),
788
+ radial-gradient(circle at 24% 18%, rgba(255,255,255,0.18), transparent 34%);
789
+ box-shadow:
790
+ 0 24px 54px rgba(0,0,0,0.34),
791
+ inset 0 1px 0 rgba(255,255,255,0.10);
792
+ backdrop-filter: blur(20px) saturate(155%);
793
+ -webkit-backdrop-filter: blur(20px) saturate(155%);
794
+ color: rgba(229,231,235,0.92);
795
+ font-size: 0.88rem;
796
+ font-weight: 650;
797
+ text-align: center;
798
+ line-height: 1.35;
799
+ letter-spacing: 0;
800
+ transform-style: preserve-3d;
801
+ }
802
+ .architecture-node::before {
803
+ content: "";
804
+ position: absolute;
805
+ inset: 0;
806
+ border-radius: inherit;
807
+ background: linear-gradient(135deg, rgba(255,255,255,0.16), rgba(170,190,220,0.07), rgba(120,140,170,0.05));
808
+ opacity: 0.8;
809
+ pointer-events: none;
810
+ }
811
+ .architecture-node span {
812
+ position: relative;
813
+ z-index: 1;
814
+ }
815
+ .architecture-core {
816
+ position: absolute;
817
+ left: 50%;
818
+ top: 50%;
819
+ width: 230px;
820
+ min-height: 132px;
821
+ display: flex;
822
+ flex-direction: column;
823
+ align-items: center;
824
+ justify-content: center;
825
+ gap: 8px;
826
+ padding: 22px;
827
+ border-radius: 16px;
828
+ border: 1px solid rgba(255,255,255,0.18);
829
+ background:
830
+ linear-gradient(180deg, rgba(255,255,255,0.14), rgba(255,255,255,0.04)),
831
+ radial-gradient(circle at 50% 0%, rgba(210,220,235,0.16), transparent 58%);
832
+ box-shadow:
833
+ 0 28px 64px rgba(0,0,0,0.42),
834
+ inset 0 1px 0 rgba(255,255,255,0.13);
835
+ backdrop-filter: blur(24px) saturate(165%);
836
+ -webkit-backdrop-filter: blur(24px) saturate(165%);
837
+ transform: translate3d(-50%, -50%, 90px);
838
+ transform-style: preserve-3d;
839
+ }
840
+ .architecture-core .core-label {
841
+ color: rgba(255,255,255,0.9);
842
+ font-size: 0.78rem;
843
+ font-weight: 600;
844
+ text-transform: uppercase;
845
+ letter-spacing: 0.08em;
846
+ }
847
+ .architecture-core .core-value {
848
+ color: white;
849
+ font-size: 1.55rem;
850
+ font-weight: 720;
851
+ }
852
+ .architecture-node:nth-child(1) { transform: translate3d(-50%, -50%, 0) rotateY(0deg) translateZ(250px); }
853
+ .architecture-node:nth-child(2) { transform: translate3d(-50%, -50%, 0) rotateY(40deg) translateZ(250px); }
854
+ .architecture-node:nth-child(3) { transform: translate3d(-50%, -50%, 0) rotateY(80deg) translateZ(250px); }
855
+ .architecture-node:nth-child(4) { transform: translate3d(-50%, -50%, 0) rotateY(120deg) translateZ(250px); }
856
+ .architecture-node:nth-child(5) { transform: translate3d(-50%, -50%, 0) rotateY(160deg) translateZ(250px); }
857
+ .architecture-node:nth-child(6) { transform: translate3d(-50%, -50%, 0) rotateY(200deg) translateZ(250px); }
858
+ .architecture-node:nth-child(7) { transform: translate3d(-50%, -50%, 0) rotateY(240deg) translateZ(250px); }
859
+ .architecture-node:nth-child(8) { transform: translate3d(-50%, -50%, 0) rotateY(280deg) translateZ(250px); }
860
+ .architecture-node:nth-child(9) { transform: translate3d(-50%, -50%, 0) rotateY(320deg) translateZ(250px); }
861
+ .architecture-rail {
862
+ position: absolute;
863
+ left: 50%;
864
+ top: 50%;
865
+ width: 440px;
866
+ height: 440px;
867
+ border-radius: 999px;
868
+ border: 1px solid rgba(210,220,235,0.11);
869
+ transform: translate(-50%, -50%) rotateX(72deg);
870
+ box-shadow: inset 0 0 42px rgba(255,255,255,0.035);
871
+ }
872
+ @keyframes architectureOrbit {
873
+ from { transform: rotateX(-8deg) rotateY(0deg); }
874
+ to { transform: rotateX(-8deg) rotateY(360deg); }
875
+ }
876
+ @media (prefers-reduced-motion: reduce) {
877
+ .architecture-orbit {
878
+ animation: none;
879
+ }
880
+ }
881
+ </style>
882
+ """
883
+
884
+
885
+ def liquid_action_button(label, href=None, extra_class=""):
886
+ safe_label = escape(label)
887
+ content = f"""
888
+ <span class="liquid-depth">
889
+ <span class="liquid-layer layer-a"></span>
890
+ <span class="liquid-layer layer-b"></span>
891
+ <span class="liquid-layer layer-c"></span>
892
+ <span class="liquid-shadow"></span>
893
+ <span class="liquid-shine"></span>
894
+ </span>
895
+ <span class="text-overlay">{safe_label}</span>
896
+ """
897
+ class_name = f"liquid-action {extra_class}".strip()
898
+
899
+ if href:
900
+ return f'<a href="{escape(href, quote=True)}" class="{class_name}">{content}</a>'
901
+
902
+ return f'<span class="{class_name}">{content}</span>'
903
+
904
+
905
+ def repository_context_chip(repo):
906
+ if not repo:
907
+ return ""
908
+ last_analyzed = repo.get("last_analyzed") or "not tracked"
909
+ return f"""
910
+ <div class="glass rounded-xl px-3 py-2 text-xs text-slate-400">
911
+ <span class="font-semibold text-slate-100">{escape(repo.get("name", "Repository"))}</span>
912
+ <span class="mx-2 text-slate-600">/</span>
913
+ <span>{escape(repo.get("source_type", "local"))}</span>
914
+ <span class="mx-2 text-slate-600">/</span>
915
+ <span>{escape(last_analyzed)}</span>
916
+ </div>
917
+ """
918
+
919
+
920
+ def product_nav(encoded_path=None, repo=None):
921
+ if not encoded_path:
922
+ encoded_path = quote(default_repository_path())
923
+ return f"""
924
+ <nav class="glass-nav">
925
+ <div class="mx-auto flex max-w-6xl flex-col gap-3 px-6 py-4 md:flex-row md:items-center md:justify-between">
926
+ <div class="flex flex-col gap-2">
927
+ <a href="/" class="text-sm font-semibold uppercase tracking-wide text-white/80">ADRE</a>
928
+ {repository_context_chip(repo)}
929
+ </div>
930
+ <div class="flex flex-wrap gap-2 text-sm">
931
+ <a href="/" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Home</a>
932
+ <a href="/decisions?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Decisions</a>
933
+ <a href="/explore?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Explore</a>
934
+ <a href="/dashboard?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Dashboard</a>
935
+ <a href="/graph?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Graph</a>
936
+ <a href="/evolution?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Evolution</a>
937
+ <a href="/stability?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-slate-200">Stability</a>
938
+ </div>
939
+ </div>
940
+ </nav>
941
+ """
942
+
943
+
944
+ def resolve_project_file(project_path, file_path):
945
+ if not file_path:
946
+ return None
947
+ if os.path.isabs(file_path):
948
+ return os.path.normpath(file_path)
949
+ return os.path.normpath(os.path.join(project_path, file_path))
950
+
951
+
952
+ def issue_search_terms(issue):
953
+ terms = []
954
+ imported = issue.get("imported", "")
955
+ if issue.get("issue_type") == "cycle" and " -> " in imported:
956
+ imported = imported.split(" -> ", 1)[0]
957
+ if imported:
958
+ terms.extend([
959
+ imported,
960
+ imported.replace("/", ".").replace(".py", ""),
961
+ os.path.splitext(os.path.basename(imported))[0],
962
+ ])
963
+ return [term for term in dict.fromkeys(terms) if term]
964
+
965
+
966
+ def find_issue_line(project_path, issue):
967
+ if issue.get("line"):
968
+ try:
969
+ return max(1, int(issue["line"]))
970
+ except (TypeError, ValueError):
971
+ pass
972
+ absolute_path = resolve_project_file(project_path, issue.get("file"))
973
+ if not absolute_path or not os.path.isfile(absolute_path):
974
+ return 1
975
+
976
+ terms = issue_search_terms(issue)
977
+ try:
978
+ with open(absolute_path, "r", encoding="utf-8") as source:
979
+ lines = source.readlines()
980
+ except OSError:
981
+ return 1
982
+
983
+ for index, line in enumerate(lines, start=1):
984
+ stripped = line.strip()
985
+ if not stripped or stripped.startswith("#"):
986
+ continue
987
+ if ("import " in stripped or "from " in stripped) and any(term in stripped for term in terms):
988
+ return index
989
+
990
+ for index, line in enumerate(lines, start=1):
991
+ if line.strip():
992
+ return index
993
+ return 1
994
+
995
+
996
+ def code_preview(project_path, issue, context=5):
997
+ absolute_path = resolve_project_file(project_path, issue.get("file"))
998
+ if not absolute_path or not os.path.isfile(absolute_path):
999
+ return {
1000
+ "line_start": 1,
1001
+ "line_end": 1,
1002
+ "highlight_start": 1,
1003
+ "highlight_end": 1,
1004
+ "html": '<div class="code-empty">Source file is not available from this runtime.</div>',
1005
+ }
1006
+
1007
+ highlight_line = find_issue_line(project_path, issue)
1008
+ try:
1009
+ with open(absolute_path, "r", encoding="utf-8") as source:
1010
+ lines = source.readlines()
1011
+ except OSError:
1012
+ return {
1013
+ "line_start": highlight_line,
1014
+ "line_end": highlight_line,
1015
+ "highlight_start": highlight_line,
1016
+ "highlight_end": highlight_line,
1017
+ "html": '<div class="code-empty">Source preview could not be read.</div>',
1018
+ }
1019
+
1020
+ if not lines:
1021
+ return {
1022
+ "line_start": 1,
1023
+ "line_end": 1,
1024
+ "highlight_start": 1,
1025
+ "highlight_end": 1,
1026
+ "html": '<div class="code-empty">Source file is empty.</div>',
1027
+ }
1028
+
1029
+ start = max(1, highlight_line - context)
1030
+ end = min(len(lines), highlight_line + context)
1031
+ rendered_lines = []
1032
+ for line_number in range(start, end + 1):
1033
+ line = lines[line_number - 1].rstrip("\n")
1034
+ highlighted = " is-highlighted" if line_number == highlight_line else ""
1035
+ rendered_lines.append(
1036
+ f"""
1037
+ <div class="code-line{highlighted}">
1038
+ <span class="code-line-number">{line_number}</span>
1039
+ <span>{escape(line) or " "}</span>
1040
+ </div>
1041
+ """
1042
+ )
1043
+
1044
+ return {
1045
+ "line_start": start,
1046
+ "line_end": end,
1047
+ "highlight_start": highlight_line,
1048
+ "highlight_end": highlight_line,
1049
+ "html": f'<div class="code-block py-3">{"".join(rendered_lines)}</div>',
1050
+ }
1051
+
1052
+
1053
+ def source_targets(project_path, issue, preview):
1054
+ file_path = issue.get("file", "")
1055
+ absolute_path = resolve_project_file(project_path, file_path) or file_path
1056
+ line_start = preview["highlight_start"]
1057
+ line_end = preview["highlight_end"]
1058
+ github_repository = os.environ.get("GITHUB_REPOSITORY")
1059
+ branch = os.environ.get("GITHUB_HEAD_REF") or os.environ.get("GITHUB_REF_NAME") or "main"
1060
+ remote_url = ""
1061
+ if github_repository:
1062
+ remote_url = (
1063
+ f"https://github.com/{github_repository}/blob/{quote(branch)}/"
1064
+ f"{quote(file_path)}#L{line_start}-L{line_end}"
1065
+ )
1066
+ return {
1067
+ "absolute_path": absolute_path,
1068
+ "open_fields": {"path": absolute_path, "line": line_start},
1069
+ "remote_url": remote_url,
1070
+ }
1071
+
1072
+
1073
+ def issue_title(issue):
1074
+ if issue.get("title"):
1075
+ return issue["title"]
1076
+ if issue.get("issue_type") == "cycle":
1077
+ return "Circular dependency detected"
1078
+ if issue.get("issue_type") == "repository_bypass":
1079
+ return "Architecture drift detected"
1080
+ if issue.get("issue_type") == "layer_skip":
1081
+ return "Architecture drift detected"
1082
+ source_layer = issue.get("layer", "unknown")
1083
+ imported_layer = issue.get("imported_layer", "unknown")
1084
+ return f"Layer boundary violation: {source_layer} -> {imported_layer}"
1085
+
1086
+
1087
+ def short_issue_explanation(issue):
1088
+ explanation = issue.get("explanation", "")
1089
+ if ". " in explanation:
1090
+ return explanation.split(". ", 1)[0] + "."
1091
+ return explanation
1092
+
1093
+
1094
+ def render_issue_cards(project_path, issues):
1095
+ if not issues:
1096
+ return '<div class="text-sm text-slate-500">No architecture issues detected.</div>'
1097
+
1098
+ cards = []
1099
+ for index, issue in enumerate(issues[:12], start=1):
1100
+ preview = code_preview(project_path, issue)
1101
+ targets = source_targets(project_path, issue, preview)
1102
+ severity = issue.get("severity", "low")
1103
+ kind = issue.get("kind") or "deterministic"
1104
+ kind_label = "Proven from code" if kind == "deterministic" else "Inferred"
1105
+ confidence = issue.get("confidence")
1106
+ confidence_label = "{0:.0%}".format(confidence) if confidence is not None else ""
1107
+ safe_file = escape(issue.get("file", "unknown"))
1108
+ problem = escape(issue.get("problem") or short_issue_explanation(issue) or "")
1109
+ evidence_items = issue.get("evidence") or []
1110
+ evidence_html = "".join(
1111
+ f'<div class="font-mono text-xs text-slate-300">{escape(item)}</div>'
1112
+ for item in evidence_items[:4]
1113
+ )
1114
+ pattern = escape(issue.get("established") or issue.get("established_pattern") or "")
1115
+ why = escape(issue.get("reason") or issue.get("why_it_matters") or "")
1116
+ changed = escape(issue.get("changed") or "")
1117
+ affected = issue.get("affected_files") or []
1118
+ affected_html = escape(", ".join(affected[:8])) if affected else safe_file
1119
+ cards.append(
1120
+ f"""
1121
+ <article class="glass glass-card issue-card p-5" data-issue-card>
1122
+ <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
1123
+ <div class="min-w-0">
1124
+ <div class="flex flex-wrap items-center gap-3">
1125
+ <h3 class="text-base font-semibold text-slate-100">{escape(issue_title(issue))}</h3>
1126
+ <span class="severity-badge severity-{escape(severity)}">{escape(severity)}</span>
1127
+ <span class="glass-btn rounded-xl px-3 py-1 text-xs text-slate-200">{escape(kind_label)}</span>
1128
+ {f'<span class="text-xs text-slate-400">Confidence {escape(confidence_label)}</span>' if confidence_label else ""}
1129
+ </div>
1130
+ <div class="mt-2 break-all font-mono text-xs text-slate-400">{safe_file}</div>
1131
+ <p class="mt-3 max-w-3xl text-sm leading-6 text-slate-300">{problem}</p>
1132
+ {f'<div class="mt-2 text-xs text-slate-400">Changed: {changed}</div>' if changed else ""}
1133
+ <div class="mt-4 grid gap-3 text-sm text-slate-400 md:grid-cols-2">
1134
+ <div>
1135
+ <div class="text-xs uppercase tracking-wide text-slate-500">Evidence</div>
1136
+ <div class="mt-2 space-y-1">{evidence_html or '<div class="text-xs text-slate-500">No extra evidence attached.</div>'}</div>
1137
+ </div>
1138
+ <div>
1139
+ <div class="text-xs uppercase tracking-wide text-slate-500">Established</div>
1140
+ <div class="mt-2 font-mono text-xs text-slate-300">{pattern or "Not inferred"}</div>
1141
+ </div>
1142
+ </div>
1143
+ <div class="mt-3 text-xs text-slate-500">Affected files: {affected_html}</div>
1144
+ {f'<p class="mt-3 max-w-3xl text-sm leading-6 text-slate-400">Reason: {why}</p>' if why else ""}
1145
+ </div>
1146
+ <div class="flex shrink-0 flex-wrap gap-2">
1147
+ {post_button("/open", targets["open_fields"], "View Source", "glass-btn source-btn rounded-xl px-4 py-2 text-sm font-semibold")}
1148
+ <button
1149
+ type="button"
1150
+ class="glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200"
1151
+ data-copy-path-button
1152
+ data-copy-path="{escape(targets["absolute_path"], quote=True)}"
1153
+ >
1154
+ Copy Path
1155
+ </button>
1156
+ <button
1157
+ type="button"
1158
+ class="glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200"
1159
+ data-preview-button
1160
+ aria-expanded="false"
1161
+ aria-controls="issue-preview-{index}"
1162
+ >
1163
+ Preview Code
1164
+ </button>
1165
+ </div>
1166
+ </div>
1167
+ <div id="issue-preview-{index}" class="code-preview" data-code-preview>
1168
+ <div class="code-preview-inner">
1169
+ <div class="mb-2 flex items-center justify-between gap-3 text-xs text-slate-500">
1170
+ <span>Lines {preview["line_start"]}-{preview["line_end"]}</span>
1171
+ <span>Highlighted line {preview["highlight_start"]}</span>
1172
+ </div>
1173
+ {preview["html"]}
1174
+ </div>
1175
+ </div>
1176
+ </article>
1177
+ """
1178
+ )
1179
+ return "\n".join(cards)
1180
+
1181
+
1182
+ def render_scope_panel(scope, encoded_path, select_value=""):
1183
+ scope = scope or {}
1184
+ languages = scope.get("languages") or {}
1185
+ language_text = ", ".join(
1186
+ "{0}: {1}".format(name, count) for name, count in sorted(languages.items())
1187
+ ) or "none parsed"
1188
+ selected = ", ".join(scope.get("selected_files") or []) or "entire repository"
1189
+ expanded = ", ".join(scope.get("expanded_files") or []) or "none"
1190
+ incremental = scope.get("incremental") or {}
1191
+ if incremental:
1192
+ incremental_html = """
1193
+ <div class="mt-4 grid gap-3 text-xs text-slate-400 md:grid-cols-3 lg:grid-cols-6">
1194
+ <div class="glass rounded-xl px-3 py-2">Discovered {0}</div>
1195
+ <div class="glass rounded-xl px-3 py-2">Unchanged {1}</div>
1196
+ <div class="glass rounded-xl px-3 py-2">Changed {2}</div>
1197
+ <div class="glass rounded-xl px-3 py-2">Added {3}</div>
1198
+ <div class="glass rounded-xl px-3 py-2">Deleted {4}</div>
1199
+ <div class="glass rounded-xl px-3 py-2">Parsed {5} · Reused {1}</div>
1200
+ </div>
1201
+ """.format(
1202
+ incremental.get("discovered", 0),
1203
+ incremental.get("reused", 0),
1204
+ incremental.get("changed", 0),
1205
+ incremental.get("added", 0),
1206
+ incremental.get("deleted", 0),
1207
+ incremental.get("parsed", 0),
1208
+ )
1209
+ else:
1210
+ incremental_html = ""
1211
+ return f"""
1212
+ <section class="glass glass-card mb-6 p-5">
1213
+ <div class="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
1214
+ <div>
1215
+ <div class="text-sm font-medium text-slate-400">What was analyzed</div>
1216
+ <p class="mt-2 text-sm leading-6 text-slate-500">
1217
+ Indexed {scope.get("indexed_file_count", 0)} files and analyzed {scope.get("analyzed_file_count", 0)} files ({escape(language_text)}).
1218
+ </p>
1219
+ </div>
1220
+ <div class="text-xs text-slate-500">{escape(scope.get("selection_mode", "repository"))}</div>
1221
+ </div>
1222
+ <div class="mt-4 grid gap-3 text-sm text-slate-300 md:grid-cols-3">
1223
+ <div class="glass rounded-xl px-4 py-3">
1224
+ <div class="text-xs uppercase tracking-wide text-slate-500">Selected</div>
1225
+ <div class="mt-2 break-all font-mono text-xs">{escape(selected)}</div>
1226
+ </div>
1227
+ <div class="glass rounded-xl px-4 py-3">
1228
+ <div class="text-xs uppercase tracking-wide text-slate-500">Expanded from dependencies</div>
1229
+ <div class="mt-2 break-all font-mono text-xs">{escape(expanded)}</div>
1230
+ </div>
1231
+ <div class="glass rounded-xl px-4 py-3">
1232
+ <div class="text-xs uppercase tracking-wide text-slate-500">Parse errors</div>
1233
+ <div class="mt-2">{scope.get("parse_errors", 0)}</div>
1234
+ </div>
1235
+ </div>
1236
+ <div class="mt-3 grid gap-3 text-xs text-slate-500 md:grid-cols-2">
1237
+ <div>Unsupported files: {scope.get("unsupported_files", 0)}</div>
1238
+ <div>Excluded: {escape(", ".join((scope.get("excluded_directories") or [])[:8]))}</div>
1239
+ </div>
1240
+ {incremental_html}
1241
+ <form action="/dashboard" method="get" class="mt-5 grid gap-3 md:grid-cols-[1fr_auto]">
1242
+ <input type="hidden" name="path" value="{escape(scope.get("project_root") or "", quote=True)}">
1243
+ <input
1244
+ name="select"
1245
+ value="{escape(select_value)}"
1246
+ placeholder="controllers, services/user_service.py"
1247
+ class="rounded-xl border border-white/10 bg-black/25 px-4 py-3 font-mono text-sm text-slate-100 outline-none transition focus:border-white/20"
1248
+ >
1249
+ <button type="submit" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
1250
+ Analyze selection
1251
+ </button>
1252
+ </form>
1253
+ <p class="mt-3 text-xs leading-5 text-slate-500">
1254
+ Enter files or directories relative to the repository. Related imports are included automatically.
1255
+ </p>
1256
+ </section>
1257
+ """
1258
+
1259
+
1260
+ def render_architecture_panel(baseline, encoded_path="", select_value="", baseline_saved=False, saved_summary=""):
1261
+ baseline = baseline or {}
1262
+ if not baseline:
1263
+ return ""
1264
+ enough = baseline.get("enough_structure")
1265
+ classification = escape(str(baseline.get("classification") or "insufficient"))
1266
+ if enough:
1267
+ summary = escape(baseline.get("summary_path") or "Observed layers and dependency directions.")
1268
+ else:
1269
+ notes = baseline.get("notes") or []
1270
+ summary = escape(notes[0] if notes else "Not enough repeated structure to establish architecture.")
1271
+ extra = "&select={0}".format(quote(select_value)) if select_value else ""
1272
+ if baseline_saved:
1273
+ status = "Saved baseline: {0}".format(escape(saved_summary or baseline.get("summary_path") or "accepted architecture"))
1274
+ else:
1275
+ status = "No saved baseline. This panel is the current analysis, not an accepted architecture."
1276
+ layers = [layer for layer in baseline.get("layers") or [] if layer.get("role") != "unknown"]
1277
+ layer_html = "\n".join(
1278
+ """
1279
+ <div class="glass rounded-xl px-4 py-3">
1280
+ <div class="flex items-center justify-between gap-3">
1281
+ <div class="font-semibold text-slate-100">{name}</div>
1282
+ <div class="text-xs text-slate-400">{role} · {confidence:.0%}</div>
1283
+ </div>
1284
+ <div class="mt-2 text-xs leading-5 text-slate-500">{evidence}</div>
1285
+ </div>
1286
+ """.format(
1287
+ name=escape(layer.get("name") or ""),
1288
+ role=escape(layer.get("role") or "unknown"),
1289
+ confidence=float(layer.get("confidence") or 0),
1290
+ evidence=escape(((layer.get("evidence") or [{}])[0].get("detail") if layer.get("evidence") else "") or layer.get("classification") or ""),
1291
+ )
1292
+ for layer in layers[:8]
1293
+ ) or '<div class="text-sm text-slate-500">No named layers were established from this scope.</div>'
1294
+
1295
+ direction_html = "\n".join(
1296
+ """
1297
+ <div class="font-mono text-xs text-slate-300">{source} → {target} <span class="text-slate-500">({mark}, {count})</span></div>
1298
+ """.format(
1299
+ source=escape(item.get("source") or ""),
1300
+ target=escape(item.get("target") or ""),
1301
+ mark="established" if item.get("established") else "observed",
1302
+ count=item.get("count", 0),
1303
+ )
1304
+ for item in (baseline.get("directions") or [])[:10]
1305
+ ) or '<div class="text-sm text-slate-500">No cross-layer directions observed.</div>'
1306
+
1307
+ pattern_html = "\n".join(
1308
+ """
1309
+ <div class="glass rounded-xl px-4 py-3">
1310
+ <div class="font-semibold text-slate-100">{name}</div>
1311
+ <div class="mt-1 text-xs text-slate-400">{classification} · {confidence:.0%}</div>
1312
+ <div class="mt-2 text-xs leading-5 text-slate-500">{evidence}</div>
1313
+ </div>
1314
+ """.format(
1315
+ name=escape((pattern.get("name") or "").replace("_", " ")),
1316
+ classification=escape(pattern.get("classification") or "inferred"),
1317
+ confidence=float(pattern.get("confidence") or 0),
1318
+ evidence=escape(((pattern.get("evidence") or [{}])[0].get("detail") if pattern.get("evidence") else "") or pattern.get("summary") or ""),
1319
+ )
1320
+ for pattern in (baseline.get("patterns") or [])[:6]
1321
+ ) or '<div class="text-sm text-slate-500">No patterns had enough evidence to establish.</div>'
1322
+
1323
+ notes = "\n".join(
1324
+ '<p class="mt-2 text-sm leading-6 text-slate-400">{0}</p>'.format(escape(note))
1325
+ for note in (baseline.get("notes") or [])
1326
+ )
1327
+ return f"""
1328
+ <section class="glass glass-card mb-6 p-5">
1329
+ <div class="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
1330
+ <div>
1331
+ <div class="text-sm font-medium text-slate-400">Architecture</div>
1332
+ <p class="mt-2 text-sm leading-6 text-slate-300">{summary}</p>
1333
+ <p class="mt-2 text-xs text-slate-500">{status}</p>
1334
+ <p class="mt-2 text-xs text-slate-500">Classification: {classification} · Confidence {float(baseline.get("confidence") or 0):.2f}</p>
1335
+ {notes}
1336
+ </div>
1337
+ <div class="flex flex-wrap gap-2">
1338
+ {post_button("/save-baseline", {"path": unquote(encoded_path), "select": select_value or None}, "Save baseline", "glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200", confirm="Save the current architecture as the accepted baseline (.adre/baseline.json)?")}
1339
+ <a href="/review?path={encoded_path}{extra}" class="glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200">Review against baseline</a>
1340
+ <a href="/review-branch?path={encoded_path}" class="glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200">Review a branch</a>
1341
+ </div>
1342
+ </div>
1343
+ <div class="mt-5 grid gap-4 lg:grid-cols-3">
1344
+ <div>
1345
+ <div class="text-xs uppercase tracking-wide text-slate-500">Detected layers</div>
1346
+ <div class="mt-3 space-y-2">{layer_html}</div>
1347
+ </div>
1348
+ <div>
1349
+ <div class="text-xs uppercase tracking-wide text-slate-500">Dependency direction</div>
1350
+ <div class="mt-3 space-y-2">{direction_html}</div>
1351
+ </div>
1352
+ <div>
1353
+ <div class="text-xs uppercase tracking-wide text-slate-500">Established patterns</div>
1354
+ <div class="mt-3 space-y-2">{pattern_html}</div>
1355
+ </div>
1356
+ </div>
1357
+ </section>
1358
+ """
1359
+
1360
+
1361
+ def issue_card_script():
1362
+ return """
1363
+ <script>
1364
+ document.querySelectorAll('[data-preview-button]').forEach((button) => {
1365
+ button.addEventListener('click', () => {
1366
+ const card = button.closest('[data-issue-card]');
1367
+ const preview = card.querySelector('[data-code-preview]');
1368
+ const isOpen = preview.classList.toggle('is-open');
1369
+ button.setAttribute('aria-expanded', String(isOpen));
1370
+ button.textContent = isOpen ? 'Hide Code' : 'Preview Code';
1371
+ });
1372
+ });
1373
+
1374
+ document.querySelectorAll('[data-copy-path-button]').forEach((button) => {
1375
+ button.addEventListener('click', async () => {
1376
+ const copyPath = button.dataset.copyPath;
1377
+ const originalLabel = button.textContent;
1378
+ try {
1379
+ await navigator.clipboard.writeText(copyPath);
1380
+ button.textContent = 'Path Copied';
1381
+ window.setTimeout(() => { button.textContent = originalLabel; }, 1400);
1382
+ } catch (error) {
1383
+ button.textContent = 'Source Path Ready';
1384
+ window.setTimeout(() => { button.textContent = originalLabel; }, 1400);
1385
+ }
1386
+ });
1387
+ });
1388
+ </script>
1389
+ """
1390
+
1391
+
1392
+ def open_source(path: str, line: int = 1):
1393
+ absolute_path = safe_source_path(path)
1394
+ safe_line = max(1, int(line or 1))
1395
+
1396
+ if not absolute_path:
1397
+ return open_result_page(
1398
+ "Source file blocked",
1399
+ "The requested source file is missing or outside the allowed project directory.",
1400
+ path,
1401
+ safe_line,
1402
+ )
1403
+
1404
+ try:
1405
+ open_in_vscode(absolute_path, safe_line)
1406
+ except FileNotFoundError:
1407
+ return open_result_page(
1408
+ "VS Code CLI unavailable",
1409
+ "The file is valid, but VS Code could not be launched from this environment. Use Copy Path, reveal the file in Finder, or install the VS Code shell command.",
1410
+ absolute_path,
1411
+ safe_line,
1412
+ show_vscode_help=True,
1413
+ )
1414
+ except subprocess.CalledProcessError as exc:
1415
+ return open_result_page(
1416
+ "Could not open VS Code",
1417
+ f"VS Code launch returned exit code {exc.returncode}. Use Copy Path or reveal the file in Finder while you fix the VS Code CLI.",
1418
+ absolute_path,
1419
+ safe_line,
1420
+ show_vscode_help=True,
1421
+ )
1422
+
1423
+ return open_result_page(
1424
+ "Opened in VS Code",
1425
+ "VS Code was asked to open the source file at the relevant line.",
1426
+ absolute_path,
1427
+ safe_line,
1428
+ vscode_available=True,
1429
+ )
1430
+
1431
+
1432
+ def open_folder(path: str):
1433
+ absolute_path = safe_source_path(path)
1434
+ if not absolute_path:
1435
+ return open_result_page(
1436
+ "Source file blocked",
1437
+ "The requested source file is missing or outside the allowed project directory.",
1438
+ path,
1439
+ )
1440
+
1441
+ try:
1442
+ reveal_in_file_manager(absolute_path)
1443
+ except (FileNotFoundError, subprocess.CalledProcessError) as exc:
1444
+ message = str(exc) or "Could not reveal the file in the system file manager."
1445
+ return open_result_page(
1446
+ "File manager unavailable",
1447
+ message,
1448
+ absolute_path,
1449
+ show_vscode_help=False,
1450
+ )
1451
+
1452
+ label = "Finder" if platform.system() == "Darwin" else "file manager"
1453
+ return open_result_page(
1454
+ f"Opened in {label}",
1455
+ f"The source file was revealed in the system {label}.",
1456
+ absolute_path,
1457
+ )
1458
+
1459
+
1460
+ def repository_error_page(title, message, target=""):
1461
+ return f"""
1462
+ <!doctype html>
1463
+ <html lang="en">
1464
+ <head>
1465
+ <meta charset="utf-8">
1466
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1467
+ <title>{escape(title)}</title>
1468
+ <script src="https://cdn.tailwindcss.com"></script>
1469
+ {liquid_glass_styles()}
1470
+ </head>
1471
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
1472
+ {product_nav(quote(default_repository_path()))}
1473
+ <main class="mx-auto max-w-5xl px-6 py-10">
1474
+ <section class="glass glass-card p-6">
1475
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Repository loading</p>
1476
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">{escape(title)}</h1>
1477
+ <p class="mt-4 text-sm leading-6 text-slate-400">{escape(message)}</p>
1478
+ {f'<div class="mt-4 break-all font-mono text-sm text-slate-500">{escape(target)}</div>' if target else ''}
1479
+ <a href="/" class="glass-btn mt-5 rounded-xl px-4 py-3 text-sm font-medium text-slate-200">Try another repository</a>
1480
+ </section>
1481
+ <section class="mt-6 glass glass-card p-5">
1482
+ <div class="text-sm font-medium text-slate-400">Recent Repositories</div>
1483
+ <div class="mt-4 grid gap-3 md:grid-cols-2">{render_recent_repositories(show_pin=True)}</div>
1484
+ </section>
1485
+ </main>
1486
+ </body>
1487
+ </html>
1488
+ """
1489
+
1490
+
1491
+ def render_repository_list_items(repositories, selectable=False, show_pin=False):
1492
+ if not repositories:
1493
+ return '<div class="text-sm text-slate-500">No repositories available.</div>'
1494
+
1495
+ items = []
1496
+ for item in repositories:
1497
+ encoded = quote(item["path"])
1498
+ pin_badge = '<span class="ml-2 text-xs text-amber-200/80">pinned</span>' if item.get("pinned") else ""
1499
+ if selectable:
1500
+ items.append(
1501
+ f"""
1502
+ <button
1503
+ type="button"
1504
+ class="repo-picker-item glass glass-card w-full p-4 text-left"
1505
+ data-repo-path="{escape(item["path"], quote=True)}"
1506
+ >
1507
+ <div class="flex items-start justify-between gap-3">
1508
+ <div class="min-w-0">
1509
+ <div class="truncate font-semibold text-slate-100">{escape(item.get("name", "Repository"))}{pin_badge}</div>
1510
+ <div class="mt-1 text-xs uppercase tracking-wide text-slate-500">{escape(item.get("source_type", "local"))}</div>
1511
+ </div>
1512
+ <div class="shrink-0 text-xs text-slate-500">{escape(item.get("last_analyzed", ""))}</div>
1513
+ </div>
1514
+ <div class="mt-3 break-all font-mono text-xs text-slate-500">{escape(item.get("path", ""))}</div>
1515
+ </button>
1516
+ """
1517
+ )
1518
+ else:
1519
+ pin_action = ""
1520
+ if show_pin:
1521
+ pin_action = post_button(
1522
+ "/toggle-pin",
1523
+ {"path": item.get("path", "")},
1524
+ "Unpin" if item.get("pinned") else "Pin",
1525
+ "glass-btn rounded-xl px-3 py-2 text-xs text-slate-300",
1526
+ )
1527
+ items.append(
1528
+ f"""
1529
+ <div class="glass glass-card p-4">
1530
+ <div class="flex items-start justify-between gap-3">
1531
+ <a href="/dashboard?path={encoded}" class="min-w-0 flex-1">
1532
+ <div class="truncate font-semibold text-slate-100">{escape(item.get("name", "Repository"))}{pin_badge}</div>
1533
+ <div class="mt-1 text-xs uppercase tracking-wide text-slate-500">{escape(item.get("source_type", "local"))}</div>
1534
+ <div class="mt-3 break-all font-mono text-xs text-slate-500">{escape(item.get("path", ""))}</div>
1535
+ </a>
1536
+ <div class="flex shrink-0 flex-col items-end gap-2">
1537
+ <div class="text-xs text-slate-500">{escape(item.get("last_analyzed", ""))}</div>
1538
+ {pin_action}
1539
+ </div>
1540
+ </div>
1541
+ </div>
1542
+ """
1543
+ )
1544
+ return "\n".join(items)
1545
+
1546
+
1547
+ def render_recent_repositories(selectable=False, show_pin=False):
1548
+ return render_repository_list_items(get_recent_repositories(), selectable=selectable, show_pin=show_pin)
1549
+
1550
+
1551
+ def readable_source_type(source_type):
1552
+ if source_type == "github":
1553
+ return "GitHub Repository"
1554
+ return "Local Repository"
1555
+
1556
+
1557
+ def relative_time_label(value):
1558
+ if not value:
1559
+ return "not analyzed"
1560
+ try:
1561
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
1562
+ except ValueError:
1563
+ return value
1564
+ if parsed.tzinfo is None:
1565
+ parsed = parsed.replace(tzinfo=timezone.utc)
1566
+ seconds = max(0, int((datetime.now(timezone.utc) - parsed).total_seconds()))
1567
+ if seconds < 60:
1568
+ return "just now"
1569
+ minutes = seconds // 60
1570
+ if minutes < 60:
1571
+ return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
1572
+ hours = minutes // 60
1573
+ if hours < 24:
1574
+ return f"{hours} hour{'s' if hours != 1 else ''} ago"
1575
+ days = hours // 24
1576
+ if days == 1:
1577
+ return "Yesterday"
1578
+ if days < 30:
1579
+ return f"{days} days ago"
1580
+ return parsed.date().isoformat()
1581
+
1582
+
1583
+ def render_home_repository_cards(repositories, empty_message="No repositories yet.", favorite=False):
1584
+ if not repositories:
1585
+ return f'<div class="glass rounded-xl px-4 py-4 text-sm text-slate-500">{escape(empty_message)}</div>'
1586
+
1587
+ cards = []
1588
+ for item in repositories:
1589
+ encoded_path = quote(item.get("path", ""))
1590
+ reanalyze_target = item.get("source_url") if item.get("source_type") == "github" and item.get("source_url") else item.get("path", "")
1591
+ reanalyze_button = post_button(
1592
+ "/load-repository",
1593
+ {"source_type": item.get("source_type", "local"), "target": reanalyze_target},
1594
+ "Reanalyze",
1595
+ "glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-200",
1596
+ )
1597
+ pin_button = post_button(
1598
+ "/toggle-pin",
1599
+ {"path": item.get("path", "")},
1600
+ "Unpin" if item.get("pinned") else "Pin",
1601
+ "glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-400",
1602
+ )
1603
+ pin_label = "Unpin" if item.get("pinned") else "Pin"
1604
+ favorite_badge = '<span class="rounded-full border border-amber-300/20 px-2 py-1 text-xs text-amber-200/80">Favorite</span>' if favorite or item.get("pinned") else ""
1605
+ cards.append(
1606
+ f"""
1607
+ <article class="glass glass-card p-4">
1608
+ <div class="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
1609
+ <div class="min-w-0">
1610
+ <div class="flex flex-wrap items-center gap-2">
1611
+ <h3 class="truncate text-base font-semibold text-slate-100">{escape(item.get("name", "Repository"))}</h3>
1612
+ {favorite_badge}
1613
+ </div>
1614
+ <div class="mt-2 text-sm text-slate-400">{escape(readable_source_type(item.get("source_type", "local")))}</div>
1615
+ <div class="mt-1 text-xs text-slate-500">Last analyzed: {escape(relative_time_label(item.get("last_analyzed")))}</div>
1616
+ <div class="mt-3 break-all font-mono text-xs text-slate-600">{escape(item.get("path", ""))}</div>
1617
+ </div>
1618
+ <div class="flex shrink-0 flex-wrap gap-2 md:justify-end">
1619
+ <a href="/dashboard?path={encoded_path}" class="glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-200">Open Dashboard</a>
1620
+ {reanalyze_button}
1621
+ {pin_button}
1622
+ </div>
1623
+ </div>
1624
+ </article>
1625
+ """
1626
+ )
1627
+ return "\n".join(cards)
1628
+
1629
+
1630
+ def decision_one_line_reason(item):
1631
+ reasons = [reason.strip() for reason in item.get("reason", []) if reason and reason.strip()]
1632
+ if reasons:
1633
+ first_reason = reasons[0]
1634
+ if len(first_reason) > 140:
1635
+ return first_reason[:137] + "..."
1636
+ return first_reason
1637
+ context = item.get("explanation_context", {}).get("why_it_matters", "")
1638
+ if context:
1639
+ return context.split(". ", 1)[0] + ("." if ". " in context else "")
1640
+ return "Architectural pressure detected in the selected repository."
1641
+
1642
+
1643
+ def decision_severity_label(item):
1644
+ impact = item.get("impact_level", "low")
1645
+ if impact == "high":
1646
+ return "High"
1647
+ if impact == "medium":
1648
+ return "Medium"
1649
+ return "Low"
1650
+
1651
+
1652
+ def decision_group_key(item):
1653
+ signals = set(item.get("source_signals", []))
1654
+ if "cycle" in signals:
1655
+ return "cycles"
1656
+ if "hotspot" in signals:
1657
+ return "hotspots"
1658
+ if "layer_violation" in signals:
1659
+ return "layer_violations"
1660
+ return "other"
1661
+
1662
+
1663
+ def render_decision_cards(report):
1664
+ grouped = {
1665
+ "cycles": [],
1666
+ "hotspots": [],
1667
+ "layer_violations": [],
1668
+ "other": [],
1669
+ }
1670
+ for item in report.get("decisions", [])[:20]:
1671
+ grouped[decision_group_key(item)].append(item)
1672
+
1673
+ group_labels = {
1674
+ "cycles": "Cycles",
1675
+ "hotspots": "Hotspots",
1676
+ "layer_violations": "Layer Violations",
1677
+ "other": "Other Decisions",
1678
+ }
1679
+ sections = []
1680
+ card_index = 0
1681
+
1682
+ for group_name in ("cycles", "hotspots", "layer_violations", "other"):
1683
+ items = grouped[group_name]
1684
+ if not items:
1685
+ continue
1686
+
1687
+ cards = []
1688
+ for item in items[:8]:
1689
+ card_index += 1
1690
+ affected = ", ".join(item.get("affected_files", [])[:4]) or "Repository-wide"
1691
+ details = "\n".join(reason.strip() for reason in item.get("reason", []) if reason and reason.strip())
1692
+ extra_context = item.get("explanation_context", {}).get("why_it_matters", "")
1693
+ if extra_context and extra_context not in details:
1694
+ details = f"{details}\n\n{extra_context}".strip()
1695
+ severity = decision_severity_label(item).lower()
1696
+ cards.append(
1697
+ f"""
1698
+ <article class="glass rounded-xl px-4 py-4" data-decision-card>
1699
+ <div class="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
1700
+ <div class="min-w-0">
1701
+ <div class="flex flex-wrap items-center gap-3">
1702
+ <h3 class="text-base font-semibold text-slate-100">{escape(item.get("action", "Architecture decision"))}</h3>
1703
+ <span class="severity-badge severity-{escape(severity)}">{escape(decision_severity_label(item))}</span>
1704
+ </div>
1705
+ <p class="mt-2 text-sm leading-6 text-slate-400">{escape(decision_one_line_reason(item))}</p>
1706
+ <div class="mt-3 break-all text-xs text-slate-500">{escape(affected)}</div>
1707
+ </div>
1708
+ <button
1709
+ type="button"
1710
+ class="glass-btn shrink-0 rounded-xl px-4 py-2 text-sm font-medium text-slate-200"
1711
+ data-decision-toggle
1712
+ aria-expanded="false"
1713
+ aria-controls="decision-details-{card_index}"
1714
+ >
1715
+ Details
1716
+ </button>
1717
+ </div>
1718
+ <div id="decision-details-{card_index}" class="decision-details mt-0 hidden text-sm leading-6 text-slate-500">
1719
+ <div class="mt-4 whitespace-pre-wrap">{escape(details or "No additional details available.")}</div>
1720
+ </div>
1721
+ </article>
1722
+ """
1723
+ )
1724
+
1725
+ sections.append(
1726
+ f"""
1727
+ <section class="space-y-3">
1728
+ <div class="text-sm font-medium text-slate-400">{escape(group_labels[group_name])}</div>
1729
+ <div class="space-y-3">{"".join(cards)}</div>
1730
+ </section>
1731
+ """
1732
+ )
1733
+
1734
+ if not sections:
1735
+ return '<div class="text-sm text-slate-500">No architecture decisions generated.</div>'
1736
+ return "\n".join(sections)
1737
+
1738
+
1739
+ def decision_card_script():
1740
+ return """
1741
+ <script>
1742
+ document.querySelectorAll('[data-decision-toggle]').forEach((button) => {
1743
+ button.addEventListener('click', () => {
1744
+ const card = button.closest('[data-decision-card]');
1745
+ const details = card.querySelector('.decision-details');
1746
+ const isOpen = details.classList.toggle('hidden') === false;
1747
+ button.setAttribute('aria-expanded', String(isOpen));
1748
+ button.textContent = isOpen ? 'Hide Details' : 'Details';
1749
+ });
1750
+ });
1751
+ </script>
1752
+ """
1753
+
1754
+
1755
+ def repository_picker_script():
1756
+ return """
1757
+ <script>
1758
+ const form = document.getElementById('repository-form');
1759
+ const progress = document.getElementById('analysis-progress');
1760
+ const stages = Array.from(document.querySelectorAll('.progress-stage'));
1761
+ const targetInput = document.getElementById('repository-target');
1762
+ const sourceTypeInput = document.getElementById('repository-source-type');
1763
+ const drawer = document.getElementById('folder-drawer');
1764
+ const drawerList = document.getElementById('folder-drawer-list');
1765
+ const drawerPath = document.getElementById('folder-drawer-path');
1766
+ const browseButton = document.getElementById('browse-folders');
1767
+ const analyzeSelectedButton = document.getElementById('analyze-selected-folder');
1768
+ const closeDrawerButton = document.getElementById('close-folder-drawer');
1769
+ const selectedFolderLabel = document.getElementById('selected-folder-label');
1770
+ const selectedPanel = document.getElementById('selected-repository-panel');
1771
+ const selectedName = document.getElementById('selected-repository-name');
1772
+ const manualLocalPath = document.getElementById('manual-local-path');
1773
+ const useManualLocalPath = document.getElementById('use-manual-local-path');
1774
+ const analyzeGithubButton = document.getElementById('analyze-github-button');
1775
+ const githubTarget = document.getElementById('github-target');
1776
+
1777
+ function openFolderDrawer() {
1778
+ drawer.classList.remove('hidden');
1779
+ drawer.classList.add('flex');
1780
+ }
1781
+
1782
+ function closeFolderDrawer() {
1783
+ drawer.classList.add('hidden');
1784
+ drawer.classList.remove('flex');
1785
+ }
1786
+
1787
+ function setSelectedFolder(path) {
1788
+ targetInput.value = path;
1789
+ sourceTypeInput.value = 'local';
1790
+ selectedFolderLabel.textContent = path || 'No local folder selected.';
1791
+ selectedName.textContent = path ? (path.split('/').filter(Boolean).pop() || path) : 'Repository';
1792
+ selectedPanel.classList.toggle('hidden', !path);
1793
+ if (manualLocalPath) {
1794
+ manualLocalPath.value = path || '';
1795
+ }
1796
+ }
1797
+
1798
+ function escapeHtml(value) {
1799
+ return String(value || '')
1800
+ .replaceAll('&', '&amp;')
1801
+ .replaceAll('<', '&lt;')
1802
+ .replaceAll('>', '&gt;')
1803
+ .replaceAll('"', '&quot;')
1804
+ .replaceAll("'", '&#39;');
1805
+ }
1806
+
1807
+ async function loadDirectories(path = '') {
1808
+ const query = path ? `?path=${encodeURIComponent(path)}` : '';
1809
+ const response = await fetch(`/api/browse-directories${query}`);
1810
+ const data = await response.json();
1811
+ if (!response.ok) {
1812
+ drawerList.innerHTML = `<div class="text-sm text-red-300">${data.detail || 'Could not load folders.'}</div>`;
1813
+ return;
1814
+ }
1815
+ drawerPath.textContent = data.parent || 'Quick locations';
1816
+ const rows = [];
1817
+ if (data.can_go_up && data.parent_up) {
1818
+ const parentPath = escapeHtml(data.parent_up);
1819
+ rows.push(`<button type="button" class="folder-entry glass rounded-xl px-4 py-3 text-left text-sm text-slate-200" data-folder-path="${parentPath}">.. Parent folder</button>`);
1820
+ }
1821
+ data.directories.forEach((entry) => {
1822
+ const safePath = escapeHtml(entry.path);
1823
+ const safeName = escapeHtml(entry.name);
1824
+ const selectButton = `<button type="button" class="select-folder glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200" data-folder-path="${safePath}">Select</button>`;
1825
+ rows.push(`
1826
+ <div class="glass rounded-xl px-4 py-3 text-sm text-slate-200">
1827
+ <div class="flex items-start justify-between gap-3">
1828
+ <button type="button" class="folder-entry min-w-0 flex-1 text-left" data-folder-path="${safePath}">
1829
+ <span class="font-medium text-white">${safeName}</span>
1830
+ <div class="mt-1 break-all font-mono text-xs text-slate-500">${safePath}</div>
1831
+ </button>
1832
+ ${selectButton}
1833
+ </div>
1834
+ </div>
1835
+ `);
1836
+ });
1837
+ drawerList.innerHTML = rows.join('') || '<div class="text-sm text-slate-500">No readable folders found.</div>';
1838
+ drawerList.querySelectorAll('.folder-entry').forEach((button) => {
1839
+ button.addEventListener('click', () => {
1840
+ setSelectedFolder(button.dataset.folderPath);
1841
+ loadDirectories(button.dataset.folderPath);
1842
+ });
1843
+ });
1844
+ drawerList.querySelectorAll('.select-folder').forEach((button) => {
1845
+ button.addEventListener('click', () => {
1846
+ setSelectedFolder(button.dataset.folderPath);
1847
+ closeFolderDrawer();
1848
+ });
1849
+ });
1850
+ }
1851
+
1852
+ browseButton?.addEventListener('click', async () => {
1853
+ openFolderDrawer();
1854
+ await loadDirectories('');
1855
+ });
1856
+
1857
+ closeDrawerButton?.addEventListener('click', closeFolderDrawer);
1858
+ drawer?.addEventListener('click', (event) => {
1859
+ if (event.target === drawer) {
1860
+ closeFolderDrawer();
1861
+ }
1862
+ });
1863
+
1864
+ useManualLocalPath?.addEventListener('click', () => {
1865
+ const path = manualLocalPath.value.trim();
1866
+ if (!path) {
1867
+ return;
1868
+ }
1869
+ setSelectedFolder(path);
1870
+ closeFolderDrawer();
1871
+ });
1872
+
1873
+ function submitSelectedFolder() {
1874
+ if (!targetInput.value) {
1875
+ openFolderDrawer();
1876
+ return;
1877
+ }
1878
+ sourceTypeInput.value = 'local';
1879
+ form.requestSubmit();
1880
+ }
1881
+
1882
+ analyzeSelectedButton?.addEventListener('click', submitSelectedFolder);
1883
+
1884
+ analyzeGithubButton?.addEventListener('click', () => {
1885
+ sourceTypeInput.value = 'github';
1886
+ });
1887
+
1888
+ githubTarget?.addEventListener('keydown', (event) => {
1889
+ if (event.key === 'Enter') {
1890
+ sourceTypeInput.value = 'github';
1891
+ }
1892
+ });
1893
+
1894
+ form.addEventListener('submit', (event) => {
1895
+ const sourceType = sourceTypeInput.value || 'local';
1896
+ if (sourceType === 'github') {
1897
+ const githubValue = document.getElementById('github-target')?.value?.trim();
1898
+ if (!githubValue) {
1899
+ event.preventDefault();
1900
+ return;
1901
+ }
1902
+ targetInput.value = githubValue;
1903
+ } else if (!targetInput.value) {
1904
+ event.preventDefault();
1905
+ openFolderDrawer();
1906
+ return;
1907
+ }
1908
+
1909
+ progress.classList.remove('hidden');
1910
+ stages.forEach((stage, index) => {
1911
+ stage.style.borderColor = 'rgba(255,255,255,0.10)';
1912
+ stage.style.color = 'rgb(203,213,225)';
1913
+ window.setTimeout(() => {
1914
+ stage.style.borderColor = 'rgba(226,232,240,0.28)';
1915
+ stage.style.color = 'white';
1916
+ }, index * 420);
1917
+ });
1918
+ });
1919
+ </script>
1920
+ """
1921
+
1922
+
1923
+ @app.get("/api/browse-directories")
1924
+ def browse_directories(path: str = ""):
1925
+ try:
1926
+ return list_browsable_directories(path or None)
1927
+ except ValueError as exc:
1928
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
1929
+
1930
+
1931
+ def pin_repository(path: str):
1932
+ entry = toggle_repository_pin(resolve_repository_path(path))
1933
+ if not entry:
1934
+ return RedirectResponse(url="/", status_code=303)
1935
+ return RedirectResponse(url=f"/dashboard?path={quote(entry['path'])}", status_code=303)
1936
+
1937
+
1938
+ def load_repository(source_type: str, target: str):
1939
+ try:
1940
+ if source_type == "local":
1941
+ entry = register_local_repository(target)
1942
+ elif source_type == "github":
1943
+ entry = register_github_repository(target)
1944
+ else:
1945
+ raise ValueError("Choose either Local Folder or GitHub Repository.")
1946
+ except Exception as exc:
1947
+ return repository_error_page("Repository could not be loaded", str(exc), target)
1948
+
1949
+ return RedirectResponse(url=f"/dashboard?path={quote(entry['path'])}", status_code=303)
1950
+
1951
+
1952
+ @app.get("/", response_class=HTMLResponse)
1953
+ def root():
1954
+ default_path = default_repository_path()
1955
+ encoded_path = quote(default_path)
1956
+ pinned = get_pinned_repositories()
1957
+ recent = [item for item in get_recent_repositories() if not item.get("pinned")]
1958
+ pinned_html = render_home_repository_cards(pinned, "Pin repositories you use often to keep them here.", favorite=True)
1959
+ recent_html = render_home_repository_cards(recent, "Analyze a repository to see it here.")
1960
+
1961
+ return f"""
1962
+ <!doctype html>
1963
+ <html lang="en">
1964
+ <head>
1965
+ <meta charset="utf-8">
1966
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1967
+ <title>ADRE</title>
1968
+ <script src="https://cdn.tailwindcss.com"></script>
1969
+ {liquid_glass_styles()}
1970
+ </head>
1971
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
1972
+ {product_nav(encoded_path)}
1973
+ <main class="mx-auto max-w-6xl px-6 py-12">
1974
+ <section class="mx-auto max-w-4xl text-center">
1975
+ <p class="mb-4 text-sm font-medium uppercase tracking-wide text-white/60">ADRE</p>
1976
+ <h1 class="text-4xl font-semibold tracking-tight text-white md:text-6xl">
1977
+ Understand architecture risk across software repositories.
1978
+ </h1>
1979
+ <p class="mx-auto mt-6 max-w-3xl text-lg leading-8 text-slate-400">
1980
+ Understand architecture, dependencies, drift, hotspots, and technical risk across software repositories.
1981
+ </p>
1982
+ </section>
1983
+
1984
+ <section class="mx-auto mt-10 max-w-4xl glass glass-card p-6 md:p-8">
1985
+ <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
1986
+ <div>
1987
+ <h2 class="text-2xl font-semibold tracking-tight text-white">Analyze Repository</h2>
1988
+ <p class="mt-2 text-sm leading-6 text-slate-400">
1989
+ Select a local project or analyze a GitHub repository.
1990
+ </p>
1991
+ </div>
1992
+ <div class="rounded-full border border-white/10 px-3 py-1 text-xs text-slate-500">Existing analysis engine</div>
1993
+ </div>
1994
+
1995
+ <form id="repository-form" action="/load-repository" method="post" class="mt-6 space-y-5">
1996
+ {csrf_input()}
1997
+ <input type="hidden" name="source_type" id="repository-source-type" value="local">
1998
+ <input type="hidden" name="target" id="repository-target" value="">
1999
+
2000
+ <div class="grid gap-4 md:grid-cols-[1.1fr_0.9fr]">
2001
+ <section class="glass rounded-2xl p-5">
2002
+ <div class="text-sm font-medium text-slate-300">Local Repository</div>
2003
+ <p class="mt-2 text-sm leading-6 text-slate-500">Recommended for repositories already on this machine.</p>
2004
+ <button type="button" id="browse-folders" class="source-btn glass-btn mt-5 w-full rounded-xl px-5 py-4 text-base font-semibold">
2005
+ Select Local Repository
2006
+ </button>
2007
+
2008
+ <div id="selected-repository-panel" class="mt-5 hidden rounded-2xl border border-emerald-300/15 bg-emerald-950/10 p-4">
2009
+ <div class="text-sm font-semibold text-emerald-200">✓ Repository Selected</div>
2010
+ <div id="selected-repository-name" class="mt-2 text-lg font-semibold text-white">Repository</div>
2011
+ <div id="selected-folder-label" class="mt-1 break-all font-mono text-xs text-slate-400"></div>
2012
+ <button type="button" id="analyze-selected-folder" class="glass-btn mt-4 rounded-xl px-4 py-3 text-sm font-semibold text-slate-100">
2013
+ Analyze Repository
2014
+ </button>
2015
+ </div>
2016
+ </section>
2017
+
2018
+ <section class="glass rounded-2xl p-5">
2019
+ <div class="text-sm font-medium text-slate-300">GitHub Repository</div>
2020
+ <p class="mt-2 text-sm leading-6 text-slate-500">Paste a public GitHub repository URL.</p>
2021
+ <input
2022
+ id="github-target"
2023
+ placeholder="https://github.com/user/repo"
2024
+ class="mt-5 w-full rounded-xl border border-white/10 bg-black/25 px-4 py-3 font-mono text-sm text-slate-100 outline-none transition focus:border-white/20"
2025
+ >
2026
+ <button type="submit" id="analyze-github-button" class="glass-btn mt-3 w-full rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2027
+ Analyze GitHub Repository
2028
+ </button>
2029
+ </section>
2030
+ </div>
2031
+ </form>
2032
+ </section>
2033
+
2034
+ <section id="analysis-progress" class="mx-auto mt-5 hidden max-w-4xl glass glass-card p-5">
2035
+ <div class="text-sm font-medium text-slate-400">Analysis Progress</div>
2036
+ <div class="mt-4 grid gap-3 text-sm text-slate-300 md:grid-cols-5">
2037
+ <div class="progress-stage glass rounded-xl px-4 py-3">Loading repository</div>
2038
+ <div class="progress-stage glass rounded-xl px-4 py-3">Building dependency graph</div>
2039
+ <div class="progress-stage glass rounded-xl px-4 py-3">Running architecture analysis</div>
2040
+ <div class="progress-stage glass rounded-xl px-4 py-3">Calculating intelligence reports</div>
2041
+ <div class="progress-stage glass rounded-xl px-4 py-3">Rendering dashboard</div>
2042
+ </div>
2043
+ </section>
2044
+
2045
+ <div id="folder-drawer" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/60 px-4 py-8 backdrop-blur-sm">
2046
+ <div class="glass glass-card max-h-[86vh] w-full max-w-3xl overflow-hidden p-5">
2047
+ <div class="flex items-start justify-between gap-4">
2048
+ <div>
2049
+ <div class="text-sm font-medium text-slate-300">Select Local Repository</div>
2050
+ <div id="folder-drawer-path" class="mt-2 break-all font-mono text-xs text-slate-500">Quick locations</div>
2051
+ </div>
2052
+ <button type="button" id="close-folder-drawer" class="glass-btn rounded-xl px-3 py-2 text-sm text-slate-200">Close</button>
2053
+ </div>
2054
+ <div class="mt-4 grid gap-3 md:grid-cols-[1fr_auto]">
2055
+ <input
2056
+ id="manual-local-path"
2057
+ placeholder="~/projects/my-app"
2058
+ class="rounded-xl border border-white/10 bg-black/25 px-4 py-3 font-mono text-sm text-slate-100 outline-none transition focus:border-white/20"
2059
+ >
2060
+ <button type="button" id="use-manual-local-path" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2061
+ Use Path
2062
+ </button>
2063
+ </div>
2064
+ <div id="folder-drawer-list" class="mt-4 max-h-[48vh] space-y-2 overflow-y-auto"></div>
2065
+ </div>
2066
+ </div>
2067
+
2068
+ <section class="mx-auto mt-10 max-w-5xl">
2069
+ <div class="mb-4 flex items-center justify-between gap-4">
2070
+ <h2 class="text-xl font-semibold text-white">Pinned Repositories</h2>
2071
+ <div class="text-sm text-slate-500">Favorites stay at the top.</div>
2072
+ </div>
2073
+ <div class="grid gap-3">{pinned_html}</div>
2074
+ </section>
2075
+
2076
+ <section class="mx-auto mt-8 max-w-5xl">
2077
+ <div class="mb-4 flex items-center justify-between gap-4">
2078
+ <h2 class="text-xl font-semibold text-white">Recent Repositories</h2>
2079
+ <div class="text-sm text-slate-500">Previously analyzed projects.</div>
2080
+ </div>
2081
+ <div class="grid gap-3">{recent_html}</div>
2082
+ </section>
2083
+ </main>
2084
+ {repository_picker_script()}
2085
+ </body>
2086
+ </html>
2087
+ """
2088
+
2089
+
2090
+ @app.get("/scan-structure")
2091
+ def scan_structure(path: str = ""):
2092
+ project_root = resolve_repository_path(path) if path else default_repository_path()
2093
+ return scan_project_structure(project_root)
2094
+
2095
+
2096
+ @app.get("/analyze-drift")
2097
+ def analyze_drift(path: str = ""):
2098
+ project_root = resolve_repository_path(path) if path else default_repository_path()
2099
+ return analyze_project_drift(project_root)
2100
+
2101
+
2102
+ @app.get("/dependency-graph")
2103
+ def dependency_graph(path: str = ""):
2104
+ project_root = resolve_repository_path(path) if path else default_repository_path()
2105
+ graph = build_dependency_graph(project_root)
2106
+ return {
2107
+ "project_root": project_root,
2108
+ "dependency_graph": graph
2109
+ }
2110
+
2111
+
2112
+ @app.get("/analyze-architecture")
2113
+ def analyze_architecture(path: str = "", select: str = ""):
2114
+ project_root = resolve_repository_path(path) if path else default_repository_path()
2115
+ analysis = analyze_project_architecture(project_root, selected_paths=parse_select_query(select))
2116
+ save_architecture_snapshot(analysis)
2117
+ severity_counts = analysis["severity_counts"]
2118
+ display_score = analysis["score"]
2119
+
2120
+ return {
2121
+ "score": display_score,
2122
+ "raw_score": analysis["score"],
2123
+ "summary": {
2124
+ "total_issues": len(analysis["issues"]),
2125
+ "critical_severity": severity_counts["critical"],
2126
+ "high_severity": severity_counts["high"],
2127
+ "medium_severity": severity_counts["medium"],
2128
+ "low_severity": severity_counts["low"],
2129
+ "cycle_count": len(analysis["cycles"]),
2130
+ "indirect_dependency_count": len(analysis["indirect_dependencies"]),
2131
+ "hotspot_count": len(analysis["hotspot_files"])
2132
+ },
2133
+ "issues": analysis["issues"],
2134
+ "findings": analysis.get("findings", []),
2135
+ "scope": analysis.get("scope"),
2136
+ "established_pattern": analysis.get("established_pattern"),
2137
+ "architecture_type": analysis.get("architecture_type"),
2138
+ "incremental": analysis.get("incremental"),
2139
+ "architecture": {
2140
+ "classification": (analysis.get("architecture") or {}).get("classification"),
2141
+ "enough_structure": (analysis.get("architecture") or {}).get("enough_structure"),
2142
+ "confidence": (analysis.get("architecture") or {}).get("confidence"),
2143
+ "summary_path": (analysis.get("architecture") or {}).get("summary_path"),
2144
+ "layers": [
2145
+ {
2146
+ "name": layer.get("name"),
2147
+ "role": layer.get("role"),
2148
+ "confidence": layer.get("confidence"),
2149
+ "classification": layer.get("classification"),
2150
+ }
2151
+ for layer in (analysis.get("architecture") or {}).get("layers") or []
2152
+ if layer.get("role") != "unknown"
2153
+ ],
2154
+ "patterns": [
2155
+ {
2156
+ "name": pattern.get("name"),
2157
+ "classification": pattern.get("classification"),
2158
+ "confidence": pattern.get("confidence"),
2159
+ }
2160
+ for pattern in (analysis.get("architecture") or {}).get("patterns") or []
2161
+ ],
2162
+ },
2163
+ "cycles": analysis["cycles"],
2164
+ "indirect_dependencies": analysis["indirect_dependencies"],
2165
+ "hotspot_files": analysis["hotspot_files"],
2166
+ "architecture_risk_model": analysis["risk_scores"],
2167
+ "priority_issues": analysis["priority_issues"],
2168
+ "file_risk_ranking": analysis["file_risk_ranking"],
2169
+ "refactor_recommendations": analysis["refactor_recommendations"],
2170
+ "dependency_graph": analysis["dependency_graph"]
2171
+ }
2172
+
2173
+
2174
+ @app.get("/architecture-report")
2175
+ def architecture_report(path: str = ""):
2176
+ project_root = resolve_repository_path(path) if path else default_repository_path()
2177
+ analysis = analyze_project_architecture(project_root)
2178
+ return build_architecture_report(analysis)
2179
+
2180
+
2181
+ @app.get("/architecture-history")
2182
+ def architecture_history():
2183
+ return build_architecture_history()
2184
+
2185
+
2186
+ @app.get("/compare-snapshots")
2187
+ def compare_snapshots(file1: str, file2: str):
2188
+ before = load_snapshot_file(file1)
2189
+ after = load_snapshot_file(file2)
2190
+ before["file"] = os.path.basename(file1)
2191
+ after["file"] = os.path.basename(file2)
2192
+ return compare_snapshot_data(before, after)
2193
+
2194
+
2195
+ @app.get("/decisions", response_class=HTMLResponse)
2196
+ def decisions(path: str):
2197
+ project_path = resolve_repository_path(path)
2198
+ repo_context = ensure_repository_context(project_path)
2199
+ encoded_path = quote(project_path)
2200
+
2201
+ try:
2202
+ report = generate_architecture_decisions(project_path)
2203
+ explanation = generate_architecture_explanation(project_path)
2204
+ report = attach_explanation_context_to_decisions(report, explanation)
2205
+ except Exception as exc:
2206
+ safe_error = escape(str(exc))
2207
+ return f"""
2208
+ <!doctype html>
2209
+ <html lang="en">
2210
+ <head>
2211
+ <meta charset="utf-8">
2212
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2213
+ <title>Architecture Decisions</title>
2214
+ <script src="https://cdn.tailwindcss.com"></script>
2215
+ {liquid_glass_styles()}
2216
+ </head>
2217
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2218
+ {product_nav(encoded_path, repo_context)}
2219
+ <main class="mx-auto max-w-6xl px-6 py-10">
2220
+ <section class="glass glass-card p-6">
2221
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Architecture Decisions</p>
2222
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">Decision report unavailable</h1>
2223
+ <p class="mt-4 text-sm leading-6 text-slate-400">The decision engine could not aggregate this project.</p>
2224
+ <div class="mt-4 glass rounded-xl px-4 py-3 text-sm text-slate-300">{safe_error}</div>
2225
+ </section>
2226
+ </main>
2227
+ </body>
2228
+ </html>
2229
+ """
2230
+
2231
+ summary = report.get("executive_summary", {})
2232
+ health = summary.get("current_architecture_health", {})
2233
+ impact = report.get("impact_overview", {})
2234
+ decisions_html = render_decision_cards(report)
2235
+ has_structural_issues = any(
2236
+ decision_group_key(item) in {"cycles", "layer_violations"}
2237
+ for item in report.get("decisions", [])
2238
+ )
2239
+ health_score = min(int(health.get("score", 0)), 99) if has_structural_issues else int(health.get("score", 0))
2240
+
2241
+ risks_html = "\n".join(
2242
+ f'<div class="glass rounded-xl px-4 py-3 text-sm leading-6 text-slate-300">{escape(risk)}</div>'
2243
+ for risk in report.get("key_risks", [])[:4]
2244
+ ) or '<div class="text-sm text-slate-500">No systemic risks detected.</div>'
2245
+
2246
+ return f"""
2247
+ <!doctype html>
2248
+ <html lang="en">
2249
+ <head>
2250
+ <meta charset="utf-8">
2251
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2252
+ <title>Architecture Decisions</title>
2253
+ <script src="https://cdn.tailwindcss.com"></script>
2254
+ {liquid_glass_styles()}
2255
+ <style>
2256
+ .decision-details.hidden {{ display: none; }}
2257
+ </style>
2258
+ </head>
2259
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2260
+ {product_nav(encoded_path, repo_context)}
2261
+ <main class="mx-auto max-w-6xl px-6 py-10">
2262
+ <header class="mb-8">
2263
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">Architecture decision engine</p>
2264
+ <div class="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
2265
+ <div>
2266
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Decisions</h1>
2267
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
2268
+ </div>
2269
+ <div class="flex flex-wrap gap-2">
2270
+ <a href="/dashboard?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2271
+ Open dashboard
2272
+ </a>
2273
+ <a href="/explore?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2274
+ Explore architecture
2275
+ </a>
2276
+ </div>
2277
+ </div>
2278
+ </header>
2279
+
2280
+ <section class="grid gap-4 md:grid-cols-4">
2281
+ <div class="glass glass-card p-5">
2282
+ <div class="text-sm font-medium text-slate-400">Architecture Health</div>
2283
+ <div class="mt-3 text-3xl font-semibold text-white">{health_score}/100</div>
2284
+ <p class="mt-3 text-sm text-slate-500">{escape(str(health.get("architecture_type", "unknown")))}</p>
2285
+ </div>
2286
+ <div class="glass glass-card p-5">
2287
+ <div class="text-sm font-medium text-slate-400">Stability</div>
2288
+ <div class="mt-3 text-3xl font-semibold text-white">{health.get("stability_score", 0)}/100</div>
2289
+ <p class="mt-3 text-sm text-slate-500">Governance stability signal.</p>
2290
+ </div>
2291
+ <div class="glass glass-card p-5">
2292
+ <div class="text-sm font-medium text-slate-400">Trajectory</div>
2293
+ <div class="mt-3 text-3xl font-semibold text-white">{escape(summary.get("overall_trajectory", "stable"))}</div>
2294
+ <p class="mt-3 text-sm text-slate-500">Architecture movement over time.</p>
2295
+ </div>
2296
+ <div class="glass glass-card p-5">
2297
+ <div class="text-sm font-medium text-slate-400">High Impact</div>
2298
+ <div class="mt-3 text-3xl font-semibold text-white">{impact.get("high", 0)}</div>
2299
+ <p class="mt-3 text-sm text-slate-500">Grouped by cycles, hotspots, and layer violations.</p>
2300
+ </div>
2301
+ </section>
2302
+
2303
+ <section class="mt-6 glass glass-card p-5">
2304
+ <div class="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
2305
+ <div>
2306
+ <div class="text-sm font-medium text-slate-400">Decision Cards</div>
2307
+ <p class="mt-2 text-sm text-slate-500">Each card shows the title, severity, affected files, and one-line reason. Long explanations stay collapsed until expanded.</p>
2308
+ </div>
2309
+ <div class="text-xs text-slate-500">Main weakness: {escape(str(summary.get("main_structural_weakness", "unknown")))}</div>
2310
+ </div>
2311
+ <div class="mt-5 space-y-6">{decisions_html}</div>
2312
+ </section>
2313
+
2314
+ <section class="mt-6 glass glass-card p-5">
2315
+ <div class="text-sm font-medium text-slate-400">Key Risks</div>
2316
+ <div class="mt-4 space-y-3">{risks_html}</div>
2317
+ </section>
2318
+ </main>
2319
+ {decision_card_script()}
2320
+ </body>
2321
+ </html>
2322
+ """
2323
+
2324
+
2325
+ @app.get("/explore", response_class=HTMLResponse)
2326
+ def explore(path: str):
2327
+ project_path = resolve_repository_path(path)
2328
+ repo_context = ensure_repository_context(project_path)
2329
+ encoded_path = quote(project_path)
2330
+
2331
+ try:
2332
+ explanation = generate_architecture_explanation(project_path)
2333
+ except Exception as exc:
2334
+ safe_error = escape(str(exc))
2335
+ return f"""
2336
+ <!doctype html>
2337
+ <html lang="en">
2338
+ <head>
2339
+ <meta charset="utf-8">
2340
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2341
+ <title>Architecture Explorer</title>
2342
+ <script src="https://cdn.tailwindcss.com"></script>
2343
+ {liquid_glass_styles()}
2344
+ </head>
2345
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2346
+ {product_nav(encoded_path, repo_context)}
2347
+ <main class="mx-auto max-w-4xl px-6 py-10">
2348
+ <section class="glass glass-card p-6">
2349
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Architecture Explorer</p>
2350
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">Explanation unavailable</h1>
2351
+ <p class="mt-4 text-sm leading-6 text-slate-400">The explainer could not interpret this project.</p>
2352
+ <div class="mt-4 glass rounded-xl px-4 py-3 text-sm text-slate-300">{safe_error}</div>
2353
+ </section>
2354
+ </main>
2355
+ </body>
2356
+ </html>
2357
+ """
2358
+
2359
+ patterns_html = "\n".join(
2360
+ f"""
2361
+ <div class="glass rounded-xl px-4 py-4">
2362
+ <div class="font-semibold text-slate-100">{escape(item["name"])}</div>
2363
+ <div class="mt-2 text-sm leading-6 text-slate-400">{escape(item["explanation"])}</div>
2364
+ </div>
2365
+ """
2366
+ for item in explanation.get("core_patterns", [])
2367
+ ) or '<div class="text-sm text-slate-500">No dominant architecture patterns detected.</div>'
2368
+
2369
+ subsystems_html = "\n".join(
2370
+ f"""
2371
+ <article class="glass rounded-xl px-5 py-5">
2372
+ <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
2373
+ <div>
2374
+ <h3 class="text-lg font-semibold text-white">{escape(item["subsystem"])}/</h3>
2375
+ <p class="mt-1 text-sm text-slate-500">{escape(item["role"])}</p>
2376
+ </div>
2377
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">
2378
+ {escape(item["risk_level"])} risk
2379
+ </div>
2380
+ </div>
2381
+ <p class="mt-4 text-sm leading-7 text-slate-300">{escape(item["story"])}</p>
2382
+ <div class="mt-4 grid gap-2 text-xs text-slate-400 sm:grid-cols-4">
2383
+ <div class="glass rounded-xl px-3 py-2">Files: {item["file_count"]}</div>
2384
+ <div class="glass rounded-xl px-3 py-2">Issues: {item["issue_count"]}</div>
2385
+ <div class="glass rounded-xl px-3 py-2">Cycles: {item["cycle_participants"]}</div>
2386
+ <div class="glass rounded-xl px-3 py-2">Hotspots: {item["hotspots"]}</div>
2387
+ </div>
2388
+ </article>
2389
+ """
2390
+ for item in explanation.get("key_subsystems", [])
2391
+ ) or '<div class="text-sm text-slate-500">No subsystem stories available.</div>'
2392
+
2393
+ coupling_html = "\n".join(
2394
+ f"""
2395
+ <div class="glass rounded-xl px-4 py-4">
2396
+ <div class="text-xs uppercase tracking-wide text-slate-500">{escape(item["type"])}</div>
2397
+ <div class="mt-2 text-sm leading-6 text-slate-300">{escape(item["explanation"])}</div>
2398
+ </div>
2399
+ """
2400
+ for item in explanation.get("coupling_explanation", [])
2401
+ ) or '<div class="text-sm text-slate-500">No coupling narrative available.</div>'
2402
+
2403
+ return f"""
2404
+ <!doctype html>
2405
+ <html lang="en">
2406
+ <head>
2407
+ <meta charset="utf-8">
2408
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2409
+ <title>Architecture Explorer</title>
2410
+ <script src="https://cdn.tailwindcss.com"></script>
2411
+ {liquid_glass_styles()}
2412
+ </head>
2413
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2414
+ {product_nav(encoded_path, repo_context)}
2415
+ <main class="mx-auto max-w-4xl px-6 py-10">
2416
+ <header class="mb-8">
2417
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">Architecture explainability</p>
2418
+ <div class="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
2419
+ <div>
2420
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Explorer</h1>
2421
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
2422
+ </div>
2423
+ <a href="/decisions?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2424
+ View decisions
2425
+ </a>
2426
+ </div>
2427
+ </header>
2428
+
2429
+ <section class="glass glass-card p-6">
2430
+ <p class="text-sm font-medium text-slate-400">System Overview</p>
2431
+ <p class="mt-4 text-lg leading-8 text-slate-200">{escape(explanation["architecture_summary"])}</p>
2432
+ </section>
2433
+
2434
+ <section class="mt-6 grid gap-4 md:grid-cols-2">
2435
+ <div class="glass glass-card p-5">
2436
+ <div class="text-sm font-medium text-slate-400">Detected Patterns</div>
2437
+ <div class="mt-4 space-y-3">{patterns_html}</div>
2438
+ </div>
2439
+ <div class="glass glass-card p-5">
2440
+ <div class="text-sm font-medium text-slate-400">Dependency Narrative</div>
2441
+ <p class="mt-4 text-sm leading-7 text-slate-300">{escape(explanation.get("dependency_narrative", ""))}</p>
2442
+ <div class="mt-4 space-y-3">{coupling_html}</div>
2443
+ </div>
2444
+ </section>
2445
+
2446
+ <section class="mt-6 glass glass-card p-5">
2447
+ <div class="text-sm font-medium text-slate-400">Subsystem Stories</div>
2448
+ <div class="mt-4 space-y-4">{subsystems_html}</div>
2449
+ </section>
2450
+
2451
+ <section class="mt-6 glass glass-card p-6">
2452
+ <p class="text-sm font-medium text-slate-400">Risk Narrative</p>
2453
+ <p class="mt-4 text-lg leading-8 text-slate-200">{escape(explanation.get("risk_narrative", ""))}</p>
2454
+ </section>
2455
+ </main>
2456
+ </body>
2457
+ </html>
2458
+ """
2459
+
2460
+
2461
+ @app.get("/dashboard", response_class=HTMLResponse)
2462
+ def dashboard(path: str, select: str = ""):
2463
+ project_path = resolve_repository_path(path)
2464
+ repo_context = ensure_repository_context(project_path)
2465
+ selected_paths = parse_select_query(select)
2466
+ analysis = analyze_project_architecture(project_path, selected_paths=selected_paths)
2467
+ display_score = analysis["score"]
2468
+ severity_counts = analysis["severity_counts"]
2469
+ total_issues = len(analysis["issues"])
2470
+ cycle_count = len(analysis["cycles"])
2471
+ hotspot_count = len(analysis["hotspot_files"])
2472
+ encoded_path = quote(project_path)
2473
+ top_risks = analysis.get("file_risk_ranking", [])[:5]
2474
+ recommendations = analysis.get("refactor_recommendations", [])[:5]
2475
+ issue_cards_html = render_issue_cards(project_path, analysis.get("issues", []))
2476
+ saved_baseline_path = resolve_baseline_path(project_path)
2477
+ baseline_saved = os.path.isfile(saved_baseline_path)
2478
+ saved_summary = ""
2479
+ if baseline_saved:
2480
+ try:
2481
+ saved = load_architecture_baseline(saved_baseline_path)
2482
+ saved_summary = saved.get("summary_path") or saved.get("architecture_type") or ""
2483
+ except (OSError, ValueError, json.JSONDecodeError):
2484
+ saved_summary = ""
2485
+ scope_html = render_scope_panel(analysis.get("scope"), encoded_path, select_value=select)
2486
+ architecture_html = render_architecture_panel(
2487
+ analysis.get("architecture"),
2488
+ encoded_path,
2489
+ select_value=select,
2490
+ baseline_saved=baseline_saved,
2491
+ saved_summary=saved_summary,
2492
+ )
2493
+
2494
+ if top_risks:
2495
+ top_risks_html = "\n".join(
2496
+ f"""
2497
+ <div class="glass rounded-xl px-4 py-3">
2498
+ <div class="flex items-start justify-between gap-4">
2499
+ <div>
2500
+ <div class="break-all font-semibold text-slate-100">{escape(item["file"])}</div>
2501
+ <div class="mt-1 text-xs text-slate-500">{escape(", ".join(item.get("reasons", [])))}</div>
2502
+ </div>
2503
+ <div class="text-lg font-semibold text-white">{item["risk_score"]}</div>
2504
+ </div>
2505
+ </div>
2506
+ """
2507
+ for item in top_risks
2508
+ )
2509
+ else:
2510
+ top_risks_html = '<div class="text-sm text-slate-500">No high-leverage file risks detected.</div>'
2511
+
2512
+ if recommendations:
2513
+ recommendations_html = "\n".join(
2514
+ f"""
2515
+ <div class="glass rounded-xl px-4 py-4">
2516
+ <div class="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
2517
+ <div>
2518
+ <div class="font-semibold text-slate-100">{escape(item["title"])}</div>
2519
+ <div class="mt-2 text-sm leading-6 text-slate-500">{escape(item["expected_benefit"])}</div>
2520
+ </div>
2521
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">Impact: {escape(item.get("impact", "medium").title())}</div>
2522
+ </div>
2523
+ </div>
2524
+ """
2525
+ for item in recommendations
2526
+ )
2527
+ else:
2528
+ recommendations_html = '<div class="text-sm text-slate-500">No immediate refactor recommendations generated.</div>'
2529
+
2530
+ return f"""
2531
+ <!doctype html>
2532
+ <html lang="en">
2533
+ <head>
2534
+ <meta charset="utf-8">
2535
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2536
+ <title>ADRE Dashboard</title>
2537
+ <script src="https://cdn.tailwindcss.com"></script>
2538
+ {liquid_glass_styles()}
2539
+ </head>
2540
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2541
+ {product_nav(encoded_path, repo_context)}
2542
+ <main class="mx-auto max-w-6xl px-6 py-10">
2543
+ <header class="mb-8">
2544
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">ADRE</p>
2545
+ <div class="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
2546
+ <div>
2547
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Dashboard</h1>
2548
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
2549
+ </div>
2550
+ <div class="flex flex-wrap gap-3">
2551
+ {liquid_action_button("Run Architecture Scan", f"/analyze-architecture?path={encoded_path}")}
2552
+ {liquid_action_button("Generate Report", f"/architecture-report?path={encoded_path}")}
2553
+ <a href="/graph?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
2554
+ View dependency graph
2555
+ </a>
2556
+ </div>
2557
+ </div>
2558
+ </header>
2559
+
2560
+ <section class="glass glass-card mb-6 p-5">
2561
+ <div class="grid gap-3 md:grid-cols-4">
2562
+ <div>
2563
+ <div class="text-xs uppercase tracking-wide text-slate-500">Repository</div>
2564
+ <div class="mt-1 break-all font-semibold text-slate-100">{escape(repo_context.get("name", "Repository"))}</div>
2565
+ </div>
2566
+ <div>
2567
+ <div class="text-xs uppercase tracking-wide text-slate-500">Source Type</div>
2568
+ <div class="mt-1 font-semibold text-slate-100">{escape(repo_context.get("source_type", "local"))}</div>
2569
+ </div>
2570
+ <div>
2571
+ <div class="text-xs uppercase tracking-wide text-slate-500">Last Analysis</div>
2572
+ <div class="mt-1 font-semibold text-slate-100">{escape(repo_context.get("last_analyzed") or "not tracked")}</div>
2573
+ </div>
2574
+ <div>
2575
+ <div class="text-xs uppercase tracking-wide text-slate-500">Resolved Path</div>
2576
+ <div class="mt-1 break-all font-mono text-xs text-slate-400">{escape(repo_context.get("path", project_path))}</div>
2577
+ </div>
2578
+ </div>
2579
+ </section>
2580
+
2581
+ {scope_html}
2582
+
2583
+ {architecture_html}
2584
+
2585
+ <section class="glass glass-card mb-6 p-6">
2586
+ <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
2587
+ <div>
2588
+ <p class="text-sm font-medium text-white/65">Architecture Score</p>
2589
+ <div class="mt-2 text-6xl font-bold tracking-tight text-white">{display_score}<span class="text-2xl text-slate-400">/100</span></div>
2590
+ </div>
2591
+ <div class="grid gap-3 text-sm text-slate-300 sm:grid-cols-2">
2592
+ <div class="glass rounded-xl px-4 py-3">
2593
+ <div class="text-slate-500">Architecture type</div>
2594
+ <div class="mt-1 font-semibold text-slate-100">{escape(str(analysis.get("architecture_type", "unknown")))}</div>
2595
+ <div class="mt-2 font-mono text-xs text-slate-400">{escape(analysis.get("established_pattern") or "pattern inferred from dependencies")}</div>
2596
+ </div>
2597
+ <div class="glass rounded-xl px-4 py-3">
2598
+ <div class="text-slate-500">Confidence</div>
2599
+ <div class="mt-1 font-semibold text-slate-100">{analysis.get("architecture_confidence", 0):.2f}</div>
2600
+ </div>
2601
+ </div>
2602
+ </div>
2603
+ </section>
2604
+
2605
+ <section class="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
2606
+ <div class="glass glass-card p-5">
2607
+ <div class="text-sm font-medium text-slate-400">Issues</div>
2608
+ <div class="mt-3 text-3xl font-semibold text-white">{total_issues}</div>
2609
+ <div class="mt-4 grid grid-cols-2 gap-2 text-sm">
2610
+ <div class="glass rounded-lg px-3 py-2 text-red-200">Critical: {severity_counts["critical"]}</div>
2611
+ <div class="glass rounded-lg px-3 py-2 text-orange-200">High: {severity_counts["high"]}</div>
2612
+ <div class="glass rounded-lg px-3 py-2 text-amber-200">Medium: {severity_counts["medium"]}</div>
2613
+ <div class="glass rounded-lg px-3 py-2 text-slate-200">Low: {severity_counts["low"]}</div>
2614
+ </div>
2615
+ </div>
2616
+
2617
+ <div class="glass glass-card p-5">
2618
+ <div class="text-sm font-medium text-slate-400">Cycles</div>
2619
+ <div class="mt-3 text-3xl font-semibold text-white">{cycle_count}</div>
2620
+ <p class="mt-3 text-sm text-slate-500">Circular dependency paths detected in the resolved graph.</p>
2621
+ </div>
2622
+
2623
+ <div class="glass glass-card p-5">
2624
+ <div class="text-sm font-medium text-slate-400">Hotspots</div>
2625
+ <div class="mt-3 text-3xl font-semibold text-white">{hotspot_count}</div>
2626
+ <p class="mt-3 text-sm text-slate-500">Files with the most inbound dependency pressure.</p>
2627
+ </div>
2628
+
2629
+ <div class="glass glass-card p-5">
2630
+ <div class="text-sm font-medium text-slate-400">Drift</div>
2631
+ <div class="mt-3 text-3xl font-semibold text-white">Tracked</div>
2632
+ <p class="mt-3 text-sm text-slate-500">Architecture snapshots and history are available through the drift timeline.</p>
2633
+ </div>
2634
+
2635
+ <div class="glass glass-card p-5">
2636
+ <div class="text-sm font-medium text-slate-400">PR Risk</div>
2637
+ <div class="mt-3 text-3xl font-semibold text-white">Ready</div>
2638
+ <p class="mt-3 text-sm text-slate-500">Pull request checks can flag cycles, score drops, and structural regressions.</p>
2639
+ </div>
2640
+
2641
+ <div class="glass glass-card p-5">
2642
+ <div class="text-sm font-medium text-slate-400">Severity mix</div>
2643
+ <div class="mt-4 space-y-2">
2644
+ <div class="flex items-center justify-between text-sm"><span class="text-red-300">Critical</span><span>{severity_counts["critical"]}</span></div>
2645
+ <div class="flex items-center justify-between text-sm"><span class="text-orange-300">High</span><span>{severity_counts["high"]}</span></div>
2646
+ <div class="flex items-center justify-between text-sm"><span class="text-amber-300">Medium</span><span>{severity_counts["medium"]}</span></div>
2647
+ <div class="flex items-center justify-between text-sm"><span class="text-slate-300">Low</span><span>{severity_counts["low"]}</span></div>
2648
+ </div>
2649
+ </div>
2650
+ </section>
2651
+
2652
+ <section class="mt-6 glass glass-card p-5">
2653
+ <div class="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
2654
+ <div>
2655
+ <div class="text-sm font-medium text-slate-400">Issue Inspection</div>
2656
+ <p class="mt-2 text-sm leading-6 text-slate-500">
2657
+ Verify each finding against evidence and source. Inferred conclusions are labeled separately from proven graph facts.
2658
+ </p>
2659
+ </div>
2660
+ <div class="text-xs text-slate-500">Code previews stay collapsed by default.</div>
2661
+ </div>
2662
+ <div class="mt-5 space-y-4">
2663
+ {issue_cards_html}
2664
+ </div>
2665
+ </section>
2666
+
2667
+ <section class="mt-6 grid gap-4 lg:grid-cols-2">
2668
+ <div class="glass glass-card p-5">
2669
+ <div class="text-sm font-medium text-slate-400">Top Risks</div>
2670
+ <div class="mt-4 space-y-3">
2671
+ {top_risks_html}
2672
+ </div>
2673
+ </div>
2674
+
2675
+ <div class="glass glass-card p-5">
2676
+ <div class="text-sm font-medium text-slate-400">Recommended Refactors</div>
2677
+ <div class="mt-4 space-y-3">
2678
+ {recommendations_html}
2679
+ </div>
2680
+ </div>
2681
+ </section>
2682
+ </main>
2683
+ {issue_card_script()}
2684
+ </body>
2685
+ </html>
2686
+ """
2687
+
2688
+
2689
+ def save_baseline(path: str, select: str = ""):
2690
+ project_path = resolve_repository_path(path)
2691
+ ensure_repository_context(project_path)
2692
+ selected_paths = parse_select_query(select)
2693
+ analysis = analyze_project_architecture(project_path, selected_paths=selected_paths)
2694
+ baseline = analysis.get("architecture")
2695
+ if not baseline:
2696
+ return HTMLResponse("Analysis did not produce an architecture baseline.", status_code=500)
2697
+ save_architecture_baseline(baseline)
2698
+ encoded_path = quote(project_path)
2699
+ extra = "&select={0}".format(quote(select)) if select else ""
2700
+ return RedirectResponse("/dashboard?path={0}{1}".format(encoded_path, extra), status_code=303)
2701
+
2702
+
2703
+ def page_shell(title, encoded_path, repo_context, body, width="max-w-6xl"):
2704
+ return f"""
2705
+ <!doctype html>
2706
+ <html lang="en">
2707
+ <head>
2708
+ <meta charset="utf-8">
2709
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2710
+ <title>{escape(title)}</title>
2711
+ <script src="https://cdn.tailwindcss.com"></script>
2712
+ {liquid_glass_styles()}
2713
+ </head>
2714
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
2715
+ {product_nav(encoded_path, repo_context)}
2716
+ <main class="mx-auto {width} px-6 py-10">
2717
+ {body}
2718
+ </main>
2719
+ {issue_card_script()}
2720
+ </body>
2721
+ </html>
2722
+ """
2723
+
2724
+
2725
+ def status_badge(label, tone):
2726
+ tones = {
2727
+ "pass": "border-emerald-300/30 bg-emerald-950/30 text-emerald-200",
2728
+ "fail": "border-rose-300/30 bg-rose-950/30 text-rose-200",
2729
+ "warn": "border-amber-300/30 bg-amber-950/30 text-amber-200",
2730
+ }
2731
+ return '<span class="rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-wide {0}">{1}</span>'.format(
2732
+ tones.get(tone, tones["warn"]), escape(label)
2733
+ )
2734
+
2735
+
2736
+ def render_review_extras(comparison, notes=None):
2737
+ """Declared rules, accepted exceptions and stale entries: the same
2738
+ information `adre review` and the GitHub check show."""
2739
+ comparison = comparison or {}
2740
+ sections = []
2741
+ rule_lines = []
2742
+ if comparison.get("declared_rules"):
2743
+ rule_lines.append("Declared architecture from <code>.adre/architecture.json</code> is applied.")
2744
+ if comparison.get("rules_only"):
2745
+ rule_lines.append("No saved baseline: checking every current dependency against the declared rules only.")
2746
+ for note in notes or []:
2747
+ rule_lines.append(escape(note))
2748
+ if rule_lines:
2749
+ sections.append(
2750
+ '<div class="glass rounded-xl px-4 py-3 text-sm leading-6 text-slate-300">{0}</div>'.format("<br>".join(rule_lines))
2751
+ )
2752
+ accepted = comparison.get("accepted_drift") or []
2753
+ if accepted:
2754
+ rows = "".join(
2755
+ '<li class="glass rounded-xl px-4 py-3"><div class="font-mono text-xs text-slate-200">{changed}</div>'
2756
+ '<div class="mt-1 text-xs text-slate-400">{kind} · accepted: {reason}</div></li>'.format(
2757
+ changed=escape(item.get("changed") or item.get("file") or ""),
2758
+ kind=escape(item.get("issue_type") or "drift"),
2759
+ reason=escape((item.get("accepted_by") or {}).get("reason") or ""),
2760
+ )
2761
+ for item in accepted
2762
+ )
2763
+ sections.append(
2764
+ '<section class="glass glass-card p-5"><div class="text-sm font-medium text-slate-400">'
2765
+ 'Accepted exceptions ({0})</div><p class="mt-2 text-xs text-slate-500">Matched by entries in '
2766
+ '<code>.adre/accepted.json</code>; they do not fail the review.</p><ul class="mt-4 space-y-2">{1}</ul></section>'.format(len(accepted), rows)
2767
+ )
2768
+ stale = comparison.get("stale_accepted") or []
2769
+ if stale:
2770
+ rows = "".join(
2771
+ '<li class="glass rounded-xl px-4 py-3"><div class="font-mono text-xs text-slate-200">entry {index}: {source} → {target}</div>'
2772
+ '<div class="mt-1 text-xs text-slate-400">{reason}</div></li>'.format(
2773
+ index=escape(str(rule.get("index"))),
2774
+ source=escape(rule.get("from") or ""),
2775
+ target=escape(rule.get("to") or ""),
2776
+ reason=escape(rule.get("reason") or ""),
2777
+ )
2778
+ for rule in stale
2779
+ )
2780
+ consequence = "They fail the review because <code>fail_on_stale</code> is on." if comparison.get("fail_on_stale") else "Remove them so they cannot hide a future regression."
2781
+ sections.append(
2782
+ '<section class="glass glass-card p-5"><div class="text-sm font-medium text-amber-200">'
2783
+ 'Stale accepted exceptions ({0})</div><p class="mt-2 text-xs text-slate-400">These entries no longer match any dependency. {1}</p>'
2784
+ '<ul class="mt-4 space-y-2">{2}</ul></section>'.format(len(stale), consequence, rows)
2785
+ )
2786
+ return "\n".join(sections)
2787
+
2788
+
2789
+ @app.get("/review", response_class=HTMLResponse)
2790
+ def review_against_baseline(path: str, select: str = ""):
2791
+ project_path = resolve_repository_path(path)
2792
+ repo_context = ensure_repository_context(project_path)
2793
+ encoded_path = quote(project_path)
2794
+ extra = "&select={0}".format(quote(select)) if select else ""
2795
+ save_button = post_button(
2796
+ "/save-baseline",
2797
+ {"path": project_path, "select": select or None},
2798
+ "Save baseline",
2799
+ "glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200",
2800
+ confirm="Save the current architecture as the accepted baseline (.adre/baseline.json)?",
2801
+ )
2802
+ result = review_working_tree(project_path, selected_paths=parse_select_query(select))
2803
+
2804
+ if result["status"] == "no_baseline":
2805
+ body = f"""
2806
+ <h1 class="text-3xl font-semibold text-white">No baseline saved</h1>
2807
+ <p class="mt-4 text-sm leading-6 text-slate-400">
2808
+ Save an architecture baseline before reviewing this repository against it,
2809
+ or declare the intended architecture in <code>.adre/architecture.json</code>.
2810
+ </p>
2811
+ <div class="mt-6 flex flex-wrap gap-3">
2812
+ {save_button}
2813
+ <a href="/dashboard?path={encoded_path}{extra}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">Back to dashboard</a>
2814
+ </div>
2815
+ """
2816
+ return HTMLResponse(page_shell("Architecture Review", encoded_path, repo_context, body, width="max-w-3xl"), status_code=404)
2817
+ if result["status"] != "ok":
2818
+ body = f"""
2819
+ <h1 class="text-3xl font-semibold text-white">Review could not run</h1>
2820
+ <p class="mt-4 text-sm leading-6 text-rose-200">{escape(result["error"])}</p>
2821
+ <div class="mt-6 flex flex-wrap gap-3">
2822
+ <a href="/dashboard?path={encoded_path}{extra}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">Back to dashboard</a>
2823
+ </div>
2824
+ """
2825
+ return HTMLResponse(page_shell("Architecture Review", encoded_path, repo_context, body, width="max-w-3xl"), status_code=400)
2826
+
2827
+ comparison = result["comparison"]
2828
+ analysis = result["analysis"]
2829
+ drift = comparison.get("drift") or []
2830
+ stale_fails = bool(comparison.get("stale_accepted")) and comparison.get("fail_on_stale")
2831
+ if drift:
2832
+ verdict = "{0} architectural drift finding(s) versus the saved baseline.".format(len(drift))
2833
+ badge = status_badge("Drift", "fail")
2834
+ elif stale_fails:
2835
+ verdict = "No drift, but stale accepted exceptions fail the review."
2836
+ badge = status_badge("Stale exceptions", "warn")
2837
+ else:
2838
+ verdict = "No architectural drift versus the saved baseline."
2839
+ badge = status_badge("Pass", "pass")
2840
+ issue_cards_html = render_issue_cards(project_path, drift)
2841
+ architecture_html = render_architecture_panel(
2842
+ analysis.get("architecture"),
2843
+ encoded_path,
2844
+ select_value=select,
2845
+ baseline_saved=not comparison.get("rules_only"),
2846
+ saved_summary=comparison.get("baseline_summary_path") or "",
2847
+ )
2848
+ summary_line = comparison.get("summary") or ""
2849
+ summary_html = (
2850
+ '<p class="mt-2 max-w-3xl text-sm leading-6 text-slate-400">{0}</p>'.format(escape(summary_line))
2851
+ if summary_line and summary_line != verdict
2852
+ else ""
2853
+ )
2854
+ body = f"""
2855
+ <header class="mb-8">
2856
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">ADRE</p>
2857
+ <div class="flex flex-wrap items-center gap-3">
2858
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Review</h1>
2859
+ {badge}
2860
+ </div>
2861
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
2862
+ <p class="mt-4 max-w-3xl text-sm leading-6 text-slate-300">{escape(verdict)}</p>
2863
+ {summary_html}
2864
+ <p class="mt-2 text-xs text-slate-500">
2865
+ What architecture exists: {escape(comparison.get("baseline_summary_path") or "insufficient structure")}
2866
+ · What the current tree looks like: {escape(comparison.get("current_summary_path") or "insufficient structure")}
2867
+ </p>
2868
+ <p class="mt-2 text-xs text-slate-500">
2869
+ Same result as <code>adre review</code>: the accepted ArchitectureBaseline, declared rules and accepted exceptions.
2870
+ It does not enforce MVC, Clean Architecture, or any other preferred style.
2871
+ </p>
2872
+ <div class="mt-5 flex flex-wrap gap-3">
2873
+ <a href="/dashboard?path={encoded_path}{extra}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">Back to dashboard</a>
2874
+ <a href="/review-branch?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">Review a branch</a>
2875
+ {save_button.replace(">Save baseline<", ">Update baseline<")}
2876
+ </div>
2877
+ </header>
2878
+ {architecture_html}
2879
+ <section class="glass glass-card p-5">
2880
+ <div class="text-sm font-medium text-slate-400">Drift findings</div>
2881
+ <div class="mt-5 space-y-4">
2882
+ {issue_cards_html}
2883
+ </div>
2884
+ </section>
2885
+ <div class="mt-6 space-y-6">{render_review_extras(comparison)}</div>
2886
+ """
2887
+ return page_shell("Architecture Review", encoded_path, repo_context, body)
2888
+
2889
+
2890
+ def suggested_base_ref(project_path):
2891
+ """origin's default branch if known, else main or master."""
2892
+ try:
2893
+ head = run_git(project_path, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
2894
+ if head:
2895
+ return head
2896
+ except (OSError, subprocess.CalledProcessError):
2897
+ pass
2898
+ for candidate in ("origin/main", "main", "origin/master", "master"):
2899
+ try:
2900
+ run_git(project_path, ["rev-parse", "--verify", "--quiet", candidate + "^{commit}"])
2901
+ return candidate
2902
+ except (OSError, subprocess.CalledProcessError):
2903
+ continue
2904
+ return "main"
2905
+
2906
+
2907
+ @app.get("/review-branch", response_class=HTMLResponse)
2908
+ def review_branch(path: str, base: str = ""):
2909
+ """The pull-request review the GitHub Action runs, for the checked-out branch."""
2910
+ project_path = resolve_repository_path(path)
2911
+ repo_context = ensure_repository_context(project_path)
2912
+ encoded_path = quote(project_path)
2913
+ base = (base or "").strip()
2914
+ suggested = base or suggested_base_ref(project_path)
2915
+ form = f"""
2916
+ <form action="/review-branch" method="get" class="mt-5 flex flex-wrap items-end gap-3">
2917
+ <input type="hidden" name="path" value="{escape(project_path, quote=True)}">
2918
+ <label class="text-sm text-slate-300">
2919
+ <span class="block text-xs uppercase tracking-wide text-slate-500">Base branch or commit</span>
2920
+ <input name="base" value="{escape(suggested, quote=True)}" class="glass mt-1 rounded-xl px-4 py-3 font-mono text-sm text-slate-100" />
2921
+ </label>
2922
+ <button type="submit" class="glass-btn source-btn rounded-xl px-5 py-3 text-sm font-semibold">Review current branch</button>
2923
+ </form>
2924
+ """
2925
+ header = f"""
2926
+ <header class="mb-8">
2927
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">ADRE</p>
2928
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Review a branch</h1>
2929
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
2930
+ <p class="mt-4 max-w-3xl text-sm leading-6 text-slate-300">
2931
+ Compares the checked-out branch (HEAD) with a base branch, exactly like the pull-request check:
2932
+ only drift that this branch adds is reported, renamed files are matched, and the baseline and
2933
+ declared rules come from the base commit.
2934
+ </p>
2935
+ {form}
2936
+ </header>
2937
+ """
2938
+ if not base:
2939
+ return page_shell("Review a branch", encoded_path, repo_context, header, width="max-w-5xl")
2940
+
2941
+ result = review_pull_request(project_path, base, "HEAD")
2942
+ status = result.get("status") or "ERROR"
2943
+ tone = {"PASS": "pass", "DRIFT": "fail"}.get(status, "warn")
2944
+ drift = result.get("drift") or []
2945
+ notes = []
2946
+ if result.get("comparison_mode") == "baseline_snapshot":
2947
+ notes.append("The base tree could not be analyzed, so the saved baseline's edges were used: {0}".format(result.get("base_analysis_error") or ""))
2948
+ if result.get("renamed_files"):
2949
+ notes.append("{0} renamed file(s) were matched to their old paths.".format(len(result["renamed_files"])))
2950
+ if result.get("working_tree_dirty"):
2951
+ notes.append("The working tree has uncommitted changes; they are included in this review.")
2952
+ if result.get("declared_file_changed"):
2953
+ notes.append("This branch changes .adre/architecture.json; declared rules come from the base, so the change applies after merge.")
2954
+ if result.get("accepted_file_changed"):
2955
+ notes.append("This branch changes .adre/accepted.json; check the accepted exceptions below.")
2956
+ details = "Base {0} · HEAD {1} · {2} changed file(s)".format(
2957
+ (result.get("base_sha") or base)[:12], (result.get("head_sha") or "HEAD")[:12], len(result.get("changed_files") or [])
2958
+ )
2959
+ body = header + f"""
2960
+ <section class="glass glass-card mb-6 p-5">
2961
+ <div class="flex flex-wrap items-center gap-3">
2962
+ {status_badge(status.replace("_", " "), tone)}
2963
+ <span class="text-sm text-slate-300">{escape(result.get("summary") or "")}</span>
2964
+ </div>
2965
+ <p class="mt-3 font-mono text-xs text-slate-500">{escape(details)}</p>
2966
+ </section>
2967
+ <section class="glass glass-card p-5">
2968
+ <div class="text-sm font-medium text-slate-400">New drift on this branch</div>
2969
+ <div class="mt-5 space-y-4">
2970
+ {render_issue_cards(project_path, drift) if drift else '<div class="text-sm text-slate-500">No new drift.</div>'}
2971
+ </div>
2972
+ </section>
2973
+ <div class="mt-6 space-y-6">{render_review_extras(result, notes)}</div>
2974
+ """
2975
+ return page_shell("Review a branch", encoded_path, repo_context, body, width="max-w-5xl")
2976
+
2977
+
2978
+ @app.get("/evolution", response_class=HTMLResponse)
2979
+ def evolution(path: str):
2980
+ project_path = resolve_repository_path(path)
2981
+ repo_context = ensure_repository_context(project_path)
2982
+ encoded_path = quote(project_path)
2983
+
2984
+ try:
2985
+ snapshots = extract_git_snapshots(project_path)
2986
+ evolution_report = analyze_architecture_evolution(snapshots)
2987
+ except Exception as exc:
2988
+ safe_error = escape(str(exc))
2989
+ return f"""
2990
+ <!doctype html>
2991
+ <html lang="en">
2992
+ <head>
2993
+ <meta charset="utf-8">
2994
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2995
+ <title>Architecture Evolution</title>
2996
+ <script src="https://cdn.tailwindcss.com"></script>
2997
+ {liquid_glass_styles()}
2998
+ </head>
2999
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
3000
+ {product_nav(encoded_path, repo_context)}
3001
+ <main class="mx-auto max-w-6xl px-6 py-10">
3002
+ <section class="glass glass-card p-6">
3003
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Architecture Evolution</p>
3004
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">Git history unavailable</h1>
3005
+ <p class="mt-4 text-sm leading-6 text-slate-400">
3006
+ Evolution intelligence requires a git repository with commit history.
3007
+ </p>
3008
+ <div class="mt-4 glass rounded-xl px-4 py-3 text-sm text-slate-300">{safe_error}</div>
3009
+ </section>
3010
+ </main>
3011
+ </body>
3012
+ </html>
3013
+ """
3014
+
3015
+ timeline = evolution_report.get("architecture_timeline", [])
3016
+ drift_events = evolution_report.get("drift_events", [])[:10]
3017
+ repeat_offenders = evolution_report.get("repeat_offenders", [])[:10]
3018
+ subsystem_health = evolution_report.get("subsystem_health", {})
3019
+ root_causes = evolution_report.get("root_causes", [])
3020
+
3021
+ if timeline:
3022
+ first_score = timeline[0]["architecture_score"]
3023
+ last_score = timeline[-1]["architecture_score"]
3024
+ score_delta = last_score - first_score
3025
+ else:
3026
+ first_score = 0
3027
+ last_score = 0
3028
+ score_delta = 0
3029
+
3030
+ timeline_html = "\n".join(
3031
+ f"""
3032
+ <div class="glass rounded-xl px-4 py-3">
3033
+ <div class="flex items-center justify-between gap-4">
3034
+ <div>
3035
+ <div class="font-semibold text-slate-100">{escape((item.get("commit") or "unknown")[:12])}</div>
3036
+ <div class="mt-1 text-xs text-slate-500">{escape(str(item.get("timestamp") or ""))}</div>
3037
+ </div>
3038
+ <div class="text-right">
3039
+ <div class="font-semibold text-white">{item["architecture_score"]}/100</div>
3040
+ <div class="mt-1 text-xs text-slate-500">
3041
+ {item["issue_count"]} issues · {item["cycle_count"]} cycles · {item["hotspot_count"]} hotspots
3042
+ </div>
3043
+ </div>
3044
+ </div>
3045
+ </div>
3046
+ """
3047
+ for item in timeline[-8:]
3048
+ ) or '<div class="text-sm text-slate-500">No git architecture timeline available.</div>'
3049
+
3050
+ drift_events_html = "\n".join(
3051
+ f"""
3052
+ <div class="glass rounded-xl px-4 py-3">
3053
+ <div class="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
3054
+ <div>
3055
+ <div class="font-semibold text-slate-100">{escape(event["event"].title())}</div>
3056
+ <div class="mt-1 text-sm text-slate-500">{escape(event.get("details", ""))}</div>
3057
+ </div>
3058
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">
3059
+ {escape(event["severity"])} · {escape((event.get("commit") or "unknown")[:12])}
3060
+ </div>
3061
+ </div>
3062
+ </div>
3063
+ """
3064
+ for event in drift_events
3065
+ ) or '<div class="text-sm text-slate-500">No major drift events detected.</div>'
3066
+
3067
+ offenders_html = "\n".join(
3068
+ f"""
3069
+ <div class="glass rounded-xl px-4 py-3">
3070
+ <div class="flex items-start justify-between gap-4">
3071
+ <div>
3072
+ <div class="break-all font-semibold text-slate-100">{escape(item["file"])}</div>
3073
+ <div class="mt-1 text-xs text-slate-500">{escape(", ".join(item.get("reasons", [])))}</div>
3074
+ </div>
3075
+ <div class="text-lg font-semibold text-white">{item["offender_score"]}</div>
3076
+ </div>
3077
+ </div>
3078
+ """
3079
+ for item in repeat_offenders
3080
+ ) or '<div class="text-sm text-slate-500">No repeat architecture offenders detected.</div>'
3081
+
3082
+ subsystem_html = "\n".join(
3083
+ f"""
3084
+ <div class="glass rounded-xl px-4 py-3">
3085
+ <div class="flex items-start justify-between gap-4">
3086
+ <div>
3087
+ <div class="font-semibold text-slate-100">{escape(subsystem)}</div>
3088
+ <div class="mt-1 text-xs text-slate-500">
3089
+ issues {data["issue_growth"]:+} · dependencies {data["dependency_growth"]:+} · cycles {data["cycle_involvement"]}
3090
+ </div>
3091
+ </div>
3092
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">{escape(data["trend"])}</div>
3093
+ </div>
3094
+ </div>
3095
+ """
3096
+ for subsystem, data in sorted(
3097
+ subsystem_health.items(),
3098
+ key=lambda item: (-item[1].get("risk_delta", 0), item[0]),
3099
+ )[:8]
3100
+ ) or '<div class="text-sm text-slate-500">No subsystem health data available.</div>'
3101
+
3102
+ root_causes_html = "\n".join(
3103
+ f'<div class="glass rounded-xl px-4 py-3 text-sm leading-6 text-slate-300">{escape(insight)}</div>'
3104
+ for insight in root_causes
3105
+ ) or '<div class="text-sm text-slate-500">No root cause signal detected.</div>'
3106
+
3107
+ return f"""
3108
+ <!doctype html>
3109
+ <html lang="en">
3110
+ <head>
3111
+ <meta charset="utf-8">
3112
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3113
+ <title>Architecture Evolution</title>
3114
+ <script src="https://cdn.tailwindcss.com"></script>
3115
+ {liquid_glass_styles()}
3116
+ </head>
3117
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
3118
+ {product_nav(encoded_path, repo_context)}
3119
+ <main class="mx-auto max-w-6xl px-6 py-10">
3120
+ <header class="mb-8">
3121
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">Architecture observability</p>
3122
+ <div class="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
3123
+ <div>
3124
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Evolution</h1>
3125
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
3126
+ </div>
3127
+ <a href="/dashboard?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
3128
+ Current dashboard
3129
+ </a>
3130
+ </div>
3131
+ </header>
3132
+
3133
+ <section class="grid gap-4 md:grid-cols-3">
3134
+ <div class="glass glass-card p-5">
3135
+ <div class="text-sm font-medium text-slate-400">Trend</div>
3136
+ <div class="mt-3 text-3xl font-semibold text-white">{escape(evolution_report["trend"])}</div>
3137
+ <p class="mt-3 text-sm text-slate-500">Architecture score changed {score_delta:+} points across analyzed history.</p>
3138
+ </div>
3139
+ <div class="glass glass-card p-5">
3140
+ <div class="text-sm font-medium text-slate-400">Stability Score</div>
3141
+ <div class="mt-3 text-3xl font-semibold text-white">{evolution_report["stability_score"]}/100</div>
3142
+ <p class="mt-3 text-sm text-slate-500">Higher stability means fewer large architectural swings between commits.</p>
3143
+ </div>
3144
+ <div class="glass glass-card p-5">
3145
+ <div class="text-sm font-medium text-slate-400">Score Range</div>
3146
+ <div class="mt-3 text-3xl font-semibold text-white">{first_score} → {last_score}</div>
3147
+ <p class="mt-3 text-sm text-slate-500">{len(timeline)} commits analyzed.</p>
3148
+ </div>
3149
+ </section>
3150
+
3151
+ <section class="mt-6 grid gap-4 lg:grid-cols-2">
3152
+ <div class="glass glass-card p-5">
3153
+ <div class="text-sm font-medium text-slate-400">Score Trend</div>
3154
+ <div class="mt-4 space-y-3">{timeline_html}</div>
3155
+ </div>
3156
+ <div class="glass glass-card p-5">
3157
+ <div class="text-sm font-medium text-slate-400">Drift Events</div>
3158
+ <div class="mt-4 space-y-3">{drift_events_html}</div>
3159
+ </div>
3160
+ <div class="glass glass-card p-5">
3161
+ <div class="text-sm font-medium text-slate-400">Repeat Offenders</div>
3162
+ <div class="mt-4 space-y-3">{offenders_html}</div>
3163
+ </div>
3164
+ <div class="glass glass-card p-5">
3165
+ <div class="text-sm font-medium text-slate-400">Subsystem Health</div>
3166
+ <div class="mt-4 space-y-3">{subsystem_html}</div>
3167
+ </div>
3168
+ </section>
3169
+
3170
+ <section class="glass glass-card mt-6 p-5">
3171
+ <div class="text-sm font-medium text-slate-400">Root Cause Signals</div>
3172
+ <div class="mt-4 grid gap-3 md:grid-cols-2">{root_causes_html}</div>
3173
+ </section>
3174
+ </main>
3175
+ </body>
3176
+ </html>
3177
+ """
3178
+
3179
+
3180
+ @app.get("/stability", response_class=HTMLResponse)
3181
+ def stability(path: str):
3182
+ project_path = resolve_repository_path(path)
3183
+ repo_context = ensure_repository_context(project_path)
3184
+ encoded_path = quote(project_path)
3185
+
3186
+ try:
3187
+ stability_report = analyze_architecture_stability(project_path)
3188
+ except Exception as exc:
3189
+ safe_error = escape(str(exc))
3190
+ return f"""
3191
+ <!doctype html>
3192
+ <html lang="en">
3193
+ <head>
3194
+ <meta charset="utf-8">
3195
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3196
+ <title>Architecture Stability</title>
3197
+ <script src="https://cdn.tailwindcss.com"></script>
3198
+ {liquid_glass_styles()}
3199
+ </head>
3200
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
3201
+ {product_nav(encoded_path, repo_context)}
3202
+ <main class="mx-auto max-w-6xl px-6 py-10">
3203
+ <section class="glass glass-card p-6">
3204
+ <p class="text-sm font-medium uppercase tracking-wide text-white/60">Architecture Stability</p>
3205
+ <h1 class="mt-2 text-3xl font-semibold tracking-tight text-white">Git history unavailable</h1>
3206
+ <p class="mt-4 text-sm leading-6 text-slate-400">
3207
+ Stability intelligence requires a git repository with commit history.
3208
+ </p>
3209
+ <div class="mt-4 glass rounded-xl px-4 py-3 text-sm text-slate-300">{safe_error}</div>
3210
+ </section>
3211
+ </main>
3212
+ </body>
3213
+ </html>
3214
+ """
3215
+
3216
+ volatile_files = stability_report.get("volatile_files", [])[:10]
3217
+ fragile_subsystems = stability_report.get("fragile_subsystems", [])[:8]
3218
+ blast_radius = stability_report.get("blast_radius_ranking", [])[:10]
3219
+ governance_insights = stability_report.get("governance_insights", [])
3220
+
3221
+ volatile_html = "\n".join(
3222
+ f"""
3223
+ <div class="glass rounded-xl px-4 py-3">
3224
+ <div class="flex items-start justify-between gap-4">
3225
+ <div>
3226
+ <div class="break-all font-semibold text-slate-100">{escape(item["file"])}</div>
3227
+ <div class="mt-1 text-xs text-slate-500">{escape(", ".join(item.get("reasons", [])))}</div>
3228
+ </div>
3229
+ <div class="text-lg font-semibold text-white">{item["volatility_score"]}</div>
3230
+ </div>
3231
+ </div>
3232
+ """
3233
+ for item in volatile_files
3234
+ ) or '<div class="text-sm text-slate-500">No volatile architecture files detected.</div>'
3235
+
3236
+ fragile_html = "\n".join(
3237
+ f"""
3238
+ <div class="glass rounded-xl px-4 py-3">
3239
+ <div class="flex items-start justify-between gap-4">
3240
+ <div>
3241
+ <div class="font-semibold text-slate-100">{escape(item["subsystem"])}</div>
3242
+ <div class="mt-1 text-xs text-slate-500">
3243
+ issues {item["issue_density"]} · regressions {item["regression_frequency"]} · dependencies +{item["dependency_growth"]}
3244
+ </div>
3245
+ </div>
3246
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">
3247
+ {escape(item["trend"])} · {item["fragility_score"]}
3248
+ </div>
3249
+ </div>
3250
+ </div>
3251
+ """
3252
+ for item in fragile_subsystems
3253
+ ) or '<div class="text-sm text-slate-500">No fragile subsystem concentration detected.</div>'
3254
+
3255
+ blast_html = "\n".join(
3256
+ f"""
3257
+ <div class="glass rounded-xl px-4 py-3">
3258
+ <div class="flex items-start justify-between gap-4">
3259
+ <div>
3260
+ <div class="break-all font-semibold text-slate-100">{escape(item["file"])}</div>
3261
+ <div class="mt-1 text-xs text-slate-500">
3262
+ inbound {item["inbound_dependencies"]} · transitive {item["transitive_dependents"]} · hotspot {str(item["hotspot"]).lower()}
3263
+ </div>
3264
+ </div>
3265
+ <div class="glass-btn rounded-xl px-3 py-2 text-xs font-medium text-slate-200">
3266
+ {escape(item["blast_radius"])} · {item["blast_radius_score"]}
3267
+ </div>
3268
+ </div>
3269
+ </div>
3270
+ """
3271
+ for item in blast_radius
3272
+ ) or '<div class="text-sm text-slate-500">No blast radius data available.</div>'
3273
+
3274
+ insights_html = "\n".join(
3275
+ f'<div class="glass rounded-xl px-4 py-3 text-sm leading-6 text-slate-300">{escape(insight)}</div>'
3276
+ for insight in governance_insights
3277
+ ) or '<div class="text-sm text-slate-500">No governance insight detected.</div>'
3278
+
3279
+ return f"""
3280
+ <!doctype html>
3281
+ <html lang="en">
3282
+ <head>
3283
+ <meta charset="utf-8">
3284
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3285
+ <title>Architecture Stability</title>
3286
+ <script src="https://cdn.tailwindcss.com"></script>
3287
+ {liquid_glass_styles()}
3288
+ </head>
3289
+ <body class="app-bg min-h-screen text-slate-100 antialiased">
3290
+ {product_nav(encoded_path, repo_context)}
3291
+ <main class="mx-auto max-w-6xl px-6 py-10">
3292
+ <header class="mb-8">
3293
+ <p class="mb-2 text-sm font-medium uppercase tracking-wide text-white/60">Architecture governance</p>
3294
+ <div class="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
3295
+ <div>
3296
+ <h1 class="text-3xl font-semibold tracking-tight text-white md:text-4xl">Architecture Stability</h1>
3297
+ <p class="mt-3 break-all text-sm text-slate-400">{escape(project_path)}</p>
3298
+ </div>
3299
+ <a href="/evolution?path={encoded_path}" class="glass-btn rounded-xl px-4 py-3 text-sm font-medium text-slate-200">
3300
+ View evolution
3301
+ </a>
3302
+ </div>
3303
+ </header>
3304
+
3305
+ <section class="grid gap-4 md:grid-cols-3">
3306
+ <div class="glass glass-card p-5">
3307
+ <div class="text-sm font-medium text-slate-400">Stability Score</div>
3308
+ <div class="mt-3 text-3xl font-semibold text-white">{stability_report["stability_score"]}/100</div>
3309
+ <p class="mt-3 text-sm text-slate-500">Higher means fewer recurring architectural instability signals.</p>
3310
+ </div>
3311
+ <div class="glass glass-card p-5">
3312
+ <div class="text-sm font-medium text-slate-400">Volatile Files</div>
3313
+ <div class="mt-3 text-3xl font-semibold text-white">{len(stability_report.get("volatile_files", []))}</div>
3314
+ <p class="mt-3 text-sm text-slate-500">Files repeatedly involved in cycles, violations, hotspots, or drift.</p>
3315
+ </div>
3316
+ <div class="glass glass-card p-5">
3317
+ <div class="text-sm font-medium text-slate-400">Commits Analyzed</div>
3318
+ <div class="mt-3 text-3xl font-semibold text-white">{stability_report.get("commit_count", 0)}</div>
3319
+ <p class="mt-3 text-sm text-slate-500">Git history used for governance signals.</p>
3320
+ </div>
3321
+ </section>
3322
+
3323
+ <section class="mt-6 grid gap-4 lg:grid-cols-2">
3324
+ <div class="glass glass-card p-5">
3325
+ <div class="text-sm font-medium text-slate-400">Volatile Files</div>
3326
+ <div class="mt-4 space-y-3">{volatile_html}</div>
3327
+ </div>
3328
+ <div class="glass glass-card p-5">
3329
+ <div class="text-sm font-medium text-slate-400">Fragile Subsystems</div>
3330
+ <div class="mt-4 space-y-3">{fragile_html}</div>
3331
+ </div>
3332
+ <div class="glass glass-card p-5">
3333
+ <div class="text-sm font-medium text-slate-400">Largest Blast Radius</div>
3334
+ <div class="mt-4 space-y-3">{blast_html}</div>
3335
+ </div>
3336
+ <div class="glass glass-card p-5">
3337
+ <div class="text-sm font-medium text-slate-400">Governance Insights</div>
3338
+ <div class="mt-4 space-y-3">{insights_html}</div>
3339
+ </div>
3340
+ </section>
3341
+ </main>
3342
+ </body>
3343
+ </html>
3344
+ """
3345
+
3346
+
3347
+ @app.get("/graph", response_class=HTMLResponse)
3348
+ def graph(path: str, select: str = ""):
3349
+ project_path = resolve_repository_path(path)
3350
+ repo_context = ensure_repository_context(project_path)
3351
+ analysis = analyze_project_architecture(project_path, selected_paths=parse_select_query(select))
3352
+ dependency_graph = analysis.get("dependency_graph", {})
3353
+ resolved_graph = analysis.get("resolved_graph", {})
3354
+ hotspot_nodes = {item.get("file") for item in analysis.get("hotspot_files", [])}
3355
+ cycle_edges = set()
3356
+ encoded_path = quote(project_path)
3357
+
3358
+ for cycle in analysis.get("cycles", []):
3359
+ for source, target in zip(cycle, cycle[1:]):
3360
+ cycle_edges.add((source, target))
3361
+
3362
+ elements = []
3363
+ node_ids = set()
3364
+
3365
+ for file_path in sorted(dependency_graph):
3366
+ label = os.path.basename(file_path) or file_path
3367
+ classes = []
3368
+
3369
+ if file_path in hotspot_nodes:
3370
+ classes.append("hotspot")
3371
+
3372
+ node_ids.add(file_path)
3373
+ elements.append({
3374
+ "data": {
3375
+ "id": file_path,
3376
+ "label": label,
3377
+ "fullLabel": file_path,
3378
+ },
3379
+ "classes": " ".join(classes),
3380
+ })
3381
+
3382
+ edge_count = 0
3383
+
3384
+ for source, targets in sorted(resolved_graph.items()):
3385
+ for target in sorted(targets):
3386
+ if source not in dependency_graph or target not in dependency_graph:
3387
+ continue
3388
+
3389
+ edge_count += 1
3390
+ elements.append({
3391
+ "data": {
3392
+ "id": f"edge-{edge_count}",
3393
+ "source": source,
3394
+ "target": target,
3395
+ },
3396
+ "classes": "cycle-edge" if (source, target) in cycle_edges else "normal-edge",
3397
+ })
3398
+
3399
+ if edge_count == 0:
3400
+ for source, data in sorted(dependency_graph.items()):
3401
+ for imported in sorted(data.get("imports", [])):
3402
+ external_id = f"external::{imported}"
3403
+
3404
+ if external_id not in node_ids:
3405
+ node_ids.add(external_id)
3406
+ elements.append({
3407
+ "data": {
3408
+ "id": external_id,
3409
+ "label": imported.split(".")[-1],
3410
+ "fullLabel": imported,
3411
+ },
3412
+ "classes": "external",
3413
+ })
3414
+
3415
+ edge_count += 1
3416
+ elements.append({
3417
+ "data": {
3418
+ "id": f"edge-{edge_count}",
3419
+ "source": source,
3420
+ "target": external_id,
3421
+ },
3422
+ "classes": "normal-edge",
3423
+ })
3424
+
3425
+ graph_data = json.dumps(elements).replace("</", "<\\/")
3426
+
3427
+ return f"""
3428
+ <!doctype html>
3429
+ <html lang="en">
3430
+ <head>
3431
+ <meta charset="utf-8">
3432
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3433
+ <title>ADRE Dependency Graph</title>
3434
+ <script src="https://cdn.tailwindcss.com"></script>
3435
+ <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
3436
+ {liquid_glass_styles()}
3437
+ </head>
3438
+ <body class="app-bg h-screen overflow-hidden text-slate-100 antialiased">
3439
+ <main class="flex h-screen flex-col">
3440
+ {product_nav(encoded_path, repo_context)}
3441
+ <header class="glass-nav px-6 py-4">
3442
+ <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
3443
+ <div>
3444
+ <p class="text-xs font-medium uppercase tracking-wide text-white/60">ADRE</p>
3445
+ <h1 class="mt-1 text-2xl font-semibold tracking-tight text-white">Interactive Dependency Graph</h1>
3446
+ <p class="mt-1 break-all text-sm text-slate-400">{escape(project_path)}</p>
3447
+ <p class="mt-1 text-xs text-slate-500">{escape(repo_context.get("name", "Repository"))} · {escape(repo_context.get("source_type", "local"))}</p>
3448
+ </div>
3449
+ <div class="flex flex-wrap items-center gap-3">
3450
+ <div class="glass rounded-xl px-4 py-2 text-sm text-slate-300">
3451
+ <span class="text-slate-500">Files</span>
3452
+ <span class="ml-2 font-semibold text-white">{len(dependency_graph)}</span>
3453
+ </div>
3454
+ <div class="glass rounded-xl px-4 py-2 text-sm text-slate-300">
3455
+ <span class="text-slate-500">Edges</span>
3456
+ <span class="ml-2 font-semibold text-white">{edge_count}</span>
3457
+ </div>
3458
+ <div class="glass rounded-xl px-4 py-2 text-sm text-slate-300">
3459
+ <span class="text-slate-500">Cycles</span>
3460
+ <span class="ml-2 font-semibold text-amber-200">{len(analysis.get("cycles", []))}</span>
3461
+ </div>
3462
+ <a href="/dashboard?path={encoded_path}" class="glass-btn rounded-xl px-4 py-2 text-sm font-medium text-slate-200">
3463
+ Dashboard
3464
+ </a>
3465
+ </div>
3466
+ </div>
3467
+ </header>
3468
+
3469
+ <section class="canvas-bg relative min-h-0 flex-1">
3470
+ <div id="cy" class="absolute inset-0"></div>
3471
+ <div id="tooltip" class="glass pointer-events-none fixed z-20 hidden max-w-sm rounded-xl px-3 py-2 text-xs text-slate-200"></div>
3472
+
3473
+ <div class="glass absolute left-5 top-5 z-10 rounded-xl p-4">
3474
+ <div class="mb-3 text-sm font-semibold text-white">Controls</div>
3475
+ <div class="flex gap-2">
3476
+ <button id="zoom-in" class="glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-200">Zoom +</button>
3477
+ <button id="zoom-out" class="glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-200">Zoom -</button>
3478
+ <button id="fit" class="glass-btn rounded-xl px-3 py-2 text-sm font-medium text-slate-200">Fit</button>
3479
+ </div>
3480
+ <div class="mt-4 space-y-2 text-xs text-slate-400">
3481
+ <div><span class="mr-2 inline-block h-2 w-2 rounded-full bg-amber-500"></span>Hotspot file</div>
3482
+ <div><span class="mr-2 inline-block h-2 w-5 rounded-full bg-amber-400"></span>Cycle edge</div>
3483
+ <div><span class="mr-2 inline-block h-2 w-2 rounded-full bg-slate-400"></span>Normal file</div>
3484
+ </div>
3485
+ </div>
3486
+
3487
+ <div class="glass absolute bottom-5 right-5 z-10 rounded-xl px-4 py-3 text-xs text-slate-400">
3488
+ Click a node to highlight its dependency neighborhood. Drag to pan. Scroll to zoom.
3489
+ </div>
3490
+ </section>
3491
+ </main>
3492
+ <script>
3493
+ const elements = {graph_data};
3494
+ const cy = cytoscape({{
3495
+ container: document.getElementById('cy'),
3496
+ elements,
3497
+ wheelSensitivity: 0.18,
3498
+ minZoom: 0.15,
3499
+ maxZoom: 2.6,
3500
+ style: [
3501
+ {{
3502
+ selector: 'node',
3503
+ style: {{
3504
+ 'background-color': 'rgba(255,255,255,0.16)',
3505
+ 'shape': 'ellipse',
3506
+ 'border-width': 1,
3507
+ 'border-color': 'rgba(255,255,255,0.22)',
3508
+ 'color': 'rgba(255,255,255,0.82)',
3509
+ 'font-size': 11,
3510
+ 'label': 'data(label)',
3511
+ 'text-valign': 'bottom',
3512
+ 'text-halign': 'center',
3513
+ 'text-margin-y': 8,
3514
+ 'width': 34,
3515
+ 'height': 34,
3516
+ 'underlay-opacity': 0,
3517
+ 'underlay-padding': 0,
3518
+ 'overlay-opacity': 0,
3519
+ 'transition-property': 'opacity, border-color, border-width, background-color, line-color, target-arrow-color',
3520
+ 'transition-duration': 180
3521
+ }}
3522
+ }},
3523
+ {{
3524
+ selector: 'node.hotspot',
3525
+ style: {{
3526
+ 'background-color': 'rgba(217,119,6,0.55)',
3527
+ 'border-color': 'rgba(251,191,36,0.70)'
3528
+ }}
3529
+ }},
3530
+ {{
3531
+ selector: 'node.external',
3532
+ style: {{
3533
+ 'background-color': 'rgba(255,255,255,0.10)',
3534
+ 'border-color': 'rgba(255,255,255,0.18)',
3535
+ 'shape': 'round-rectangle',
3536
+ 'width': 28,
3537
+ 'height': 28
3538
+ }}
3539
+ }},
3540
+ {{
3541
+ selector: 'edge',
3542
+ style: {{
3543
+ 'width': 2,
3544
+ 'line-color': 'rgba(255,255,255,0.24)',
3545
+ 'target-arrow-color': 'rgba(255,255,255,0.24)',
3546
+ 'target-arrow-shape': 'triangle',
3547
+ 'curve-style': 'bezier',
3548
+ 'arrow-scale': 1,
3549
+ 'opacity': 0.72,
3550
+ 'transition-property': 'opacity, line-color, target-arrow-color, width',
3551
+ 'transition-duration': 180
3552
+ }}
3553
+ }},
3554
+ {{
3555
+ selector: 'edge.cycle-edge',
3556
+ style: {{
3557
+ 'line-color': 'rgba(217,119,6,0.78)',
3558
+ 'target-arrow-color': 'rgba(217,119,6,0.78)',
3559
+ 'width': 3,
3560
+ 'opacity': 1
3561
+ }}
3562
+ }},
3563
+ {{
3564
+ selector: '.dimmed',
3565
+ style: {{
3566
+ 'opacity': 0.38,
3567
+ 'text-opacity': 0.32
3568
+ }}
3569
+ }},
3570
+ {{
3571
+ selector: '.secondary',
3572
+ style: {{
3573
+ 'opacity': 0.66,
3574
+ 'text-opacity': 0.58
3575
+ }}
3576
+ }},
3577
+ {{
3578
+ selector: '.primary',
3579
+ style: {{
3580
+ 'opacity': 1,
3581
+ 'text-opacity': 1,
3582
+ 'z-index': 30,
3583
+ 'border-width': 3,
3584
+ 'border-color': 'rgba(255,255,255,0.78)',
3585
+ 'background-color': 'rgba(255,255,255,0.24)',
3586
+ 'underlay-color': 'rgba(255,255,255,0.14)',
3587
+ 'underlay-opacity': 0.72,
3588
+ 'underlay-padding': 7,
3589
+ 'shadow-blur': 16,
3590
+ 'shadow-color': 'rgba(255,255,255,0.12)',
3591
+ 'shadow-opacity': 0.38,
3592
+ 'shadow-offset-x': 0,
3593
+ 'shadow-offset-y': 8
3594
+ }}
3595
+ }},
3596
+ {{
3597
+ selector: '.neighbor',
3598
+ style: {{
3599
+ 'opacity': 0.86,
3600
+ 'text-opacity': 0.82,
3601
+ 'border-width': 2,
3602
+ 'border-color': 'rgba(255,255,255,0.48)',
3603
+ 'background-color': 'rgba(255,255,255,0.18)'
3604
+ }}
3605
+ }},
3606
+ {{
3607
+ selector: 'edge.active-edge',
3608
+ style: {{
3609
+ 'opacity': 0.92,
3610
+ 'line-color': 'rgba(255,255,255,0.72)',
3611
+ 'target-arrow-color': 'rgba(255,255,255,0.72)',
3612
+ 'width': 3
3613
+ }}
3614
+ }}
3615
+ ],
3616
+ layout: {{
3617
+ name: 'cose',
3618
+ animate: false,
3619
+ fit: true,
3620
+ padding: 70,
3621
+ nodeRepulsion: 9000,
3622
+ idealEdgeLength: 120,
3623
+ edgeElasticity: 120,
3624
+ gravity: 0.25
3625
+ }}
3626
+ }});
3627
+
3628
+ const tooltip = document.getElementById('tooltip');
3629
+
3630
+ cy.on('mouseover', 'node', (event) => {{
3631
+ const node = event.target;
3632
+ tooltip.textContent = node.data('fullLabel');
3633
+ tooltip.classList.remove('hidden');
3634
+ }});
3635
+
3636
+ cy.on('mousemove', 'node', (event) => {{
3637
+ const rendered = event.renderedPosition;
3638
+ const bounds = cy.container().getBoundingClientRect();
3639
+ tooltip.style.left = `${{bounds.left + rendered.x + 14}}px`;
3640
+ tooltip.style.top = `${{bounds.top + rendered.y + 14}}px`;
3641
+ }});
3642
+
3643
+ cy.on('mouseout', 'node', () => {{
3644
+ tooltip.classList.add('hidden');
3645
+ }});
3646
+
3647
+ cy.on('tap', 'node', (event) => {{
3648
+ const node = event.target;
3649
+ const directEdges = node.connectedEdges();
3650
+ const directNodes = directEdges.connectedNodes().difference(node);
3651
+ const secondaryEdges = directNodes.connectedEdges().difference(directEdges);
3652
+ const secondaryNodes = secondaryEdges.connectedNodes().difference(node).difference(directNodes);
3653
+
3654
+ cy.elements().removeClass('dimmed secondary neighbor primary active-edge');
3655
+ cy.elements().addClass('dimmed');
3656
+
3657
+ secondaryNodes.removeClass('dimmed').addClass('secondary');
3658
+ secondaryEdges.removeClass('dimmed').addClass('secondary');
3659
+ directNodes.removeClass('dimmed secondary').addClass('neighbor');
3660
+ directEdges.removeClass('dimmed secondary').addClass('active-edge');
3661
+ node.removeClass('dimmed secondary neighbor').addClass('primary');
3662
+ }});
3663
+
3664
+ cy.on('tap', (event) => {{
3665
+ if (event.target === cy) {{
3666
+ cy.elements().removeClass('dimmed secondary neighbor primary active-edge');
3667
+ }}
3668
+ }});
3669
+
3670
+ document.getElementById('zoom-in').addEventListener('click', () => {{
3671
+ cy.zoom({{ level: cy.zoom() * 1.2, renderedPosition: {{ x: cy.width() / 2, y: cy.height() / 2 }} }});
3672
+ }});
3673
+
3674
+ document.getElementById('zoom-out').addEventListener('click', () => {{
3675
+ cy.zoom({{ level: cy.zoom() / 1.2, renderedPosition: {{ x: cy.width() / 2, y: cy.height() / 2 }} }});
3676
+ }});
3677
+
3678
+ document.getElementById('fit').addEventListener('click', () => {{
3679
+ cy.fit(undefined, 70);
3680
+ }});
3681
+ </script>
3682
+ </body>
3683
+ </html>
3684
+ """
3685
+
3686
+
3687
+ def _form_int(value, default=1):
3688
+ try:
3689
+ return int(value)
3690
+ except (TypeError, ValueError):
3691
+ return default
3692
+
3693
+
3694
+ @app.post("/open", response_class=HTMLResponse)
3695
+ async def open_source_post(request: Request):
3696
+ fields, error = await read_form(request)
3697
+ if error:
3698
+ return error
3699
+ return open_source(fields.get("path", ""), _form_int(fields.get("line")))
3700
+
3701
+
3702
+ @app.post("/open-folder", response_class=HTMLResponse)
3703
+ async def open_folder_post(request: Request):
3704
+ fields, error = await read_form(request)
3705
+ if error:
3706
+ return error
3707
+ return open_folder(fields.get("path", ""))
3708
+
3709
+
3710
+ @app.post("/toggle-pin")
3711
+ async def pin_repository_post(request: Request):
3712
+ fields, error = await read_form(request)
3713
+ if error:
3714
+ return error
3715
+ return pin_repository(fields.get("path", ""))
3716
+
3717
+
3718
+ @app.post("/load-repository", response_class=HTMLResponse)
3719
+ async def load_repository_post(request: Request):
3720
+ fields, error = await read_form(request)
3721
+ if error:
3722
+ return error
3723
+ return load_repository(fields.get("source_type", ""), fields.get("target", ""))
3724
+
3725
+
3726
+ @app.post("/save-baseline")
3727
+ async def save_baseline_post(request: Request):
3728
+ fields, error = await read_form(request)
3729
+ if error:
3730
+ return error
3731
+ return save_baseline(fields.get("path", ""), fields.get("select", ""))