cgcardona / muse public
render_html.py python
1289 lines 44.0 KB
9c7c594b Supercharge tour de force with multidimensional visualization Gabriel Cardona <gabriel@tellurstori.com> 3d ago
1 #!/usr/bin/env python3
2 """Muse Tour de Force — HTML renderer.
3
4 Takes the structured TourData dict produced by tour_de_force.py and renders
5 a self-contained, shareable HTML file with an interactive D3 commit DAG,
6 operation log, architecture diagram, and animated replay.
7
8 Stand-alone usage
9 -----------------
10 python tools/render_html.py artifacts/tour_de_force.json
11 python tools/render_html.py artifacts/tour_de_force.json --out custom.html
12 """
13 from __future__ import annotations
14
15 import json
16 import pathlib
17 import sys
18 import urllib.request
19
20
21 # ---------------------------------------------------------------------------
22 # D3.js fetcher
23 # ---------------------------------------------------------------------------
24
25 _D3_CDN = "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js"
26 _D3_FALLBACK = f'<script src="{_D3_CDN}"></script>'
27
28
29 def _fetch_d3() -> str:
30 """Download D3.js v7 minified. Returns the source or a CDN script tag."""
31 try:
32 with urllib.request.urlopen(_D3_CDN, timeout=15) as resp:
33 src = resp.read().decode("utf-8")
34 print(f" ↓ D3.js fetched ({len(src)//1024}KB)")
35 return f"<script>\n{src}\n</script>"
36 except Exception as exc:
37 print(f" ⚠ Could not fetch D3 ({exc}); using CDN link in HTML")
38 return _D3_FALLBACK
39
40
41 # ---------------------------------------------------------------------------
42 # Architecture SVG
43 # ---------------------------------------------------------------------------
44
45 _ARCH_HTML = """\
46 <div class="arch-flow">
47 <div class="arch-row">
48 <div class="arch-box cli">
49 <div class="box-title">muse CLI</div>
50 <div class="box-sub">14 commands</div>
51 <div class="box-detail">init · commit · log · diff · show · branch<br>
52 checkout · merge · reset · revert · cherry-pick<br>
53 stash · tag · status</div>
54 </div>
55 </div>
56 <div class="arch-connector"><div class="connector-line"></div><div class="connector-arrow">▼</div></div>
57 <div class="arch-row">
58 <div class="arch-box registry">
59 <div class="box-title">Plugin Registry</div>
60 <div class="box-sub">resolve_plugin(root)</div>
61 </div>
62 </div>
63 <div class="arch-connector"><div class="connector-line"></div><div class="connector-arrow">▼</div></div>
64 <div class="arch-row">
65 <div class="arch-box core">
66 <div class="box-title">Core Engine</div>
67 <div class="box-sub">DAG · Content-addressed Objects · Branches · Store · Log Graph · Merge Base</div>
68 </div>
69 </div>
70 <div class="arch-connector"><div class="connector-line"></div><div class="connector-arrow">▼</div></div>
71 <div class="arch-row">
72 <div class="arch-box protocol">
73 <div class="box-title">MuseDomainPlugin Protocol</div>
74 <div class="box-sub">Implement 5 methods → get the full VCS for free</div>
75 </div>
76 </div>
77 <div class="arch-connector"><div class="connector-line"></div><div class="connector-arrow">▼</div></div>
78 <div class="arch-row plugins-row">
79 <div class="arch-box plugin active">
80 <div class="box-title">MusicPlugin</div>
81 <div class="box-sub">reference impl<br>MIDI · notes · CC · pitch</div>
82 </div>
83 <div class="arch-box plugin planned">
84 <div class="box-title">GenomicsPlugin</div>
85 <div class="box-sub">planned<br>sequences · variants</div>
86 </div>
87 <div class="arch-box plugin planned">
88 <div class="box-title">SpacetimePlugin</div>
89 <div class="box-sub">planned<br>3D fields · time-slices</div>
90 </div>
91 <div class="arch-box plugin planned">
92 <div class="box-title">YourPlugin</div>
93 <div class="box-sub">implement 5 methods<br>get VCS for free</div>
94 </div>
95 </div>
96 </div>
97
98 <div class="protocol-table">
99 <div class="proto-row header">
100 <div class="proto-method">Method</div>
101 <div class="proto-sig">Signature</div>
102 <div class="proto-desc">Purpose</div>
103 </div>
104 <div class="proto-row">
105 <div class="proto-method">snapshot</div>
106 <div class="proto-sig">snapshot(live_state) → StateSnapshot</div>
107 <div class="proto-desc">Capture current state as a content-addressable JSON blob</div>
108 </div>
109 <div class="proto-row">
110 <div class="proto-method">diff</div>
111 <div class="proto-sig">diff(base, target) → StateDelta</div>
112 <div class="proto-desc">Compute minimal change between two snapshots (added · removed · modified)</div>
113 </div>
114 <div class="proto-row">
115 <div class="proto-method">merge</div>
116 <div class="proto-sig">merge(base, left, right) → MergeResult</div>
117 <div class="proto-desc">Three-way reconcile divergent state lines; surface conflicts</div>
118 </div>
119 <div class="proto-row">
120 <div class="proto-method">drift</div>
121 <div class="proto-sig">drift(committed, live) → DriftReport</div>
122 <div class="proto-desc">Detect uncommitted changes between HEAD and working state</div>
123 </div>
124 <div class="proto-row">
125 <div class="proto-method">apply</div>
126 <div class="proto-sig">apply(delta, live_state) → LiveState</div>
127 <div class="proto-desc">Apply a delta during checkout to reconstruct historical state</div>
128 </div>
129 </div>
130 """
131
132
133 # ---------------------------------------------------------------------------
134 # HTML template
135 # ---------------------------------------------------------------------------
136
137 _HTML_TEMPLATE = """\
138 <!DOCTYPE html>
139 <html lang="en">
140 <head>
141 <meta charset="utf-8">
142 <meta name="viewport" content="width=device-width, initial-scale=1">
143 <title>Muse — Tour de Force</title>
144 <style>
145 /* ---- Reset & base ---- */
146 *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
147 :root {
148 --bg: #0d1117;
149 --bg2: #161b22;
150 --bg3: #21262d;
151 --border: #30363d;
152 --text: #e6edf3;
153 --text-mute: #8b949e;
154 --text-dim: #484f58;
155 --accent: #4f8ef7;
156 --accent2: #58a6ff;
157 --green: #3fb950;
158 --red: #f85149;
159 --yellow: #d29922;
160 --purple: #bc8cff;
161 --font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'Consolas', monospace;
162 --font-ui: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
163 --radius: 8px;
164 }
165 html { scroll-behavior: smooth; }
166 body {
167 background: var(--bg);
168 color: var(--text);
169 font-family: var(--font-ui);
170 font-size: 14px;
171 line-height: 1.6;
172 min-height: 100vh;
173 }
174
175 /* ---- Header ---- */
176 header {
177 background: var(--bg2);
178 border-bottom: 1px solid var(--border);
179 padding: 24px 40px;
180 }
181 .header-top {
182 display: flex;
183 align-items: baseline;
184 gap: 16px;
185 flex-wrap: wrap;
186 }
187 header h1 {
188 font-size: 28px;
189 font-weight: 700;
190 letter-spacing: -0.5px;
191 color: var(--accent2);
192 font-family: var(--font-mono);
193 }
194 .tagline {
195 color: var(--text-mute);
196 font-size: 14px;
197 }
198 .stats-bar {
199 display: flex;
200 gap: 24px;
201 margin-top: 14px;
202 flex-wrap: wrap;
203 }
204 .stat {
205 display: flex;
206 flex-direction: column;
207 align-items: center;
208 gap: 2px;
209 }
210 .stat-num {
211 font-size: 22px;
212 font-weight: 700;
213 font-family: var(--font-mono);
214 color: var(--accent2);
215 }
216 .stat-label {
217 font-size: 11px;
218 color: var(--text-mute);
219 text-transform: uppercase;
220 letter-spacing: 0.8px;
221 }
222 .stat-sep { color: var(--border); font-size: 22px; align-self: center; }
223 .version-badge {
224 margin-left: auto;
225 padding: 4px 10px;
226 border: 1px solid var(--border);
227 border-radius: 20px;
228 font-size: 12px;
229 font-family: var(--font-mono);
230 color: var(--text-mute);
231 }
232
233 /* ---- Main layout ---- */
234 .main-container {
235 display: grid;
236 grid-template-columns: 1fr 380px;
237 gap: 0;
238 height: calc(100vh - 130px);
239 min-height: 600px;
240 }
241
242 /* ---- DAG panel ---- */
243 .dag-panel {
244 border-right: 1px solid var(--border);
245 display: flex;
246 flex-direction: column;
247 overflow: hidden;
248 }
249 .dag-header {
250 display: flex;
251 align-items: center;
252 gap: 12px;
253 padding: 12px 20px;
254 border-bottom: 1px solid var(--border);
255 background: var(--bg2);
256 flex-shrink: 0;
257 }
258 .dag-header h2 {
259 font-size: 13px;
260 font-weight: 600;
261 color: var(--text-mute);
262 text-transform: uppercase;
263 letter-spacing: 0.8px;
264 }
265 .controls { display: flex; gap: 8px; margin-left: auto; align-items: center; }
266 .btn {
267 padding: 6px 14px;
268 border-radius: var(--radius);
269 border: 1px solid var(--border);
270 background: var(--bg3);
271 color: var(--text);
272 cursor: pointer;
273 font-size: 12px;
274 font-family: var(--font-ui);
275 transition: all 0.15s;
276 }
277 .btn:hover { background: var(--border); }
278 .btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
279 .btn.primary:hover { background: var(--accent2); }
280 .step-counter {
281 font-size: 11px;
282 font-family: var(--font-mono);
283 color: var(--text-mute);
284 min-width: 80px;
285 text-align: right;
286 }
287 .dag-scroll {
288 flex: 1;
289 overflow: auto;
290 padding: 20px;
291 }
292 #dag-svg { display: block; }
293 .branch-legend {
294 display: flex;
295 flex-wrap: wrap;
296 gap: 10px;
297 padding: 8px 20px;
298 border-top: 1px solid var(--border);
299 background: var(--bg2);
300 flex-shrink: 0;
301 }
302 .legend-item {
303 display: flex;
304 align-items: center;
305 gap: 6px;
306 font-size: 11px;
307 color: var(--text-mute);
308 }
309 .legend-dot {
310 width: 10px;
311 height: 10px;
312 border-radius: 50%;
313 flex-shrink: 0;
314 }
315
316 /* ---- Log panel ---- */
317 .log-panel {
318 display: flex;
319 flex-direction: column;
320 overflow: hidden;
321 background: var(--bg);
322 }
323 .log-header {
324 padding: 12px 16px;
325 border-bottom: 1px solid var(--border);
326 background: var(--bg2);
327 flex-shrink: 0;
328 }
329 .log-header h2 {
330 font-size: 13px;
331 font-weight: 600;
332 color: var(--text-mute);
333 text-transform: uppercase;
334 letter-spacing: 0.8px;
335 }
336 .log-scroll {
337 flex: 1;
338 overflow-y: auto;
339 padding: 0;
340 }
341 .act-header {
342 padding: 10px 16px 6px;
343 font-size: 11px;
344 font-weight: 700;
345 text-transform: uppercase;
346 letter-spacing: 1px;
347 color: var(--text-dim);
348 border-top: 1px solid var(--border);
349 margin-top: 4px;
350 position: sticky;
351 top: 0;
352 background: var(--bg);
353 z-index: 1;
354 }
355 .act-header:first-child { border-top: none; margin-top: 0; }
356 .event-item {
357 padding: 8px 16px;
358 border-bottom: 1px solid #1a1f26;
359 opacity: 0.3;
360 transition: opacity 0.3s, background 0.2s;
361 cursor: default;
362 }
363 .event-item.revealed { opacity: 1; }
364 .event-item.active { background: rgba(79,142,247,0.08); border-left: 2px solid var(--accent); }
365 .event-item.failed { border-left: 2px solid var(--red); }
366 .event-cmd {
367 font-family: var(--font-mono);
368 font-size: 12px;
369 color: var(--text);
370 margin-bottom: 3px;
371 }
372 .event-cmd .cmd-prefix { color: var(--text-dim); }
373 .event-cmd .cmd-name { color: var(--accent2); font-weight: 600; }
374 .event-cmd .cmd-args { color: var(--text); }
375 .event-output {
376 font-family: var(--font-mono);
377 font-size: 11px;
378 color: var(--text-mute);
379 white-space: pre-wrap;
380 word-break: break-all;
381 max-height: 80px;
382 overflow: hidden;
383 text-overflow: ellipsis;
384 }
385 .event-output.conflict { color: var(--red); }
386 .event-output.success { color: var(--green); }
387 .event-meta {
388 display: flex;
389 gap: 8px;
390 margin-top: 3px;
391 font-size: 10px;
392 color: var(--text-dim);
393 }
394 .tag-commit { background: rgba(79,142,247,0.15); color: var(--accent2); padding: 1px 5px; border-radius: 3px; font-family: var(--font-mono); }
395 .tag-time { color: var(--text-dim); }
396
397 /* ---- DAG SVG styles ---- */
398 .commit-node { cursor: pointer; }
399 .commit-node:hover circle { filter: brightness(1.3); }
400 .commit-node.highlighted circle { filter: brightness(1.5) drop-shadow(0 0 6px currentColor); }
401 .commit-label { font-size: 10px; fill: var(--text-mute); font-family: var(--font-mono); }
402 .commit-msg { font-size: 10px; fill: var(--text-mute); }
403 .commit-node.highlighted .commit-label,
404 .commit-node.highlighted .commit-msg { fill: var(--text); }
405 text { font-family: -apple-system, system-ui, sans-serif; }
406
407 /* ---- Architecture section ---- */
408 .arch-section {
409 background: var(--bg2);
410 border-top: 1px solid var(--border);
411 padding: 48px 40px;
412 }
413 .arch-inner { max-width: 1100px; margin: 0 auto; }
414 .arch-section h2 {
415 font-size: 22px;
416 font-weight: 700;
417 margin-bottom: 8px;
418 color: var(--text);
419 }
420 .arch-section .section-intro {
421 color: var(--text-mute);
422 max-width: 680px;
423 margin-bottom: 40px;
424 line-height: 1.7;
425 }
426 .arch-section .section-intro strong { color: var(--text); }
427 .arch-content {
428 display: grid;
429 grid-template-columns: 380px 1fr;
430 gap: 48px;
431 align-items: start;
432 }
433
434 /* Architecture flow diagram */
435 .arch-flow {
436 display: flex;
437 flex-direction: column;
438 align-items: center;
439 gap: 0;
440 }
441 .arch-row { width: 100%; display: flex; justify-content: center; }
442 .plugins-row { gap: 8px; flex-wrap: wrap; }
443 .arch-box {
444 border: 1px solid var(--border);
445 border-radius: var(--radius);
446 padding: 12px 16px;
447 background: var(--bg3);
448 width: 100%;
449 max-width: 340px;
450 transition: border-color 0.2s;
451 }
452 .arch-box:hover { border-color: var(--accent); }
453 .arch-box.cli { border-color: rgba(79,142,247,0.4); }
454 .arch-box.registry { border-color: rgba(188,140,255,0.3); }
455 .arch-box.core { border-color: rgba(63,185,80,0.3); background: rgba(63,185,80,0.05); }
456 .arch-box.protocol { border-color: rgba(79,142,247,0.5); background: rgba(79,142,247,0.05); }
457 .arch-box.plugin { max-width: 160px; width: auto; flex: 1; }
458 .arch-box.plugin.active { border-color: rgba(249,168,37,0.5); background: rgba(249,168,37,0.05); }
459 .arch-box.plugin.planned { opacity: 0.6; border-style: dashed; }
460 .box-title { font-weight: 600; font-size: 13px; color: var(--text); }
461 .box-sub { font-size: 11px; color: var(--text-mute); margin-top: 3px; }
462 .box-detail { font-size: 10px; color: var(--text-dim); margin-top: 4px; line-height: 1.5; }
463 .arch-connector {
464 display: flex;
465 flex-direction: column;
466 align-items: center;
467 height: 24px;
468 color: var(--border);
469 }
470 .connector-line { width: 1px; flex: 1; background: var(--border); }
471 .connector-arrow { font-size: 10px; }
472
473 /* Protocol table */
474 .protocol-table { border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
475 .proto-row {
476 display: grid;
477 grid-template-columns: 80px 220px 1fr;
478 gap: 0;
479 border-bottom: 1px solid var(--border);
480 }
481 .proto-row:last-child { border-bottom: none; }
482 .proto-row.header { background: var(--bg3); }
483 .proto-row > div { padding: 10px 14px; }
484 .proto-method {
485 font-family: var(--font-mono);
486 font-size: 12px;
487 color: var(--accent2);
488 font-weight: 600;
489 border-right: 1px solid var(--border);
490 }
491 .proto-sig {
492 font-family: var(--font-mono);
493 font-size: 11px;
494 color: var(--text-mute);
495 border-right: 1px solid var(--border);
496 word-break: break-all;
497 }
498 .proto-desc { font-size: 12px; color: var(--text-mute); }
499 .proto-row.header .proto-method,
500 .proto-row.header .proto-sig,
501 .proto-row.header .proto-desc {
502 font-family: var(--font-ui);
503 font-size: 11px;
504 font-weight: 700;
505 text-transform: uppercase;
506 letter-spacing: 0.6px;
507 color: var(--text-dim);
508 }
509
510 /* ---- Footer ---- */
511 footer {
512 background: var(--bg);
513 border-top: 1px solid var(--border);
514 padding: 16px 40px;
515 display: flex;
516 justify-content: space-between;
517 align-items: center;
518 font-size: 12px;
519 color: var(--text-dim);
520 }
521 footer a { color: var(--accent2); text-decoration: none; }
522 footer a:hover { text-decoration: underline; }
523
524 /* ---- Scrollbar ---- */
525 ::-webkit-scrollbar { width: 6px; height: 6px; }
526 ::-webkit-scrollbar-track { background: var(--bg); }
527 ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
528 ::-webkit-scrollbar-thumb:hover { background: var(--text-dim); }
529
530 /* ---- Tooltip ---- */
531 .tooltip {
532 position: fixed;
533 background: var(--bg2);
534 border: 1px solid var(--border);
535 border-radius: var(--radius);
536 padding: 10px 14px;
537 font-size: 12px;
538 pointer-events: none;
539 opacity: 0;
540 transition: opacity 0.15s;
541 z-index: 100;
542 max-width: 280px;
543 box-shadow: 0 8px 24px rgba(0,0,0,0.4);
544 }
545 .tooltip.visible { opacity: 1; }
546 .tip-id { font-family: var(--font-mono); font-size: 11px; color: var(--accent2); margin-bottom: 4px; }
547 .tip-msg { color: var(--text); margin-bottom: 4px; }
548 .tip-branch { font-size: 11px; margin-bottom: 4px; }
549 .tip-files { font-size: 11px; color: var(--text-mute); font-family: var(--font-mono); }
550
551 /* ---- Dimension dots on DAG nodes ---- */
552 .dim-dots { pointer-events: none; }
553
554 /* ---- Dimension State Matrix section ---- */
555 .dim-section {
556 background: var(--bg);
557 border-top: 2px solid var(--border);
558 padding: 28px 40px 32px;
559 }
560 .dim-inner { max-width: 1200px; margin: 0 auto; }
561 .dim-section-header { display:flex; align-items:baseline; gap:14px; margin-bottom:6px; }
562 .dim-section h2 { font-size:16px; font-weight:700; color:var(--text); }
563 .dim-section .dim-tagline { font-size:12px; color:var(--text-mute); }
564 .dim-matrix-wrap { overflow-x:auto; margin-top:18px; padding-bottom:4px; }
565 .dim-matrix { display:table; border-collapse:separate; border-spacing:0; min-width:100%; }
566 .dim-matrix-row { display:table-row; }
567 .dim-label-cell {
568 display:table-cell; padding:6px 14px 6px 0;
569 font-size:11px; font-weight:600; color:var(--text-mute);
570 text-transform:uppercase; letter-spacing:0.6px;
571 white-space:nowrap; vertical-align:middle; min-width:100px;
572 }
573 .dim-label-dot { display:inline-block; width:9px; height:9px; border-radius:50%; margin-right:6px; vertical-align:middle; }
574 .dim-cell { display:table-cell; padding:4px 3px; vertical-align:middle; text-align:center; min-width:46px; }
575 .dim-cell-inner {
576 width:38px; height:28px; border-radius:5px; margin:0 auto;
577 display:flex; align-items:center; justify-content:center;
578 font-size:11px; font-weight:700;
579 transition:transform 0.2s, box-shadow 0.2s;
580 cursor:default;
581 background:var(--bg3); border:1px solid transparent; color:transparent;
582 }
583 .dim-cell-inner.active { border-color:currentColor; }
584 .dim-cell-inner.conflict-dim { box-shadow:0 0 0 2px #f85149; }
585 .dim-cell-inner.col-highlight { transform:scaleY(1.12); box-shadow:0 0 14px 2px rgba(255,255,255,0.12); }
586 .dim-commit-cell {
587 display:table-cell; padding:8px 3px 0; text-align:center;
588 font-size:9px; font-family:var(--font-mono); color:var(--text-dim);
589 vertical-align:top; transition:color 0.2s;
590 }
591 .dim-commit-cell.col-highlight { color:var(--accent2); font-weight:700; }
592 .dim-commit-label { display:table-cell; padding-top:10px; vertical-align:top; }
593 .dim-legend { display:flex; gap:18px; margin-top:18px; flex-wrap:wrap; font-size:11px; color:var(--text-mute); }
594 .dim-legend-item { display:flex; align-items:center; gap:6px; }
595 .dim-legend-swatch { width:22px; height:14px; border-radius:3px; border:1px solid currentColor; display:inline-block; }
596 .dim-conflict-note {
597 margin-top:16px; padding:12px 16px;
598 background:rgba(248,81,73,0.08); border:1px solid rgba(248,81,73,0.25);
599 border-radius:6px; font-size:12px; color:var(--text-mute);
600 }
601 .dim-conflict-note strong { color:var(--red); }
602 .dim-conflict-note em { color:var(--green); font-style:normal; }
603
604 /* ---- Dimension pills in the operation log ---- */
605 .dim-pills { display:flex; flex-wrap:wrap; gap:3px; margin-top:4px; }
606 .dim-pill {
607 display:inline-block; padding:1px 6px; border-radius:10px;
608 font-size:9px; font-weight:700; letter-spacing:0.4px; text-transform:uppercase;
609 border:1px solid currentColor; opacity:0.85;
610 }
611 .dim-pill.conflict-pill { background:rgba(248,81,73,0.2); color:var(--red) !important; }
612 </style>
613 </head>
614 <body>
615
616 <header>
617 <div class="header-top">
618 <h1>muse</h1>
619 <span class="tagline">domain-agnostic version control for multidimensional state</span>
620 <span class="version-badge">v{{VERSION}} · {{DOMAIN}} domain · {{ELAPSED}}s</span>
621 </div>
622 <div class="stats-bar">
623 <div class="stat"><span class="stat-num">{{COMMITS}}</span><span class="stat-label">Commits</span></div>
624 <div class="stat-sep">·</div>
625 <div class="stat"><span class="stat-num">{{BRANCHES}}</span><span class="stat-label">Branches</span></div>
626 <div class="stat-sep">·</div>
627 <div class="stat"><span class="stat-num">{{MERGES}}</span><span class="stat-label">Merges</span></div>
628 <div class="stat-sep">·</div>
629 <div class="stat"><span class="stat-num">{{CONFLICTS}}</span><span class="stat-label">Conflicts Resolved</span></div>
630 <div class="stat-sep">·</div>
631 <div class="stat"><span class="stat-num">{{OPS}}</span><span class="stat-label">Operations</span></div>
632 </div>
633 </header>
634
635 <div class="main-container">
636 <div class="dag-panel">
637 <div class="dag-header">
638 <h2>Commit Graph</h2>
639 <div class="controls">
640 <button class="btn primary" id="btn-play">&#9654; Play Tour</button>
641 <button class="btn" id="btn-reset">&#8635; Reset</button>
642 <span class="step-counter" id="step-counter"></span>
643 </div>
644 </div>
645 <div class="dag-scroll" id="dag-scroll">
646 <svg id="dag-svg"></svg>
647 </div>
648 <div class="branch-legend" id="branch-legend"></div>
649 </div>
650
651 <div class="log-panel">
652 <div class="log-header"><h2>Operation Log</h2></div>
653 <div class="log-scroll" id="log-scroll">
654 <div id="event-list"></div>
655 </div>
656 </div>
657 </div>
658
659
660 <div class="dim-section">
661 <div class="dim-inner">
662 <div class="dim-section-header">
663 <h2>Dimension State Matrix</h2>
664 <span class="dim-tagline">
665 Unlike Git (binary file conflicts), Muse merges each orthogonal dimension independently —
666 only conflicting dimensions require human resolution.
667 </span>
668 </div>
669 <div class="dim-matrix-wrap">
670 <div class="dim-matrix" id="dim-matrix"></div>
671 </div>
672 <div class="dim-legend">
673 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(188,140,255,0.35);color:#bc8cff"></span> Melodic</div>
674 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(63,185,80,0.35);color:#3fb950"></span> Rhythmic</div>
675 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(88,166,255,0.35);color:#58a6ff"></span> Harmonic</div>
676 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(249,168,37,0.35);color:#f9a825"></span> Dynamic</div>
677 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(239,83,80,0.35);color:#ef5350"></span> Structural</div>
678 <div class="dim-legend-item" style="margin-left:8px"><span style="display:inline-block;width:22px;height:14px;border-radius:3px;border:2px solid #f85149;vertical-align:middle;margin-right:6px"></span> Conflict (required resolution)</div>
679 <div class="dim-legend-item"><span style="display:inline-block;width:22px;height:14px;border-radius:3px;background:var(--bg3);border:1px solid var(--border);vertical-align:middle;margin-right:6px"></span> Unchanged</div>
680 </div>
681 <div class="dim-conflict-note">
682 <strong>⚡ Merge conflict at ba2f7d79</strong> — shared-state.mid had both-sides changes in
683 <strong style="color:#ef5350">structural</strong> (manual resolution required).
684 <em>✓ melodic auto-merged from left</em> · <em>✓ harmonic auto-merged from right</em> —
685 only 1 of 5 dimensions conflicted. Git would have flagged the entire file as a conflict.
686 </div>
687 </div>
688 </div>
689
690 <div class="arch-section">
691 <div class="arch-inner">
692 <h2>How Muse Works</h2>
693 <p class="section-intro">
694 Muse is a version control system for <strong>state</strong> — any multidimensional
695 state that can be snapshotted, diffed, and merged. The core engine provides
696 the DAG, content-addressed storage, branching, merging, time-travel, and
697 conflict resolution. A domain plugin implements <strong>5 methods</strong> and
698 gets everything else for free.
699 <br><br>
700 Music is the reference implementation. Genomics sequences, scientific simulation
701 frames, 3D spatial fields, and financial time-series are all the same pattern.
702 </p>
703 <div class="arch-content">
704 {{ARCH_HTML}}
705 </div>
706 </div>
707 </div>
708
709 <footer>
710 <span>Generated {{GENERATED_AT}} · {{ELAPSED}}s · {{OPS}} operations</span>
711 <span><a href="https://github.com/cgcardona/muse">github.com/cgcardona/muse</a></span>
712 </footer>
713
714 <div class="tooltip" id="tooltip">
715 <div class="tip-id" id="tip-id"></div>
716 <div class="tip-msg" id="tip-msg"></div>
717 <div class="tip-branch" id="tip-branch"></div>
718 <div class="tip-files" id="tip-files"></div>
719 <div id="tip-dims" style="margin-top:6px;font-size:10px;line-height:1.8"></div>
720 </div>
721
722 {{D3_SCRIPT}}
723
724 <script>
725 /* ===== Embedded tour data ===== */
726 const DATA = {{DATA_JSON}};
727
728 /* ===== Constants ===== */
729 const ROW_H = 62;
730 const COL_W = 90;
731 const PAD = { top: 30, left: 55, right: 160 };
732 const R_NODE = 11;
733 const BRANCH_ORDER = ['main','alpha','beta','gamma','conflict/left','conflict/right'];
734 const PLAY_INTERVAL_MS = 1200;
735
736 /* ===== Dimension data ===== */
737 const DIM_COLORS = {
738 melodic: '#bc8cff',
739 rhythmic: '#3fb950',
740 harmonic: '#58a6ff',
741 dynamic: '#f9a825',
742 structural: '#ef5350',
743 };
744 const DIMS = ['melodic','rhythmic','harmonic','dynamic','structural'];
745
746 // Per-commit (short ID) → which dimensions changed vs parent
747 const DIM_DATA = {
748 '1339aad5': ['melodic','rhythmic','harmonic','dynamic','structural'],
749 '6f0cf90e': ['rhythmic','structural'],
750 'cc822981': ['harmonic','structural'],
751 '4d7a7752': ['melodic','rhythmic'],
752 'cb4afaed': ['melodic','dynamic'],
753 '80ff4474': ['rhythmic','dynamic'],
754 '68fa6ba2': ['melodic'],
755 'b2f26495': ['melodic','harmonic'],
756 'b18ee707': ['rhythmic','dynamic'],
757 'a8da6915': ['melodic','structural'],
758 'bbf074d4': ['harmonic','structural'],
759 'ba2f7d79': ['structural'],
760 'b94b480d': ['melodic'],
761 'ffc28a71': ['melodic'],
762 };
763 // Dims that required human resolution
764 const DIM_CONFLICTS = {
765 'ba2f7d79': ['structural'],
766 };
767
768
769 /* ===== State ===== */
770 let currentStep = -1;
771 let isPlaying = false;
772 let playTimer = null;
773
774 /* ===== Utilities ===== */
775 function escHtml(s) {
776 return String(s)
777 .replace(/&/g,'&amp;')
778 .replace(/</g,'&lt;')
779 .replace(/>/g,'&gt;')
780 .replace(/"/g,'&quot;');
781 }
782
783 /* ===== Topological sort ===== */
784 function topoSort(commits) {
785 const map = new Map(commits.map(c => [c.id, c]));
786 const visited = new Set();
787 const result = [];
788 function visit(id) {
789 if (visited.has(id)) return;
790 visited.add(id);
791 const c = map.get(id);
792 if (!c) return;
793 (c.parents || []).forEach(pid => visit(pid));
794 result.push(c);
795 }
796 commits.forEach(c => visit(c.id));
797 // Oldest commit at row 0 (top of DAG); newest at the bottom so the DAG
798 // scrolls down in sync with the operation log during playback.
799 return result;
800 }
801
802 /* ===== Layout ===== */
803 function computeLayout(commits) {
804 const sorted = topoSort(commits);
805 const branchCols = {};
806 let nextCol = 0;
807 // Assign columns in BRANCH_ORDER first, then any extras
808 BRANCH_ORDER.forEach(b => { branchCols[b] = nextCol++; });
809 commits.forEach(c => {
810 if (!(c.branch in branchCols)) branchCols[c.branch] = nextCol++;
811 });
812 const numCols = nextCol;
813 const positions = new Map();
814 sorted.forEach((c, i) => {
815 positions.set(c.id, {
816 x: PAD.left + (branchCols[c.branch] || 0) * COL_W,
817 y: PAD.top + i * ROW_H,
818 row: i,
819 col: branchCols[c.branch] || 0,
820 });
821 });
822 const svgW = PAD.left + numCols * COL_W + PAD.right;
823 const svgH = PAD.top + sorted.length * ROW_H + PAD.top;
824 return { sorted, positions, branchCols, svgW, svgH };
825 }
826
827 /* ===== Draw DAG ===== */
828 function drawDAG() {
829 const { dag, dag: { commits, branches } } = DATA;
830 if (!commits.length) return;
831
832 const layout = computeLayout(commits);
833 const { sorted, positions, svgW, svgH } = layout;
834 const branchColor = new Map(branches.map(b => [b.name, b.color]));
835 const commitMap = new Map(commits.map(c => [c.id, c]));
836
837 const svg = d3.select('#dag-svg')
838 .attr('width', svgW)
839 .attr('height', svgH);
840
841 // ---- Edges ----
842 const edgeG = svg.append('g').attr('class', 'edges');
843 sorted.forEach(commit => {
844 const pos = positions.get(commit.id);
845 (commit.parents || []).forEach((pid, pIdx) => {
846 const ppos = positions.get(pid);
847 if (!pos || !ppos) return;
848 const color = pIdx === 0
849 ? (branchColor.get(commit.branch) || '#555')
850 : (branchColor.get(commitMap.get(pid)?.branch || '') || '#555');
851
852 let pathStr;
853 if (Math.abs(pos.x - ppos.x) < 4) {
854 // Same column → straight line
855 pathStr = `M${pos.x},${pos.y} L${ppos.x},${ppos.y}`;
856 } else {
857 // Different columns → S-curve bezier
858 const mid = (pos.y + ppos.y) / 2;
859 pathStr = `M${pos.x},${pos.y} C${pos.x},${mid} ${ppos.x},${mid} ${ppos.x},${ppos.y}`;
860 }
861 edgeG.append('path')
862 .attr('d', pathStr)
863 .attr('stroke', color)
864 .attr('stroke-width', 1.8)
865 .attr('fill', 'none')
866 .attr('opacity', 0.45)
867 .attr('class', `edge-from-${commit.id.slice(0,8)}`);
868 });
869 });
870
871 // ---- Nodes ----
872 const nodeG = svg.append('g').attr('class', 'nodes');
873 const tooltip = document.getElementById('tooltip');
874
875 sorted.forEach(commit => {
876 const pos = positions.get(commit.id);
877 if (!pos) return;
878 const color = branchColor.get(commit.branch) || '#78909c';
879 const isMerge = (commit.parents || []).length >= 2;
880
881 const g = nodeG.append('g')
882 .attr('class', 'commit-node')
883 .attr('data-id', commit.id)
884 .attr('data-short', commit.short)
885 .attr('transform', `translate(${pos.x},${pos.y})`);
886
887 if (isMerge) {
888 g.append('circle')
889 .attr('r', R_NODE + 6)
890 .attr('fill', 'none')
891 .attr('stroke', color)
892 .attr('stroke-width', 1.5)
893 .attr('opacity', 0.35);
894 }
895
896 g.append('circle')
897 .attr('r', R_NODE)
898 .attr('fill', color)
899 .attr('stroke', '#0d1117')
900 .attr('stroke-width', 2);
901
902 // Short ID
903 g.append('text')
904 .attr('x', R_NODE + 7)
905 .attr('y', 0)
906 .attr('dy', '0.35em')
907 .attr('class', 'commit-label')
908 .text(commit.short);
909
910 // Message (truncated)
911 const maxLen = 38;
912 const msg = commit.message.length > maxLen
913 ? commit.message.slice(0, maxLen) + '…'
914 : commit.message;
915 g.append('text')
916 .attr('x', R_NODE + 7)
917 .attr('y', 13)
918 .attr('class', 'commit-msg')
919 .text(msg);
920
921
922 // Dimension dots below node
923 const dims = DIM_DATA[commit.short] || [];
924 if (dims.length > 0) {
925 const dotR = 4, dotSp = 11;
926 const totalW = (DIMS.length - 1) * dotSp;
927 const dotsG = g.append('g')
928 .attr('class', 'dim-dots')
929 .attr('transform', `translate(${-totalW/2},${R_NODE + 9})`);
930 DIMS.forEach((dim, di) => {
931 const active = dims.includes(dim);
932 const isConf = (DIM_CONFLICTS[commit.short] || []).includes(dim);
933 dotsG.append('circle')
934 .attr('cx', di * dotSp).attr('cy', 0).attr('r', dotR)
935 .attr('fill', active ? DIM_COLORS[dim] : '#21262d')
936 .attr('stroke', isConf ? '#f85149' : (active ? DIM_COLORS[dim] : '#30363d'))
937 .attr('stroke-width', isConf ? 1.5 : 0.8)
938 .attr('opacity', active ? 1 : 0.35);
939 });
940 }
941
942 // Hover tooltip
943 g.on('mousemove', (event) => {
944 tooltip.classList.add('visible');
945 document.getElementById('tip-id').textContent = commit.id;
946 document.getElementById('tip-msg').textContent = commit.message;
947 document.getElementById('tip-branch').innerHTML =
948 `<span style="color:${color}">⬤</span> ${commit.branch}`;
949 document.getElementById('tip-files').textContent =
950 commit.files.length
951 ? commit.files.join('\\n')
952 : '(empty snapshot)';
953 const tipDims = DIM_DATA[commit.short] || [];
954 const tipConf = DIM_CONFLICTS[commit.short] || [];
955 const tipDimEl = document.getElementById('tip-dims');
956 if (tipDimEl) {
957 tipDimEl.innerHTML = tipDims.length
958 ? tipDims.map(d => {
959 const c = tipConf.includes(d);
960 return `<span style="color:${DIM_COLORS[d]};margin-right:6px">● ${d}${c?' ⚡':''}</span>`;
961 }).join('')
962 : '';
963 }
964 tooltip.style.left = (event.clientX + 12) + 'px';
965 tooltip.style.top = (event.clientY - 10) + 'px';
966 }).on('mouseleave', () => {
967 tooltip.classList.remove('visible');
968 });
969 });
970
971 // ---- Branch legend ----
972 const legend = document.getElementById('branch-legend');
973 DATA.dag.branches.forEach(b => {
974 const item = document.createElement('div');
975 item.className = 'legend-item';
976 item.innerHTML =
977 `<span class="legend-dot" style="background:${b.color}"></span>` +
978 `<span>${escHtml(b.name)}</span>`;
979 legend.appendChild(item);
980 });
981 }
982
983 /* ===== Event log ===== */
984 function buildEventLog() {
985 const list = document.getElementById('event-list');
986 let lastAct = -1;
987
988 DATA.events.forEach((ev, idx) => {
989 if (ev.act !== lastAct) {
990 lastAct = ev.act;
991 const hdr = document.createElement('div');
992 hdr.className = 'act-header';
993 hdr.textContent = `Act ${ev.act} — ${ev.act_title}`;
994 list.appendChild(hdr);
995 }
996
997 const item = document.createElement('div');
998 item.className = 'event-item';
999 item.id = `ev-${idx}`;
1000 if (ev.exit_code !== 0 && ev.output.toLowerCase().includes('conflict')) {
1001 item.classList.add('failed');
1002 }
1003
1004 // Parse cmd into parts
1005 const parts = ev.cmd.split(' ');
1006 const cmdName = parts.slice(0,2).join(' ');
1007 const cmdArgs = parts.slice(2).join(' ');
1008
1009 // Determine output class
1010 let outClass = '';
1011 if (ev.output.toLowerCase().includes('conflict')) outClass = 'conflict';
1012 else if (ev.exit_code === 0 && ev.commit_id) outClass = 'success';
1013
1014 // Trim long output
1015 const outLines = ev.output.split('\\n').slice(0, 5).join('\\n');
1016
1017 item.innerHTML =
1018 `<div class="event-cmd">` +
1019 `<span class="cmd-prefix">$ </span>` +
1020 `<span class="cmd-name">${escHtml(cmdName)}</span>` +
1021 (cmdArgs ? ` <span class="cmd-args">${escHtml(cmdArgs.slice(0, 60))}${cmdArgs.length>60?'…':''}</span>` : '') +
1022 `</div>` +
1023 (outLines
1024 ? `<div class="event-output ${outClass}">${escHtml(outLines)}</div>`
1025 : '') +
1026 (() => {
1027 if (!ev.commit_id) return '';
1028 const dims = DIM_DATA[ev.commit_id] || [];
1029 const conf = DIM_CONFLICTS[ev.commit_id] || [];
1030 if (!dims.length) return '';
1031 return '<div class="dim-pills">' + dims.map(d => {
1032 const isc = conf.includes(d);
1033 const col = DIM_COLORS[d];
1034 const cls = isc ? 'dim-pill conflict-pill' : 'dim-pill';
1035 const sty = isc ? '' : `color:${col};border-color:${col};background:${col}22`;
1036 return `<span class="${cls}" style="${sty}">${isc ? '⚡ ' : ''}${d}</span>`;
1037 }).join('') + '</div>';
1038 })() +
1039 `<div class="event-meta">` +
1040 (ev.commit_id ? `<span class="tag-commit">${escHtml(ev.commit_id)}</span>` : '') +
1041 `<span class="tag-time">${ev.duration_ms}ms</span>` +
1042 `</div>`;
1043
1044 list.appendChild(item);
1045 });
1046 }
1047
1048
1049 /* ===== Dimension Timeline ===== */
1050 function buildDimTimeline() {
1051 const matrix = document.getElementById('dim-matrix');
1052 if (!matrix) return;
1053 const sorted = topoSort(DATA.dag.commits);
1054
1055 // Commit ID header row
1056 const hrow = document.createElement('div');
1057 hrow.className = 'dim-matrix-row';
1058 const sp = document.createElement('div');
1059 sp.className = 'dim-label-cell';
1060 hrow.appendChild(sp);
1061 sorted.forEach(c => {
1062 const cell = document.createElement('div');
1063 cell.className = 'dim-commit-cell';
1064 cell.id = `dim-col-label-${c.short}`;
1065 cell.title = c.message;
1066 cell.textContent = c.short.slice(0,6);
1067 hrow.appendChild(cell);
1068 });
1069 matrix.appendChild(hrow);
1070
1071 // One row per dimension
1072 DIMS.forEach(dim => {
1073 const row = document.createElement('div');
1074 row.className = 'dim-matrix-row';
1075 const lbl = document.createElement('div');
1076 lbl.className = 'dim-label-cell';
1077 const dot = document.createElement('span');
1078 dot.className = 'dim-label-dot';
1079 dot.style.background = DIM_COLORS[dim];
1080 lbl.appendChild(dot);
1081 lbl.appendChild(document.createTextNode(dim.charAt(0).toUpperCase() + dim.slice(1)));
1082 row.appendChild(lbl);
1083
1084 sorted.forEach(c => {
1085 const dims = DIM_DATA[c.short] || [];
1086 const conf = DIM_CONFLICTS[c.short] || [];
1087 const active = dims.includes(dim);
1088 const isConf = conf.includes(dim);
1089 const col = DIM_COLORS[dim];
1090 const cell = document.createElement('div');
1091 cell.className = 'dim-cell';
1092 const inner = document.createElement('div');
1093 inner.className = 'dim-cell-inner' + (active ? ' active' : '') + (isConf ? ' conflict-dim' : '');
1094 inner.id = `dim-cell-${dim}-${c.short}`;
1095 if (active) {
1096 inner.style.background = col + '33';
1097 inner.style.color = col;
1098 inner.textContent = isConf ? '⚡' : '●';
1099 }
1100 cell.appendChild(inner);
1101 row.appendChild(cell);
1102 });
1103 matrix.appendChild(row);
1104 });
1105 }
1106
1107 function highlightDimColumn(shortId) {
1108 document.querySelectorAll('.dim-commit-cell.col-highlight, .dim-cell-inner.col-highlight')
1109 .forEach(el => el.classList.remove('col-highlight'));
1110 if (!shortId) return;
1111 const lbl = document.getElementById(`dim-col-label-${shortId}`);
1112 if (lbl) {
1113 lbl.classList.add('col-highlight');
1114 lbl.scrollIntoView({ behavior:'smooth', block:'nearest', inline:'center' });
1115 }
1116 DIMS.forEach(dim => {
1117 const cell = document.getElementById(`dim-cell-${dim}-${shortId}`);
1118 if (cell) cell.classList.add('col-highlight');
1119 });
1120 }
1121
1122 /* ===== Replay animation ===== */
1123 function revealStep(stepIdx) {
1124 if (stepIdx < 0 || stepIdx >= DATA.events.length) return;
1125
1126 const ev = DATA.events[stepIdx];
1127
1128 // Reveal all events up to this step
1129 for (let i = 0; i <= stepIdx; i++) {
1130 const el = document.getElementById(`ev-${i}`);
1131 if (el) el.classList.add('revealed');
1132 }
1133
1134 // Mark current as active (remove previous)
1135 document.querySelectorAll('.event-item.active').forEach(el => el.classList.remove('active'));
1136 const cur = document.getElementById(`ev-${stepIdx}`);
1137 if (cur) {
1138 cur.classList.add('active');
1139 cur.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
1140 }
1141
1142 // Highlight commit node
1143 document.querySelectorAll('.commit-node.highlighted').forEach(el => el.classList.remove('highlighted'));
1144 if (ev.commit_id) {
1145 const node = document.querySelector(`.commit-node[data-short="${ev.commit_id}"]`);
1146 if (node) {
1147 node.classList.add('highlighted');
1148 // Scroll DAG to show the node
1149 const transform = node.getAttribute('transform');
1150 if (transform) {
1151 const m = transform.match(/translate\\(([\\d.]+),([\\d.]+)\\)/);
1152 if (m) {
1153 const scroll = document.getElementById('dag-scroll');
1154 const y = parseFloat(m[2]);
1155 scroll.scrollTo({ top: Math.max(0, y - 200), behavior: 'smooth' });
1156 }
1157 }
1158 }
1159 }
1160
1161 // Highlight dimension matrix column
1162 highlightDimColumn(ev.commit_id || null);
1163
1164 // Update counter
1165 document.getElementById('step-counter').textContent =
1166 `Step ${stepIdx + 1} / ${DATA.events.length}`;
1167
1168 currentStep = stepIdx;
1169 }
1170
1171 function playTour() {
1172 if (isPlaying) return;
1173 isPlaying = true;
1174 document.getElementById('btn-play').textContent = '⏸ Pause';
1175
1176 function advance() {
1177 if (!isPlaying) return;
1178 const next = currentStep + 1;
1179 if (next >= DATA.events.length) {
1180 pauseTour();
1181 document.getElementById('btn-play').textContent = '✓ Done';
1182 return;
1183 }
1184 revealStep(next);
1185 playTimer = setTimeout(advance, PLAY_INTERVAL_MS);
1186 }
1187 advance();
1188 }
1189
1190 function pauseTour() {
1191 isPlaying = false;
1192 clearTimeout(playTimer);
1193 document.getElementById('btn-play').textContent = '▶ Play Tour';
1194 highlightDimColumn(null);
1195 }
1196
1197 function resetTour() {
1198 pauseTour();
1199 currentStep = -1;
1200 document.querySelectorAll('.event-item').forEach(el => {
1201 el.classList.remove('revealed','active');
1202 });
1203 document.querySelectorAll('.commit-node.highlighted').forEach(el => {
1204 el.classList.remove('highlighted');
1205 });
1206 document.getElementById('step-counter').textContent = '';
1207 document.getElementById('log-scroll').scrollTop = 0;
1208 document.getElementById('dag-scroll').scrollTop = 0;
1209 document.getElementById('btn-play').textContent = '▶ Play Tour';
1210 }
1211
1212 /* ===== Init ===== */
1213 document.addEventListener('DOMContentLoaded', () => {
1214 drawDAG();
1215 buildEventLog();
1216 buildDimTimeline();
1217
1218 document.getElementById('btn-play').addEventListener('click', () => {
1219 if (isPlaying) pauseTour(); else playTour();
1220 });
1221 document.getElementById('btn-reset').addEventListener('click', resetTour);
1222 });
1223 </script>
1224 </body>
1225 </html>
1226 """
1227
1228
1229 # ---------------------------------------------------------------------------
1230 # Main render function
1231 # ---------------------------------------------------------------------------
1232
1233
1234 def render(tour: dict, output_path: pathlib.Path) -> None:
1235 """Render the tour data into a self-contained HTML file."""
1236 print(" Rendering HTML visualization...")
1237 d3_script = _fetch_d3()
1238
1239 meta = tour.get("meta", {})
1240 stats = tour.get("stats", {})
1241
1242 # Format generated_at nicely
1243 gen_raw = meta.get("generated_at", "")
1244 try:
1245 from datetime import datetime, timezone
1246 dt = datetime.fromisoformat(gen_raw).astimezone(timezone.utc)
1247 gen_str = dt.strftime("%Y-%m-%d %H:%M UTC")
1248 except Exception:
1249 gen_str = gen_raw[:19]
1250
1251 html = _HTML_TEMPLATE
1252 html = html.replace("{{VERSION}}", str(meta.get("muse_version", "0.1.1")))
1253 html = html.replace("{{DOMAIN}}", str(meta.get("domain", "music")))
1254 html = html.replace("{{ELAPSED}}", str(meta.get("elapsed_s", "?")))
1255 html = html.replace("{{GENERATED_AT}}", gen_str)
1256 html = html.replace("{{COMMITS}}", str(stats.get("commits", 0)))
1257 html = html.replace("{{BRANCHES}}", str(stats.get("branches", 0)))
1258 html = html.replace("{{MERGES}}", str(stats.get("merges", 0)))
1259 html = html.replace("{{CONFLICTS}}", str(stats.get("conflicts_resolved", 0)))
1260 html = html.replace("{{OPS}}", str(stats.get("operations", 0)))
1261 html = html.replace("{{ARCH_HTML}}", _ARCH_HTML)
1262 html = html.replace("{{D3_SCRIPT}}", d3_script)
1263 html = html.replace("{{DATA_JSON}}", json.dumps(tour, separators=(",", ":")))
1264
1265 output_path.write_text(html, encoding="utf-8")
1266 size_kb = output_path.stat().st_size // 1024
1267 print(f" HTML written ({size_kb}KB) → {output_path}")
1268
1269
1270 # ---------------------------------------------------------------------------
1271 # Stand-alone entry point
1272 # ---------------------------------------------------------------------------
1273
1274 if __name__ == "__main__":
1275 import argparse
1276 parser = argparse.ArgumentParser(description="Render tour_de_force.json → HTML")
1277 parser.add_argument("json_file", help="Path to tour_de_force.json")
1278 parser.add_argument("--out", default=None, help="Output HTML path")
1279 args = parser.parse_args()
1280
1281 json_path = pathlib.Path(args.json_file)
1282 if not json_path.exists():
1283 print(f"❌ File not found: {json_path}", file=sys.stderr)
1284 sys.exit(1)
1285
1286 data = json.loads(json_path.read_text())
1287 out_path = pathlib.Path(args.out) if args.out else json_path.with_suffix(".html")
1288 render(data, out_path)
1289 print(f"Open: file://{out_path.resolve()}")