cgcardona / muse public
render_html.py python
1364 lines 47.1 KB
0940e0ff Add step forward/back buttons and keyboard shortcuts to tour 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 .btn:disabled { opacity: 0.35; cursor: not-allowed; }
281 .btn:disabled:hover { background: var(--bg3); }
282 .step-counter {
283 font-size: 11px;
284 font-family: var(--font-mono);
285 color: var(--text-mute);
286 min-width: 80px;
287 text-align: right;
288 }
289 .dag-scroll {
290 flex: 1;
291 overflow: auto;
292 padding: 20px;
293 }
294 #dag-svg { display: block; }
295 .branch-legend {
296 display: flex;
297 flex-wrap: wrap;
298 gap: 10px;
299 padding: 8px 20px;
300 border-top: 1px solid var(--border);
301 background: var(--bg2);
302 flex-shrink: 0;
303 }
304 .legend-item {
305 display: flex;
306 align-items: center;
307 gap: 6px;
308 font-size: 11px;
309 color: var(--text-mute);
310 }
311 .legend-dot {
312 width: 10px;
313 height: 10px;
314 border-radius: 50%;
315 flex-shrink: 0;
316 }
317
318 /* ---- Log panel ---- */
319 .log-panel {
320 display: flex;
321 flex-direction: column;
322 overflow: hidden;
323 background: var(--bg);
324 }
325 .log-header {
326 padding: 12px 16px;
327 border-bottom: 1px solid var(--border);
328 background: var(--bg2);
329 flex-shrink: 0;
330 }
331 .log-header h2 {
332 font-size: 13px;
333 font-weight: 600;
334 color: var(--text-mute);
335 text-transform: uppercase;
336 letter-spacing: 0.8px;
337 }
338 .log-scroll {
339 flex: 1;
340 overflow-y: auto;
341 padding: 0;
342 }
343 .act-header {
344 padding: 10px 16px 6px;
345 font-size: 11px;
346 font-weight: 700;
347 text-transform: uppercase;
348 letter-spacing: 1px;
349 color: var(--text-dim);
350 border-top: 1px solid var(--border);
351 margin-top: 4px;
352 position: sticky;
353 top: 0;
354 background: var(--bg);
355 z-index: 1;
356 }
357 .act-header:first-child { border-top: none; margin-top: 0; }
358 .event-item {
359 padding: 8px 16px;
360 border-bottom: 1px solid #1a1f26;
361 opacity: 0.3;
362 transition: opacity 0.3s, background 0.2s;
363 cursor: default;
364 }
365 .event-item.revealed { opacity: 1; }
366 .event-item.active { background: rgba(79,142,247,0.08); border-left: 2px solid var(--accent); }
367 .event-item.failed { border-left: 2px solid var(--red); }
368 .event-cmd {
369 font-family: var(--font-mono);
370 font-size: 12px;
371 color: var(--text);
372 margin-bottom: 3px;
373 }
374 .event-cmd .cmd-prefix { color: var(--text-dim); }
375 .event-cmd .cmd-name { color: var(--accent2); font-weight: 600; }
376 .event-cmd .cmd-args { color: var(--text); }
377 .event-output {
378 font-family: var(--font-mono);
379 font-size: 11px;
380 color: var(--text-mute);
381 white-space: pre-wrap;
382 word-break: break-all;
383 max-height: 80px;
384 overflow: hidden;
385 text-overflow: ellipsis;
386 }
387 .event-output.conflict { color: var(--red); }
388 .event-output.success { color: var(--green); }
389 .event-meta {
390 display: flex;
391 gap: 8px;
392 margin-top: 3px;
393 font-size: 10px;
394 color: var(--text-dim);
395 }
396 .tag-commit { background: rgba(79,142,247,0.15); color: var(--accent2); padding: 1px 5px; border-radius: 3px; font-family: var(--font-mono); }
397 .tag-time { color: var(--text-dim); }
398
399 /* ---- DAG SVG styles ---- */
400 .commit-node { cursor: pointer; }
401 .commit-node:hover circle { filter: brightness(1.3); }
402 .commit-node.highlighted circle { filter: brightness(1.5) drop-shadow(0 0 6px currentColor); }
403 .commit-label { font-size: 10px; fill: var(--text-mute); font-family: var(--font-mono); }
404 .commit-msg { font-size: 10px; fill: var(--text-mute); }
405 .commit-node.highlighted .commit-label,
406 .commit-node.highlighted .commit-msg { fill: var(--text); }
407 text { font-family: -apple-system, system-ui, sans-serif; }
408
409 /* ---- Architecture section ---- */
410 .arch-section {
411 background: var(--bg2);
412 border-top: 1px solid var(--border);
413 padding: 48px 40px;
414 }
415 .arch-inner { max-width: 1100px; margin: 0 auto; }
416 .arch-section h2 {
417 font-size: 22px;
418 font-weight: 700;
419 margin-bottom: 8px;
420 color: var(--text);
421 }
422 .arch-section .section-intro {
423 color: var(--text-mute);
424 max-width: 680px;
425 margin-bottom: 40px;
426 line-height: 1.7;
427 }
428 .arch-section .section-intro strong { color: var(--text); }
429 .arch-content {
430 display: grid;
431 grid-template-columns: 380px 1fr;
432 gap: 48px;
433 align-items: start;
434 }
435
436 /* Architecture flow diagram */
437 .arch-flow {
438 display: flex;
439 flex-direction: column;
440 align-items: center;
441 gap: 0;
442 }
443 .arch-row { width: 100%; display: flex; justify-content: center; }
444 .plugins-row { gap: 8px; flex-wrap: wrap; }
445 .arch-box {
446 border: 1px solid var(--border);
447 border-radius: var(--radius);
448 padding: 12px 16px;
449 background: var(--bg3);
450 width: 100%;
451 max-width: 340px;
452 transition: border-color 0.2s;
453 }
454 .arch-box:hover { border-color: var(--accent); }
455 .arch-box.cli { border-color: rgba(79,142,247,0.4); }
456 .arch-box.registry { border-color: rgba(188,140,255,0.3); }
457 .arch-box.core { border-color: rgba(63,185,80,0.3); background: rgba(63,185,80,0.05); }
458 .arch-box.protocol { border-color: rgba(79,142,247,0.5); background: rgba(79,142,247,0.05); }
459 .arch-box.plugin { max-width: 160px; width: auto; flex: 1; }
460 .arch-box.plugin.active { border-color: rgba(249,168,37,0.5); background: rgba(249,168,37,0.05); }
461 .arch-box.plugin.planned { opacity: 0.6; border-style: dashed; }
462 .box-title { font-weight: 600; font-size: 13px; color: var(--text); }
463 .box-sub { font-size: 11px; color: var(--text-mute); margin-top: 3px; }
464 .box-detail { font-size: 10px; color: var(--text-dim); margin-top: 4px; line-height: 1.5; }
465 .arch-connector {
466 display: flex;
467 flex-direction: column;
468 align-items: center;
469 height: 24px;
470 color: var(--border);
471 }
472 .connector-line { width: 1px; flex: 1; background: var(--border); }
473 .connector-arrow { font-size: 10px; }
474
475 /* Protocol table */
476 .protocol-table { border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
477 .proto-row {
478 display: grid;
479 grid-template-columns: 80px 220px 1fr;
480 gap: 0;
481 border-bottom: 1px solid var(--border);
482 }
483 .proto-row:last-child { border-bottom: none; }
484 .proto-row.header { background: var(--bg3); }
485 .proto-row > div { padding: 10px 14px; }
486 .proto-method {
487 font-family: var(--font-mono);
488 font-size: 12px;
489 color: var(--accent2);
490 font-weight: 600;
491 border-right: 1px solid var(--border);
492 }
493 .proto-sig {
494 font-family: var(--font-mono);
495 font-size: 11px;
496 color: var(--text-mute);
497 border-right: 1px solid var(--border);
498 word-break: break-all;
499 }
500 .proto-desc { font-size: 12px; color: var(--text-mute); }
501 .proto-row.header .proto-method,
502 .proto-row.header .proto-sig,
503 .proto-row.header .proto-desc {
504 font-family: var(--font-ui);
505 font-size: 11px;
506 font-weight: 700;
507 text-transform: uppercase;
508 letter-spacing: 0.6px;
509 color: var(--text-dim);
510 }
511
512 /* ---- Footer ---- */
513 footer {
514 background: var(--bg);
515 border-top: 1px solid var(--border);
516 padding: 16px 40px;
517 display: flex;
518 justify-content: space-between;
519 align-items: center;
520 font-size: 12px;
521 color: var(--text-dim);
522 }
523 footer a { color: var(--accent2); text-decoration: none; }
524 footer a:hover { text-decoration: underline; }
525
526 /* ---- Scrollbar ---- */
527 ::-webkit-scrollbar { width: 6px; height: 6px; }
528 ::-webkit-scrollbar-track { background: var(--bg); }
529 ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
530 ::-webkit-scrollbar-thumb:hover { background: var(--text-dim); }
531
532 /* ---- Tooltip ---- */
533 .tooltip {
534 position: fixed;
535 background: var(--bg2);
536 border: 1px solid var(--border);
537 border-radius: var(--radius);
538 padding: 10px 14px;
539 font-size: 12px;
540 pointer-events: none;
541 opacity: 0;
542 transition: opacity 0.15s;
543 z-index: 100;
544 max-width: 280px;
545 box-shadow: 0 8px 24px rgba(0,0,0,0.4);
546 }
547 .tooltip.visible { opacity: 1; }
548 .tip-id { font-family: var(--font-mono); font-size: 11px; color: var(--accent2); margin-bottom: 4px; }
549 .tip-msg { color: var(--text); margin-bottom: 4px; }
550 .tip-branch { font-size: 11px; margin-bottom: 4px; }
551 .tip-files { font-size: 11px; color: var(--text-mute); font-family: var(--font-mono); }
552
553 /* ---- Dimension dots on DAG nodes ---- */
554 .dim-dots { pointer-events: none; }
555
556 /* ---- Dimension State Matrix section ---- */
557 .dim-section {
558 background: var(--bg);
559 border-top: 2px solid var(--border);
560 padding: 28px 40px 32px;
561 }
562 .dim-inner { max-width: 1200px; margin: 0 auto; }
563 .dim-section-header { display:flex; align-items:baseline; gap:14px; margin-bottom:6px; }
564 .dim-section h2 { font-size:16px; font-weight:700; color:var(--text); }
565 .dim-section .dim-tagline { font-size:12px; color:var(--text-mute); }
566 .dim-matrix-wrap { overflow-x:auto; margin-top:18px; padding-bottom:4px; }
567 .dim-matrix { display:table; border-collapse:separate; border-spacing:0; min-width:100%; }
568 .dim-matrix-row { display:table-row; }
569 .dim-label-cell {
570 display:table-cell; padding:6px 14px 6px 0;
571 font-size:11px; font-weight:600; color:var(--text-mute);
572 text-transform:uppercase; letter-spacing:0.6px;
573 white-space:nowrap; vertical-align:middle; min-width:100px;
574 }
575 .dim-label-dot { display:inline-block; width:9px; height:9px; border-radius:50%; margin-right:6px; vertical-align:middle; }
576 .dim-cell { display:table-cell; padding:4px 3px; vertical-align:middle; text-align:center; min-width:46px; }
577 .dim-cell-inner {
578 width:38px; height:28px; border-radius:5px; margin:0 auto;
579 display:flex; align-items:center; justify-content:center;
580 font-size:11px; font-weight:700;
581 transition:transform 0.2s, box-shadow 0.2s;
582 cursor:default;
583 background:var(--bg3); border:1px solid transparent; color:transparent;
584 }
585 .dim-cell-inner.active { border-color:currentColor; }
586 .dim-cell-inner.conflict-dim { box-shadow:0 0 0 2px #f85149; }
587 .dim-cell-inner.col-highlight { transform:scaleY(1.12); box-shadow:0 0 14px 2px rgba(255,255,255,0.12); }
588 .dim-commit-cell {
589 display:table-cell; padding:8px 3px 0; text-align:center;
590 font-size:9px; font-family:var(--font-mono); color:var(--text-dim);
591 vertical-align:top; transition:color 0.2s;
592 }
593 .dim-commit-cell.col-highlight { color:var(--accent2); font-weight:700; }
594 .dim-commit-label { display:table-cell; padding-top:10px; vertical-align:top; }
595 .dim-legend { display:flex; gap:18px; margin-top:18px; flex-wrap:wrap; font-size:11px; color:var(--text-mute); }
596 .dim-legend-item { display:flex; align-items:center; gap:6px; }
597 .dim-legend-swatch { width:22px; height:14px; border-radius:3px; border:1px solid currentColor; display:inline-block; }
598 .dim-conflict-note {
599 margin-top:16px; padding:12px 16px;
600 background:rgba(248,81,73,0.08); border:1px solid rgba(248,81,73,0.25);
601 border-radius:6px; font-size:12px; color:var(--text-mute);
602 }
603 .dim-conflict-note strong { color:var(--red); }
604 .dim-conflict-note em { color:var(--green); font-style:normal; }
605
606 /* ---- Dimension pills in the operation log ---- */
607 .dim-pills { display:flex; flex-wrap:wrap; gap:3px; margin-top:4px; }
608 .dim-pill {
609 display:inline-block; padding:1px 6px; border-radius:10px;
610 font-size:9px; font-weight:700; letter-spacing:0.4px; text-transform:uppercase;
611 border:1px solid currentColor; opacity:0.85;
612 }
613 .dim-pill.conflict-pill { background:rgba(248,81,73,0.2); color:var(--red) !important; }
614 </style>
615 </head>
616 <body>
617
618 <header>
619 <div class="header-top">
620 <h1>muse</h1>
621 <span class="tagline">domain-agnostic version control for multidimensional state</span>
622 <span class="version-badge">v{{VERSION}} · {{DOMAIN}} domain · {{ELAPSED}}s</span>
623 </div>
624 <div class="stats-bar">
625 <div class="stat"><span class="stat-num">{{COMMITS}}</span><span class="stat-label">Commits</span></div>
626 <div class="stat-sep">·</div>
627 <div class="stat"><span class="stat-num">{{BRANCHES}}</span><span class="stat-label">Branches</span></div>
628 <div class="stat-sep">·</div>
629 <div class="stat"><span class="stat-num">{{MERGES}}</span><span class="stat-label">Merges</span></div>
630 <div class="stat-sep">·</div>
631 <div class="stat"><span class="stat-num">{{CONFLICTS}}</span><span class="stat-label">Conflicts Resolved</span></div>
632 <div class="stat-sep">·</div>
633 <div class="stat"><span class="stat-num">{{OPS}}</span><span class="stat-label">Operations</span></div>
634 </div>
635 </header>
636
637 <div class="main-container">
638 <div class="dag-panel">
639 <div class="dag-header">
640 <h2>Commit Graph</h2>
641 <div class="controls">
642 <button class="btn primary" id="btn-play">&#9654; Play Tour</button>
643 <button class="btn" id="btn-prev" title="Previous step (←)">&#9664;</button>
644 <button class="btn" id="btn-next" title="Next step (→)">&#9654;</button>
645 <button class="btn" id="btn-reset">&#8635; Reset</button>
646 <span class="step-counter" id="step-counter"></span>
647 </div>
648 </div>
649 <div class="dag-scroll" id="dag-scroll">
650 <svg id="dag-svg"></svg>
651 </div>
652 <div class="branch-legend" id="branch-legend"></div>
653 </div>
654
655 <div class="log-panel">
656 <div class="log-header"><h2>Operation Log</h2></div>
657 <div class="log-scroll" id="log-scroll">
658 <div id="event-list"></div>
659 </div>
660 </div>
661 </div>
662
663
664 <div class="dim-section">
665 <div class="dim-inner">
666 <div class="dim-section-header">
667 <h2>Dimension State Matrix</h2>
668 <span class="dim-tagline">
669 Unlike Git (binary file conflicts), Muse merges each orthogonal dimension independently —
670 only conflicting dimensions require human resolution.
671 </span>
672 </div>
673 <div class="dim-matrix-wrap">
674 <div class="dim-matrix" id="dim-matrix"></div>
675 </div>
676 <div class="dim-legend">
677 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(188,140,255,0.35);color:#bc8cff"></span> Melodic</div>
678 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(63,185,80,0.35);color:#3fb950"></span> Rhythmic</div>
679 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(88,166,255,0.35);color:#58a6ff"></span> Harmonic</div>
680 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(249,168,37,0.35);color:#f9a825"></span> Dynamic</div>
681 <div class="dim-legend-item"><span class="dim-legend-swatch" style="background:rgba(239,83,80,0.35);color:#ef5350"></span> Structural</div>
682 <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>
683 <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>
684 </div>
685 <div class="dim-conflict-note">
686 <strong>⚡ Merge conflict (shared-state.mid)</strong> — shared-state.mid had both-sides changes in
687 <strong style="color:#ef5350">structural</strong> (manual resolution required).
688 <em>✓ melodic auto-merged from left</em> · <em>✓ harmonic auto-merged from right</em> —
689 only 1 of 5 dimensions conflicted. Git would have flagged the entire file as a conflict.
690 </div>
691 </div>
692 </div>
693
694 <div class="arch-section">
695 <div class="arch-inner">
696 <h2>How Muse Works</h2>
697 <p class="section-intro">
698 Muse is a version control system for <strong>state</strong> — any multidimensional
699 state that can be snapshotted, diffed, and merged. The core engine provides
700 the DAG, content-addressed storage, branching, merging, time-travel, and
701 conflict resolution. A domain plugin implements <strong>5 methods</strong> and
702 gets everything else for free.
703 <br><br>
704 Music is the reference implementation. Genomics sequences, scientific simulation
705 frames, 3D spatial fields, and financial time-series are all the same pattern.
706 </p>
707 <div class="arch-content">
708 {{ARCH_HTML}}
709 </div>
710 </div>
711 </div>
712
713 <footer>
714 <span>Generated {{GENERATED_AT}} · {{ELAPSED}}s · {{OPS}} operations</span>
715 <span><a href="https://github.com/cgcardona/muse">github.com/cgcardona/muse</a></span>
716 </footer>
717
718 <div class="tooltip" id="tooltip">
719 <div class="tip-id" id="tip-id"></div>
720 <div class="tip-msg" id="tip-msg"></div>
721 <div class="tip-branch" id="tip-branch"></div>
722 <div class="tip-files" id="tip-files"></div>
723 <div id="tip-dims" style="margin-top:6px;font-size:10px;line-height:1.8"></div>
724 </div>
725
726 {{D3_SCRIPT}}
727
728 <script>
729 /* ===== Embedded tour data ===== */
730 const DATA = {{DATA_JSON}};
731
732 /* ===== Constants ===== */
733 const ROW_H = 62;
734 const COL_W = 90;
735 const PAD = { top: 30, left: 55, right: 160 };
736 const R_NODE = 11;
737 const BRANCH_ORDER = ['main','alpha','beta','gamma','conflict/left','conflict/right'];
738 const PLAY_INTERVAL_MS = 1200;
739
740 /* ===== Dimension data ===== */
741 const DIM_COLORS = {
742 melodic: '#bc8cff',
743 rhythmic: '#3fb950',
744 harmonic: '#58a6ff',
745 dynamic: '#f9a825',
746 structural: '#ef5350',
747 };
748 const DIMS = ['melodic','rhythmic','harmonic','dynamic','structural'];
749
750 // Commit message → dimension mapping (stable across re-runs, independent of hash)
751 function getDims(commit) {
752 const m = (commit.message || '').toLowerCase();
753 if (m.includes('root') || m.includes('initial state'))
754 return ['melodic','rhythmic','harmonic','dynamic','structural'];
755 if (m.includes('layer 1') || m.includes('rhythmic dimension'))
756 return ['rhythmic','structural'];
757 if (m.includes('layer 2') || m.includes('harmonic dimension'))
758 return ['harmonic','structural'];
759 if (m.includes('texture pattern a') || m.includes('sparse'))
760 return ['melodic','rhythmic'];
761 if (m.includes('texture pattern b') || m.includes('dense'))
762 return ['melodic','dynamic'];
763 if (m.includes('syncopated'))
764 return ['rhythmic','dynamic'];
765 if (m.includes('descending'))
766 return ['melodic','harmonic'];
767 if (m.includes('ascending'))
768 return ['melodic'];
769 if (m.includes("merge branch 'beta'"))
770 return ['rhythmic','dynamic'];
771 if (m.includes('left:') || m.includes('version a'))
772 return ['melodic','structural'];
773 if (m.includes('right:') || m.includes('version b'))
774 return ['harmonic','structural'];
775 if (m.includes('resolve') || m.includes('reconciled'))
776 return ['structural'];
777 if (m.includes('cherry-pick') || m.includes('cherry pick'))
778 return ['melodic'];
779 if (m.includes('revert'))
780 return ['melodic'];
781 return [];
782 }
783
784 function getConflicts(commit) {
785 const m = (commit.message || '').toLowerCase();
786 if (m.includes('resolve') && m.includes('reconciled')) return ['structural'];
787 return [];
788 }
789
790 // Build per-short-ID lookup tables once the DATA is available (populated at init)
791 const DIM_DATA = {};
792 const DIM_CONFLICTS = {};
793 function _initDimMaps() {
794 DATA.dag.commits.forEach(c => {
795 DIM_DATA[c.short] = getDims(c);
796 DIM_CONFLICTS[c.short] = getConflicts(c);
797 });
798 // Also key by the short prefix used in events (some may be truncated)
799 DATA.events.forEach(ev => {
800 if (ev.commit_id && !DIM_DATA[ev.commit_id]) {
801 const full = DATA.dag.commits.find(c => c.short.startsWith(ev.commit_id) || ev.commit_id.startsWith(c.short));
802 if (full) {
803 DIM_DATA[ev.commit_id] = getDims(full);
804 DIM_CONFLICTS[ev.commit_id] = getConflicts(full);
805 }
806 }
807 });
808 }
809
810
811 /* ===== State ===== */
812 let currentStep = -1;
813 let isPlaying = false;
814 let playTimer = null;
815
816 /* ===== Utilities ===== */
817 function escHtml(s) {
818 return String(s)
819 .replace(/&/g,'&amp;')
820 .replace(/</g,'&lt;')
821 .replace(/>/g,'&gt;')
822 .replace(/"/g,'&quot;');
823 }
824
825 /* ===== Topological sort ===== */
826 function topoSort(commits) {
827 const map = new Map(commits.map(c => [c.id, c]));
828 const visited = new Set();
829 const result = [];
830 function visit(id) {
831 if (visited.has(id)) return;
832 visited.add(id);
833 const c = map.get(id);
834 if (!c) return;
835 (c.parents || []).forEach(pid => visit(pid));
836 result.push(c);
837 }
838 commits.forEach(c => visit(c.id));
839 // Oldest commit at row 0 (top of DAG); newest at the bottom so the DAG
840 // scrolls down in sync with the operation log during playback.
841 return result;
842 }
843
844 /* ===== Layout ===== */
845 function computeLayout(commits) {
846 const sorted = topoSort(commits);
847 const branchCols = {};
848 let nextCol = 0;
849 // Assign columns in BRANCH_ORDER first, then any extras
850 BRANCH_ORDER.forEach(b => { branchCols[b] = nextCol++; });
851 commits.forEach(c => {
852 if (!(c.branch in branchCols)) branchCols[c.branch] = nextCol++;
853 });
854 const numCols = nextCol;
855 const positions = new Map();
856 sorted.forEach((c, i) => {
857 positions.set(c.id, {
858 x: PAD.left + (branchCols[c.branch] || 0) * COL_W,
859 y: PAD.top + i * ROW_H,
860 row: i,
861 col: branchCols[c.branch] || 0,
862 });
863 });
864 const svgW = PAD.left + numCols * COL_W + PAD.right;
865 const svgH = PAD.top + sorted.length * ROW_H + PAD.top;
866 return { sorted, positions, branchCols, svgW, svgH };
867 }
868
869 /* ===== Draw DAG ===== */
870 function drawDAG() {
871 const { dag, dag: { commits, branches } } = DATA;
872 if (!commits.length) return;
873
874 const layout = computeLayout(commits);
875 const { sorted, positions, svgW, svgH } = layout;
876 const branchColor = new Map(branches.map(b => [b.name, b.color]));
877 const commitMap = new Map(commits.map(c => [c.id, c]));
878
879 const svg = d3.select('#dag-svg')
880 .attr('width', svgW)
881 .attr('height', svgH);
882
883 // ---- Edges ----
884 const edgeG = svg.append('g').attr('class', 'edges');
885 sorted.forEach(commit => {
886 const pos = positions.get(commit.id);
887 (commit.parents || []).forEach((pid, pIdx) => {
888 const ppos = positions.get(pid);
889 if (!pos || !ppos) return;
890 const color = pIdx === 0
891 ? (branchColor.get(commit.branch) || '#555')
892 : (branchColor.get(commitMap.get(pid)?.branch || '') || '#555');
893
894 let pathStr;
895 if (Math.abs(pos.x - ppos.x) < 4) {
896 // Same column → straight line
897 pathStr = `M${pos.x},${pos.y} L${ppos.x},${ppos.y}`;
898 } else {
899 // Different columns → S-curve bezier
900 const mid = (pos.y + ppos.y) / 2;
901 pathStr = `M${pos.x},${pos.y} C${pos.x},${mid} ${ppos.x},${mid} ${ppos.x},${ppos.y}`;
902 }
903 edgeG.append('path')
904 .attr('d', pathStr)
905 .attr('stroke', color)
906 .attr('stroke-width', 1.8)
907 .attr('fill', 'none')
908 .attr('opacity', 0.45)
909 .attr('class', `edge-from-${commit.id.slice(0,8)}`);
910 });
911 });
912
913 // ---- Nodes ----
914 const nodeG = svg.append('g').attr('class', 'nodes');
915 const tooltip = document.getElementById('tooltip');
916
917 sorted.forEach(commit => {
918 const pos = positions.get(commit.id);
919 if (!pos) return;
920 const color = branchColor.get(commit.branch) || '#78909c';
921 const isMerge = (commit.parents || []).length >= 2;
922
923 const g = nodeG.append('g')
924 .attr('class', 'commit-node')
925 .attr('data-id', commit.id)
926 .attr('data-short', commit.short)
927 .attr('transform', `translate(${pos.x},${pos.y})`);
928
929 if (isMerge) {
930 g.append('circle')
931 .attr('r', R_NODE + 6)
932 .attr('fill', 'none')
933 .attr('stroke', color)
934 .attr('stroke-width', 1.5)
935 .attr('opacity', 0.35);
936 }
937
938 g.append('circle')
939 .attr('r', R_NODE)
940 .attr('fill', color)
941 .attr('stroke', '#0d1117')
942 .attr('stroke-width', 2);
943
944 // Short ID
945 g.append('text')
946 .attr('x', R_NODE + 7)
947 .attr('y', 0)
948 .attr('dy', '0.35em')
949 .attr('class', 'commit-label')
950 .text(commit.short);
951
952 // Message (truncated)
953 const maxLen = 38;
954 const msg = commit.message.length > maxLen
955 ? commit.message.slice(0, maxLen) + '…'
956 : commit.message;
957 g.append('text')
958 .attr('x', R_NODE + 7)
959 .attr('y', 13)
960 .attr('class', 'commit-msg')
961 .text(msg);
962
963
964 // Dimension dots below node
965 const dims = DIM_DATA[commit.short] || [];
966 if (dims.length > 0) {
967 const dotR = 4, dotSp = 11;
968 const totalW = (DIMS.length - 1) * dotSp;
969 const dotsG = g.append('g')
970 .attr('class', 'dim-dots')
971 .attr('transform', `translate(${-totalW/2},${R_NODE + 9})`);
972 DIMS.forEach((dim, di) => {
973 const active = dims.includes(dim);
974 const isConf = (DIM_CONFLICTS[commit.short] || []).includes(dim);
975 dotsG.append('circle')
976 .attr('cx', di * dotSp).attr('cy', 0).attr('r', dotR)
977 .attr('fill', active ? DIM_COLORS[dim] : '#21262d')
978 .attr('stroke', isConf ? '#f85149' : (active ? DIM_COLORS[dim] : '#30363d'))
979 .attr('stroke-width', isConf ? 1.5 : 0.8)
980 .attr('opacity', active ? 1 : 0.35);
981 });
982 }
983
984 // Hover tooltip
985 g.on('mousemove', (event) => {
986 tooltip.classList.add('visible');
987 document.getElementById('tip-id').textContent = commit.id;
988 document.getElementById('tip-msg').textContent = commit.message;
989 document.getElementById('tip-branch').innerHTML =
990 `<span style="color:${color}">⬤</span> ${commit.branch}`;
991 document.getElementById('tip-files').textContent =
992 commit.files.length
993 ? commit.files.join('\\n')
994 : '(empty snapshot)';
995 const tipDims = DIM_DATA[commit.short] || [];
996 const tipConf = DIM_CONFLICTS[commit.short] || [];
997 const tipDimEl = document.getElementById('tip-dims');
998 if (tipDimEl) {
999 tipDimEl.innerHTML = tipDims.length
1000 ? tipDims.map(d => {
1001 const c = tipConf.includes(d);
1002 return `<span style="color:${DIM_COLORS[d]};margin-right:6px">● ${d}${c?' ⚡':''}</span>`;
1003 }).join('')
1004 : '';
1005 }
1006 tooltip.style.left = (event.clientX + 12) + 'px';
1007 tooltip.style.top = (event.clientY - 10) + 'px';
1008 }).on('mouseleave', () => {
1009 tooltip.classList.remove('visible');
1010 });
1011 });
1012
1013 // ---- Branch legend ----
1014 const legend = document.getElementById('branch-legend');
1015 DATA.dag.branches.forEach(b => {
1016 const item = document.createElement('div');
1017 item.className = 'legend-item';
1018 item.innerHTML =
1019 `<span class="legend-dot" style="background:${b.color}"></span>` +
1020 `<span>${escHtml(b.name)}</span>`;
1021 legend.appendChild(item);
1022 });
1023 }
1024
1025 /* ===== Event log ===== */
1026 function buildEventLog() {
1027 const list = document.getElementById('event-list');
1028 let lastAct = -1;
1029
1030 DATA.events.forEach((ev, idx) => {
1031 if (ev.act !== lastAct) {
1032 lastAct = ev.act;
1033 const hdr = document.createElement('div');
1034 hdr.className = 'act-header';
1035 hdr.textContent = `Act ${ev.act} — ${ev.act_title}`;
1036 list.appendChild(hdr);
1037 }
1038
1039 const item = document.createElement('div');
1040 item.className = 'event-item';
1041 item.id = `ev-${idx}`;
1042 if (ev.exit_code !== 0 && ev.output.toLowerCase().includes('conflict')) {
1043 item.classList.add('failed');
1044 }
1045
1046 // Parse cmd into parts
1047 const parts = ev.cmd.split(' ');
1048 const cmdName = parts.slice(0,2).join(' ');
1049 const cmdArgs = parts.slice(2).join(' ');
1050
1051 // Determine output class
1052 let outClass = '';
1053 if (ev.output.toLowerCase().includes('conflict')) outClass = 'conflict';
1054 else if (ev.exit_code === 0 && ev.commit_id) outClass = 'success';
1055
1056 // Trim long output
1057 const outLines = ev.output.split('\\n').slice(0, 5).join('\\n');
1058
1059 item.innerHTML =
1060 `<div class="event-cmd">` +
1061 `<span class="cmd-prefix">$ </span>` +
1062 `<span class="cmd-name">${escHtml(cmdName)}</span>` +
1063 (cmdArgs ? ` <span class="cmd-args">${escHtml(cmdArgs.slice(0, 60))}${cmdArgs.length>60?'…':''}</span>` : '') +
1064 `</div>` +
1065 (outLines
1066 ? `<div class="event-output ${outClass}">${escHtml(outLines)}</div>`
1067 : '') +
1068 (() => {
1069 if (!ev.commit_id) return '';
1070 const dims = DIM_DATA[ev.commit_id] || [];
1071 const conf = DIM_CONFLICTS[ev.commit_id] || [];
1072 if (!dims.length) return '';
1073 return '<div class="dim-pills">' + dims.map(d => {
1074 const isc = conf.includes(d);
1075 const col = DIM_COLORS[d];
1076 const cls = isc ? 'dim-pill conflict-pill' : 'dim-pill';
1077 const sty = isc ? '' : `color:${col};border-color:${col};background:${col}22`;
1078 return `<span class="${cls}" style="${sty}">${isc ? '⚡ ' : ''}${d}</span>`;
1079 }).join('') + '</div>';
1080 })() +
1081 `<div class="event-meta">` +
1082 (ev.commit_id ? `<span class="tag-commit">${escHtml(ev.commit_id)}</span>` : '') +
1083 `<span class="tag-time">${ev.duration_ms}ms</span>` +
1084 `</div>`;
1085
1086 list.appendChild(item);
1087 });
1088 }
1089
1090
1091 /* ===== Dimension Timeline ===== */
1092 function buildDimTimeline() {
1093 const matrix = document.getElementById('dim-matrix');
1094 if (!matrix) return;
1095 const sorted = topoSort(DATA.dag.commits);
1096
1097 // Commit ID header row
1098 const hrow = document.createElement('div');
1099 hrow.className = 'dim-matrix-row';
1100 const sp = document.createElement('div');
1101 sp.className = 'dim-label-cell';
1102 hrow.appendChild(sp);
1103 sorted.forEach(c => {
1104 const cell = document.createElement('div');
1105 cell.className = 'dim-commit-cell';
1106 cell.id = `dim-col-label-${c.short}`;
1107 cell.title = c.message;
1108 cell.textContent = c.short.slice(0,6);
1109 hrow.appendChild(cell);
1110 });
1111 matrix.appendChild(hrow);
1112
1113 // One row per dimension
1114 DIMS.forEach(dim => {
1115 const row = document.createElement('div');
1116 row.className = 'dim-matrix-row';
1117 const lbl = document.createElement('div');
1118 lbl.className = 'dim-label-cell';
1119 const dot = document.createElement('span');
1120 dot.className = 'dim-label-dot';
1121 dot.style.background = DIM_COLORS[dim];
1122 lbl.appendChild(dot);
1123 lbl.appendChild(document.createTextNode(dim.charAt(0).toUpperCase() + dim.slice(1)));
1124 row.appendChild(lbl);
1125
1126 sorted.forEach(c => {
1127 const dims = DIM_DATA[c.short] || [];
1128 const conf = DIM_CONFLICTS[c.short] || [];
1129 const active = dims.includes(dim);
1130 const isConf = conf.includes(dim);
1131 const col = DIM_COLORS[dim];
1132 const cell = document.createElement('div');
1133 cell.className = 'dim-cell';
1134 const inner = document.createElement('div');
1135 inner.className = 'dim-cell-inner' + (active ? ' active' : '') + (isConf ? ' conflict-dim' : '');
1136 inner.id = `dim-cell-${dim}-${c.short}`;
1137 if (active) {
1138 inner.style.background = col + '33';
1139 inner.style.color = col;
1140 inner.textContent = isConf ? '⚡' : '●';
1141 }
1142 cell.appendChild(inner);
1143 row.appendChild(cell);
1144 });
1145 matrix.appendChild(row);
1146 });
1147 }
1148
1149 function highlightDimColumn(shortId) {
1150 document.querySelectorAll('.dim-commit-cell.col-highlight, .dim-cell-inner.col-highlight')
1151 .forEach(el => el.classList.remove('col-highlight'));
1152 if (!shortId) return;
1153 const lbl = document.getElementById(`dim-col-label-${shortId}`);
1154 if (lbl) {
1155 lbl.classList.add('col-highlight');
1156 lbl.scrollIntoView({ behavior:'smooth', block:'nearest', inline:'center' });
1157 }
1158 DIMS.forEach(dim => {
1159 const cell = document.getElementById(`dim-cell-${dim}-${shortId}`);
1160 if (cell) cell.classList.add('col-highlight');
1161 });
1162 }
1163
1164 /* ===== Replay animation ===== */
1165 function revealStep(stepIdx) {
1166 if (stepIdx < 0 || stepIdx >= DATA.events.length) return;
1167
1168 const ev = DATA.events[stepIdx];
1169
1170 // Reveal all events up to this step
1171 for (let i = 0; i <= stepIdx; i++) {
1172 const el = document.getElementById(`ev-${i}`);
1173 if (el) el.classList.add('revealed');
1174 }
1175
1176 // Mark current as active (remove previous)
1177 document.querySelectorAll('.event-item.active').forEach(el => el.classList.remove('active'));
1178 const cur = document.getElementById(`ev-${stepIdx}`);
1179 if (cur) {
1180 cur.classList.add('active');
1181 cur.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
1182 }
1183
1184 // Highlight commit node
1185 document.querySelectorAll('.commit-node.highlighted').forEach(el => el.classList.remove('highlighted'));
1186 if (ev.commit_id) {
1187 const node = document.querySelector(`.commit-node[data-short="${ev.commit_id}"]`);
1188 if (node) {
1189 node.classList.add('highlighted');
1190 // Scroll DAG to show the node
1191 const transform = node.getAttribute('transform');
1192 if (transform) {
1193 const m = transform.match(/translate\\(([\\d.]+),([\\d.]+)\\)/);
1194 if (m) {
1195 const scroll = document.getElementById('dag-scroll');
1196 const y = parseFloat(m[2]);
1197 scroll.scrollTo({ top: Math.max(0, y - 200), behavior: 'smooth' });
1198 }
1199 }
1200 }
1201 }
1202
1203 // Highlight dimension matrix column
1204 highlightDimColumn(ev.commit_id || null);
1205
1206 // Update counter and step button states
1207 document.getElementById('step-counter').textContent =
1208 `Step ${stepIdx + 1} / ${DATA.events.length}`;
1209 document.getElementById('btn-prev').disabled = (stepIdx === 0);
1210 document.getElementById('btn-next').disabled = (stepIdx === DATA.events.length - 1);
1211
1212 currentStep = stepIdx;
1213 }
1214
1215 function playTour() {
1216 if (isPlaying) return;
1217 isPlaying = true;
1218 document.getElementById('btn-play').textContent = '⏸ Pause';
1219
1220 function advance() {
1221 if (!isPlaying) return;
1222 const next = currentStep + 1;
1223 if (next >= DATA.events.length) {
1224 pauseTour();
1225 document.getElementById('btn-play').textContent = '✓ Done';
1226 return;
1227 }
1228 revealStep(next);
1229 playTimer = setTimeout(advance, PLAY_INTERVAL_MS);
1230 }
1231 advance();
1232 }
1233
1234 function pauseTour() {
1235 isPlaying = false;
1236 clearTimeout(playTimer);
1237 document.getElementById('btn-play').textContent = '▶ Play Tour';
1238 highlightDimColumn(null);
1239 }
1240
1241 function resetTour() {
1242 pauseTour();
1243 currentStep = -1;
1244 document.querySelectorAll('.event-item').forEach(el => {
1245 el.classList.remove('revealed','active');
1246 });
1247 document.querySelectorAll('.commit-node.highlighted').forEach(el => {
1248 el.classList.remove('highlighted');
1249 });
1250 document.getElementById('step-counter').textContent = '';
1251 document.getElementById('log-scroll').scrollTop = 0;
1252 document.getElementById('dag-scroll').scrollTop = 0;
1253 document.getElementById('btn-play').textContent = '▶ Play Tour';
1254 document.getElementById('btn-prev').disabled = true;
1255 document.getElementById('btn-next').disabled = false;
1256 highlightDimColumn(null);
1257 }
1258
1259 /* ===== Init ===== */
1260 document.addEventListener('DOMContentLoaded', () => {
1261 _initDimMaps();
1262 drawDAG();
1263 buildEventLog();
1264 buildDimTimeline();
1265
1266 document.getElementById('btn-prev').disabled = true; // nothing to go back to yet
1267
1268 document.getElementById('btn-play').addEventListener('click', () => {
1269 if (isPlaying) pauseTour(); else playTour();
1270 });
1271 document.getElementById('btn-prev').addEventListener('click', () => {
1272 pauseTour();
1273 if (currentStep > 0) revealStep(currentStep - 1);
1274 });
1275 document.getElementById('btn-next').addEventListener('click', () => {
1276 pauseTour();
1277 if (currentStep < DATA.events.length - 1) revealStep(currentStep + 1);
1278 });
1279 document.getElementById('btn-reset').addEventListener('click', resetTour);
1280
1281 // Keyboard shortcuts: ← → for step, Space for play/pause
1282 document.addEventListener('keydown', (e) => {
1283 if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
1284 if (e.key === 'ArrowLeft') {
1285 e.preventDefault();
1286 pauseTour();
1287 if (currentStep > 0) revealStep(currentStep - 1);
1288 } else if (e.key === 'ArrowRight') {
1289 e.preventDefault();
1290 pauseTour();
1291 if (currentStep < DATA.events.length - 1) revealStep(currentStep + 1);
1292 } else if (e.key === ' ') {
1293 e.preventDefault();
1294 if (isPlaying) pauseTour(); else playTour();
1295 }
1296 });
1297 });
1298 </script>
1299 </body>
1300 </html>
1301 """
1302
1303
1304 # ---------------------------------------------------------------------------
1305 # Main render function
1306 # ---------------------------------------------------------------------------
1307
1308
1309 def render(tour: dict, output_path: pathlib.Path) -> None:
1310 """Render the tour data into a self-contained HTML file."""
1311 print(" Rendering HTML visualization...")
1312 d3_script = _fetch_d3()
1313
1314 meta = tour.get("meta", {})
1315 stats = tour.get("stats", {})
1316
1317 # Format generated_at nicely
1318 gen_raw = meta.get("generated_at", "")
1319 try:
1320 from datetime import datetime, timezone
1321 dt = datetime.fromisoformat(gen_raw).astimezone(timezone.utc)
1322 gen_str = dt.strftime("%Y-%m-%d %H:%M UTC")
1323 except Exception:
1324 gen_str = gen_raw[:19]
1325
1326 html = _HTML_TEMPLATE
1327 html = html.replace("{{VERSION}}", str(meta.get("muse_version", "0.1.1")))
1328 html = html.replace("{{DOMAIN}}", str(meta.get("domain", "music")))
1329 html = html.replace("{{ELAPSED}}", str(meta.get("elapsed_s", "?")))
1330 html = html.replace("{{GENERATED_AT}}", gen_str)
1331 html = html.replace("{{COMMITS}}", str(stats.get("commits", 0)))
1332 html = html.replace("{{BRANCHES}}", str(stats.get("branches", 0)))
1333 html = html.replace("{{MERGES}}", str(stats.get("merges", 0)))
1334 html = html.replace("{{CONFLICTS}}", str(stats.get("conflicts_resolved", 0)))
1335 html = html.replace("{{OPS}}", str(stats.get("operations", 0)))
1336 html = html.replace("{{ARCH_HTML}}", _ARCH_HTML)
1337 html = html.replace("{{D3_SCRIPT}}", d3_script)
1338 html = html.replace("{{DATA_JSON}}", json.dumps(tour, separators=(",", ":")))
1339
1340 output_path.write_text(html, encoding="utf-8")
1341 size_kb = output_path.stat().st_size // 1024
1342 print(f" HTML written ({size_kb}KB) → {output_path}")
1343
1344
1345 # ---------------------------------------------------------------------------
1346 # Stand-alone entry point
1347 # ---------------------------------------------------------------------------
1348
1349 if __name__ == "__main__":
1350 import argparse
1351 parser = argparse.ArgumentParser(description="Render tour_de_force.json → HTML")
1352 parser.add_argument("json_file", help="Path to tour_de_force.json")
1353 parser.add_argument("--out", default=None, help="Output HTML path")
1354 args = parser.parse_args()
1355
1356 json_path = pathlib.Path(args.json_file)
1357 if not json_path.exists():
1358 print(f"❌ File not found: {json_path}", file=sys.stderr)
1359 sys.exit(1)
1360
1361 data = json.loads(json_path.read_text())
1362 out_path = pathlib.Path(args.out) if args.out else json_path.with_suffix(".html")
1363 render(data, out_path)
1364 print(f"Open: file://{out_path.resolve()}")