File size: 86,143 Bytes
67fee72 dc38062 67fee72 dc38062 67fee72 dc38062 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 eb43738 99cc3c2 67fee72 67527e5 67fee72 973eb07 67fee72 67527e5 67fee72 67527e5 67fee72 67527e5 67fee72 67527e5 67fee72 973eb07 67fee72 973eb07 67527e5 67fee72 67527e5 67fee72 67527e5 67fee72 99cc3c2 67fee72 973eb07 67fee72 973eb07 67fee72 973eb07 99cc3c2 67fee72 99cc3c2 dc38062 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 67527e5 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 99cc3c2 67fee72 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 | <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sodium peroxide (Na2O2): how Mat2Bot got there</title><style>/* Mat2Bot Trace viewer. Reads trace.json; draws nothing it does not hold. Light and dark; phone first. */
:root{--bg:#f5f7fb;--fg:#0f172a;--muted:#475569;--line:#e2e8f0;--card:#ffffff;--head:#f1f5f9;--accent:#1d4ed8;--hl:#fff4cc;
--ok:#15803d;--warn:#b45309;--bad:#b91c1c;--off:#64748b;--radius:10px}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#0b1220;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--card:#111827;--head:#0f1a2e;--accent:#60a5fa;--hl:#3b3417;
--ok:#4ade80;--warn:#fbbf24;--bad:#f87171;--off:#94a3b8}}
:root[data-theme="dark"]{--bg:#0b1220;--fg:#e2e8f0;--muted:#94a3b8;--line:#1e293b;--card:#111827;--head:#0f1a2e;--accent:#60a5fa;--hl:#3b3417;
--ok:#4ade80;--warn:#fbbf24;--bad:#f87171;--off:#94a3b8}
*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
a{color:var(--accent)}button{font:inherit;cursor:pointer}
#trace-app{max-width:1200px;margin:0 auto;padding:16px 16px 48px}
.tv-top{display:flex;flex-wrap:wrap;gap:.5em 1.2em;align-items:baseline;margin-bottom:.4em}
.tv-top h1{font-size:1.25rem;margin:0}.tv-top nav a{margin-right:1em;text-decoration:none}
.tv-sub{color:var(--muted);font-size:.9rem;margin:0 0 1em;max-width:90ch}
.tv-tabs{display:flex;gap:.4em;flex-wrap:wrap;margin:.6em 0 1em}
.tv-tabs button{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:.35em .9em}
.tv-tabs button[aria-current="page"]{background:var(--accent);color:var(--bg);border-color:var(--accent)}
.tv-crumb{font-size:.9rem;color:var(--muted);margin-bottom:.6em}.tv-crumb a{text-decoration:none}
/* overview: the stages */
.tv-stages{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.6em}
.tv-stage{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:.7em .8em;text-align:left;color:var(--fg);
display:flex;flex-direction:column;gap:.35em;min-height:9.5em}
.tv-stage:hover,.tv-stage:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
.tv-stage .n{font-size:.75rem;color:var(--muted);letter-spacing:.04em}.tv-stage b{font-size:1rem}
.tv-stage .sum{font-size:.84rem;color:var(--muted);margin:0}.tv-stage .sum li{list-style:none}
.tv-stage ul{margin:0;padding:0}
.chip{display:inline-block;font-size:.76rem;padding:.1em .55em;border-radius:999px;border:1px solid var(--line);background:var(--head);
white-space:nowrap;line-height:1.5}
.chip.ok{border-color:var(--ok);color:var(--ok)}.chip.warn{border-color:var(--warn);color:var(--warn)}.chip.bad{border-color:var(--bad);color:var(--bad)}
.chip.off{border-color:var(--off);color:var(--off)}.chip.acc{border-color:var(--accent);color:var(--accent)}
.tv-legend{display:flex;flex-wrap:wrap;gap:.4em 1em;font-size:.82rem;color:var(--muted);margin:1em 0}
.tv-legend span{display:inline-flex;align-items:center;gap:.35em}
.tv-legend i{display:inline-block;width:22px;height:0;border-top:2px solid var(--accent)}
.tv-legend i.dash{border-top-style:dashed}.tv-legend i.dot{border-top-style:dotted}.tv-legend i.bad{border-color:var(--bad)}
.tv-legend i.ok{border-color:var(--ok)}.tv-legend i.muted{border-color:var(--off)}
/* timeline */
.tv-timeline{margin-top:1.4em}.tv-timeline h2{font-size:1.05rem;margin:.2em 0 .5em}
.tv-events{display:grid;gap:.3em;margin:0;padding:0;list-style:none}
.tv-events li{display:grid;grid-template-columns:2.2em 5.5em 1fr auto;gap:.6em;align-items:baseline;font-size:.9rem;border-bottom:1px solid var(--line);
padding:.3em 0}
.tv-events li .seq{color:var(--muted);font-variant-numeric:tabular-nums}.tv-events li .msg{color:var(--muted);font-size:.84rem;display:block}
.tv-events li.skipped{opacity:.75}
/* component view */
.tv-comp{position:relative}
.tv-groups{display:grid;gap:1em}
.tv-group h3{font-size:.95rem;margin:.6em 0 .4em;color:var(--accent)}
.tv-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:.6em;position:relative;z-index:1}
.tv-card{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:.55em .7em;display:flex;flex-direction:column;gap:.3em;
font-size:.9rem}
.tv-card.hl{background:var(--hl);border-color:var(--warn)}
.tv-card.sel{outline:2px solid var(--accent)}
.tv-card .k{font-size:.72rem;color:var(--muted);letter-spacing:.04em;text-transform:uppercase}
.tv-card .lbl{text-align:left;background:none;border:0;padding:0;color:var(--fg);font:inherit;line-height:1.4;overflow-wrap:anywhere}
.tv-card .lbl:hover{color:var(--accent)}
.tv-card .chips{display:flex;flex-wrap:wrap;gap:.3em}
.tv-card .acts{display:flex;flex-wrap:wrap;gap:.3em;margin-top:.1em}
.tv-card .acts button,.tv-card .acts a{font-size:.78rem;border:1px solid var(--line);background:var(--head);color:var(--fg);border-radius:6px;
padding:.15em .5em;text-decoration:none}
.tv-card .rel{font-size:.8rem;color:var(--muted)}.tv-card .rel a{text-decoration:none}
.tv-kids{margin:.3em 0 0 .6em;padding-left:.6em;border-left:2px solid var(--line);display:grid;gap:.4em}
svg.tv-edges{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:0;overflow:visible}
svg.tv-edges path{fill:none;stroke:var(--accent);stroke-width:1.5;opacity:.55}
svg.tv-edges path.depends_on{stroke:var(--off)}svg.tv-edges path.refuted_by{stroke:var(--bad);stroke-dasharray:5 4}
svg.tv-edges path.resolved_by{stroke:var(--ok);stroke-dasharray:2 3}svg.tv-edges path.rejected_for{stroke:var(--bad)}
svg.tv-edges path.requires_equipment{stroke:var(--bad);stroke-dasharray:6 3}svg.tv-edges path.mapped_to{stroke:var(--off);stroke-dasharray:2 3}
svg.tv-edges path.hl{opacity:1;stroke-width:3}
.tv-empty{color:var(--muted);font-style:italic}
/* compare */
.tv-compare{margin:1em 0;border:1px solid var(--line);border-radius:var(--radius);padding:.6em .9em;background:var(--card);overflow-x:auto}
.tv-compare table{border-collapse:collapse;font-size:.88rem;width:100%}
.tv-compare th,.tv-compare td{text-align:left;vertical-align:top;padding:.35em .5em;border-bottom:1px solid var(--line)}
.tv-compare th{background:var(--head)}
/* provenance panel */
.tv-panel{position:fixed;top:0;right:0;height:100%;width:min(460px,100%);background:var(--card);border-left:1px solid var(--line);box-shadow:-6px 0 20px rgba(0,0,0,.12);
padding:1em 1em 2em;overflow:auto;z-index:5;font-size:.92rem}
.tv-panel h2{font-size:1.05rem;margin:.2em 2em .4em 0;overflow-wrap:anywhere}
.tv-panel .close{position:absolute;top:.6em;right:.6em;border:1px solid var(--line);background:var(--head);color:var(--fg);border-radius:6px;padding:.2em .6em}
.tv-panel h3{font-size:.85rem;margin:1em 0 .3em;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
.tv-panel dl{margin:0;display:grid;grid-template-columns:minmax(7em,auto) 1fr;gap:.25em .8em}
.tv-panel dt{color:var(--muted)}.tv-panel dd{margin:0;overflow-wrap:anywhere}
.tv-panel code{font-size:.84em;background:var(--head);padding:.05em .3em;border-radius:4px;overflow-wrap:anywhere}
.tv-panel ul{margin:.2em 0;padding-left:1.1em}.tv-panel li{margin:.15em 0}
.tv-panel blockquote{margin:.3em 0;padding:.3em .7em;border-left:3px solid var(--accent);background:var(--head);font-size:.88rem}
.tv-panel .num{font-size:1.1rem;font-weight:600}
@media (max-width:700px){.tv-panel{top:auto;bottom:0;height:70vh;width:100%;border-left:0;border-top:1px solid var(--line);border-radius:14px 14px 0 0}
.tv-events li{grid-template-columns:2em 1fr;grid-auto-rows:auto}.tv-events li .msg{grid-column:1/-1}}
@media (prefers-reduced-motion:no-preference){.tv-card,.tv-stage{transition:background .15s,outline-color .15s}}
.tv-audit li{list-style:none;font-size:.84rem}
/* the map: a spine of stages with their branches (SVG) */
.tv-map{overflow-x:auto;margin:.2em 0 .4em;border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:10px}
.tv-map svg{display:block;max-width:none;font:13px/1.2 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
.tv-map .mnode{cursor:pointer}.tv-map .mnode:focus{outline:none}
.tv-map .mnode rect{fill:var(--bg);stroke:var(--line);stroke-width:1.4}
.tv-map .mnode.stage rect{fill:var(--head);stroke-width:2}
.tv-map .mnode:hover rect,.tv-map .mnode:focus rect{stroke:var(--accent);stroke-width:2.4}
.tv-map .mnode text{fill:var(--fg);font-weight:600;pointer-events:none}
.tv-map .mnode text.sub{font-size:11.5px;font-weight:400;fill:var(--muted)}
.tv-map .mnode text.sub2{font-size:11px;font-weight:400;fill:var(--muted)}
.tv-map .mnode.kid text{font-weight:500;font-size:12.5px}
.tv-map .mnode.more rect{stroke-dasharray:4 3}.tv-map .mnode.more text{fill:var(--accent)}
.tv-map .tone-ok rect{stroke:var(--ok)}.tv-map .tone-warn rect{stroke:var(--warn)}.tv-map .tone-bad rect{stroke:var(--bad)}.tv-map .tone-off rect{stroke:var(--off);stroke-dasharray:4 3}
.tv-map .tone-off text{fill:var(--muted)}
.tv-map path.spine{fill:none;stroke:var(--accent);stroke-width:2}.tv-map marker path{fill:var(--accent)}
.tv-map path.branch{fill:none;stroke:var(--line);stroke-width:1.5}
.tv-legend i.box{width:14px;height:14px;border:2px solid var(--accent);border-radius:4px;border-top-width:2px}
.tv-legend i.box.ok{border-color:var(--ok)}.tv-legend i.box.warn{border-color:var(--warn)}.tv-legend i.box.bad{border-color:var(--bad)}.tv-legend i.box.off{border-color:var(--off);border-style:dashed}
details.tv-timeline summary{cursor:pointer;color:var(--accent);font-size:.95rem;margin:.6em 0 .3em}
.tv-map .mnode.sel rect{stroke:var(--accent);stroke-width:3}
/* the graph: records as circles, relationships as lines; zoom and drag */
.tv-graph-bar{display:flex;flex-wrap:wrap;gap:.5em;align-items:center;margin:.3em 0 .5em}
.tv-graph-bar input{font:inherit;padding:.4em .7em;border:1px solid var(--line);border-radius:999px;background:var(--card);color:var(--fg);min-width:16em;flex:1 1 16em}
.tv-graph-bar button{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:.35em .9em}
.tv-hint{font-size:.84rem;color:var(--muted);flex-basis:100%}
.tv-graph{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);overflow:hidden;touch-action:none;cursor:grab}
.tv-graph:active{cursor:grabbing}.tv-graph svg{display:block;font:11px/1.2 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
.tv-graph line,.tv-graph circle{vector-effect:non-scaling-stroke}
.tv-graph line.gl{stroke:var(--line);stroke-width:1.2;opacity:.9}
.tv-graph line.member{stroke:var(--line);stroke-width:1;opacity:.5}
.tv-graph line.supported_by,.tv-graph line.computed_from,.tv-graph line.cites{stroke:var(--accent)}
.tv-graph line.refuted_by{stroke:var(--bad);stroke-dasharray:5 4}.tv-graph line.resolved_by{stroke:var(--ok);stroke-dasharray:2 3}
.tv-graph line.rejected_for{stroke:var(--bad);stroke-width:1.8}.tv-graph line.requires_equipment{stroke:var(--bad);stroke-dasharray:6 3}
.tv-graph line.depends_on{stroke:var(--off)}.tv-graph line.mapped_to{stroke:var(--off);stroke-dasharray:2 3}
.tv-graph line.hl{stroke-width:2.6;opacity:1}.tv-graph line.dim{opacity:.12}
.tv-graph g.gn{cursor:pointer}.tv-graph g.gn circle{stroke:var(--card);stroke-width:2}
.tv-graph g.gn.tone-ok circle{stroke:var(--ok)}.tv-graph g.gn.tone-warn circle{stroke:var(--warn)}.tv-graph g.gn.tone-bad circle{stroke:var(--bad)}
.tv-graph g.gn.tone-off circle{stroke:var(--off);stroke-dasharray:3 2;opacity:.7}
.tv-graph g.gn.hub circle{stroke:var(--accent);stroke-width:2.5}
.tv-graph g.gn text.gt{fill:var(--fg);text-anchor:middle;pointer-events:none;opacity:0;font-size:1em;paint-order:stroke;stroke:var(--card);stroke-width:.28em;stroke-linejoin:round}
.tv-graph g.gn.hub text.gt{font-weight:700;font-size:1.18em;opacity:1}
.tv-graph g.gn.lbl-always text.gt,.tv-graph.zoomed g.gn text.gt,.tv-graph.all-labels g.gn text.gt,.tv-graph g.gn:hover text.gt,.tv-graph g.gn.sel text.gt,.tv-graph g.gn.found text.gt{opacity:1}
.tv-graph g.gn.dim{opacity:.18}.tv-graph g.gn.sel circle{stroke:var(--accent);stroke-width:4}
.tv-graph g.gn.found circle{stroke:var(--accent);stroke-width:4}
.tv-glegend span{display:inline-flex;align-items:center;gap:.3em}.tv-glegend i{display:inline-block;width:12px;height:12px;border-radius:50%;border:0}
.tv-glegend i.ring{background:transparent;border:3px solid var(--ok)}.tv-glegend i.ring.warn{border-color:var(--warn)}.tv-glegend i.ring.bad{border-color:var(--bad)}.tv-glegend i.ring.off{border-color:var(--off);border-style:dashed}
.tv-stages{display:flex;flex-wrap:wrap;gap:.4em;align-items:center;margin:0 0 .4em}
.tv-chip{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:.25em .8em;font-size:.92em}
.tv-chip b{font-weight:600;color:var(--muted);margin-left:.15em}.tv-chip.open{border-color:var(--accent)}
.tv-chip.focus{background:var(--accent);color:var(--card);border-color:var(--accent)}.tv-chip.focus b{color:var(--card)}
.tv-focus{font-size:.9em;color:var(--muted);margin-left:.4em}
p.tv-hint{font-size:.9em;color:var(--muted);margin:0 0 .5em}
.tv-graph line.flow{stroke:var(--accent);stroke-dasharray:1 6;stroke-linecap:round;opacity:.55;stroke-width:2}
.tv-graph line.bundle{opacity:.6}.tv-graph line.far{opacity:.12}
.tv-graph g.gn.hub text.cnt{fill:var(--fg);text-anchor:middle;font-size:1em;font-weight:700;pointer-events:none}
.tv-graph g.gn.hub.open circle{fill:var(--accent)!important}.tv-graph g.gn.hub.open text.cnt{fill:var(--card)}
.tv-graph g.gn.far{opacity:.3}.tv-graph.focus g.gn.near text.gt,.tv-graph.few g.gn text.gt{opacity:1}.tv-graph.focus g.gn.far:not(.hub) text.gt{opacity:0}
.tv-graph ellipse.cloud.focus{opacity:.16}
.tv-glegend i.ln{display:inline-block;width:1.4em;height:0;border-top:2px dotted var(--accent);vertical-align:middle;margin-right:.3em}
.tv-glegend i.ln.bundle{border-top:3px solid var(--line)}
.tv-fullpage{position:fixed;inset:0;z-index:1000;background:var(--bg);padding:12px 16px;overflow:auto;box-sizing:border-box}
.tv-noscroll{overflow:hidden}
.tv-graph ellipse.cloud{fill:var(--accent);opacity:.07;stroke:none}.tv-graph ellipse.cloud.c1{fill:var(--ok)}.tv-graph ellipse.cloud.c2{fill:var(--warn)}.tv-graph ellipse.cloud.c3{fill:#b07aa1}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]) .tv-graph ellipse.cloud{opacity:.12}}
</style></head><body><script id="trace" type="application/json">{"edges":[{"kind":"similar_to","label":"same_elements, 1.00","ref":"analogues/brief.json#analogues/0","source":"target","target":"analogue:Na2O1"},{"kind":"supports","label":"score 1.00","ref":"analogues/brief.json#analogues/0","source":"analogue:Na2O1","target":"direction:hydrothermal"}],"events":[{"ended":"2026-10-26T00:00:00.000+00:00","message":"Na2O2: identity unresolved, phase unresolved; gates G1 PASS, G2 UNKNOWN","name":"target intake","seq":1,"stage":"M01","started":"2026-10-26T00:00:00.000+00:00","status":"completed","subject":"x1"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"no synthesis precedent of this composition in the evidence","name":"families and precedents","seq":2,"stage":"M02","started":"2026-10-26T00:00:00.000+00:00","status":"completed","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"no route for Na2O2 in the families Mat2Bot (milestone 1) plans (documented here: none in the evidence set); not planned rather than planned weakly","name":"route candidates","seq":3,"stage":"M04","started":"2026-10-26T00:00:00.000+00:00","status":"refused","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"gate S on the product alone: UNKNOWN; Na2O2 H271, H314 (hard_fail/human_only)","name":"the product's own hazards (handling only)","seq":4,"stage":"M01","started":"2026-10-26T00:00:00.000+00:00","status":"completed","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"1 similar material(s), too few for a frequency","name":"by analogy: a research brief","seq":5,"stage":"M03","started":"2026-10-26T00:00:00.000+00:00","status":"completed","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"not reached: no route candidate in Mat2Bot's planned families","name":"feasibility","seq":6,"stage":"M05","started":"2026-10-26T00:00:00.000+00:00","status":"skipped","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"not reached: no route candidate in Mat2Bot's planned families","name":"route cases and ranking","seq":7,"stage":"M07","started":"2026-10-26T00:00:00.000+00:00","status":"skipped","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"not reached: no route candidate in Mat2Bot's planned families","name":"procedure","seq":8,"stage":"M08","started":"2026-10-26T00:00:00.000+00:00","status":"skipped","subject":"Na2O2"},{"ended":"2026-10-26T00:00:00.000+00:00","message":"not reached: no route candidate in Mat2Bot's planned families","name":"laboratories","seq":9,"stage":"LAB","started":"2026-10-26T00:00:00.000+00:00","status":"skipped","subject":"Na2O2"}],"layout":{"columns":["M01","M02","M04","M03","M05","M07","M08","LAB","AUDIT"],"rows":{"analogue:Na2O1":1,"brief":0,"check:0":3,"direction:hydrothermal":2,"finding:0":0,"gate:G1":1,"gate:G2":2,"gateS:target":3,"hazard:target:Na2O2":4,"target":0}},"nodes":[{"children":["gate:G1","gate:G2","gateS:target"],"detail":{"checked_against":["the Mat2Bot v0.1 polymorph registry (KCl, CaCO3, ZnO, BaTiO3, and the ZnO competitors Zn(OH)2 and Zn5(OH)8(NO3)2(H2O)2; COD structures and cited stability fields)"],"comparisons":[],"first_checks":[],"form":"powder","formula":"Na2O2","identity":"unresolved","known_phases":[],"missing":["known phases of the composition (outside the registry; Materials Project not consulted)","Materials Project energies (no key; never decisive for polymorphs)"],"nearest_phase":null,"next_step":"","novelty":"not found in the Mat2Bot v0.1 polymorph registry (KCl, CaCO3, ZnO, BaTiO3, and the ZnO competitors Zn(OH)2 and Zn5(OH)8(NO3)2(H2O)2; COD structures and cited stability fields); no other database consulted","phase":null,"phase_note":"","predictions":[],"structure":null},"evidence":"n/a","execution":"completed","kind":"target","lab":null,"label":"Na2O2","node_id":"target","presentation_only":false,"ref":"target.json#target","science":"unresolved","stage":"M01"},{"children":[],"detail":{"findings":[],"rules":["R-G1-INPUT-001","R-G1-STRUCT-001"]},"evidence":"n/a","execution":"completed","kind":"claim","lab":null,"label":"Gate G1: PASS","node_id":"gate:G1","presentation_only":false,"ref":"target.json#gates/G1","science":"PASS","stage":"M01"},{"children":[],"detail":{"findings":[{"code":"IDENTITY_UNRESOLVED","message":"Na2O2 is outside the Mat2Bot v0.1 polymorph registry (KCl, CaCO3, ZnO, BaTiO3, and the ZnO competitors Zn(OH)2 and Zn5(OH)8(NO3)2(H2O)2; COD structures and cited stability fields)","next":"","rule":"R-G2-ID-001","severity":"warning"}],"rules":["R-G2-ID-001","R-M01-ID-001","R-M01-PHASE-001"]},"evidence":"n/a","execution":"completed","kind":"claim","lab":null,"label":"Gate G2: UNKNOWN","node_id":"gate:G2","presentation_only":false,"ref":"target.json#gates/G2","science":"UNKNOWN","stage":"M01"},{"children":["hazard:target:Na2O2"],"detail":{"findings":[{"code":"HAZARD_HARD_FAIL","message":"sodium peroxide (Na2O2, product): H271 (harmonised): no unattended automated step may handle it; a person may, after G7"},{"code":"HAZARD_HUMAN_ONLY","message":"sodium peroxide (Na2O2, product): H314 (harmonised): a person handles it; G7 records it"},{"code":"HAZARD_UNKNOWN","message":"no reagent of this route is known, so their hazards are unknown; a person decides at G7"}],"what":"what handling the material demands; not a route verdict"},"evidence":"n/a","execution":"completed","kind":"hazard","lab":null,"label":"Handling the product (gate S on it alone): UNKNOWN","node_id":"gateS:target","presentation_only":false,"ref":"safety/target.json#gate","science":"UNKNOWN","stage":"M01"},{"children":[],"detail":{"codes":["H271","H314"],"demands":["hard_fail","human_only"],"harmonised":true,"pubchem_cid":14803,"url":"https://pubchem.ncbi.nlm.nih.gov/compound/14803#section=GHS-Classification"},"evidence":"verified","execution":"completed","kind":"hazard","lab":null,"label":"sodium peroxide (Na2O2): hard_fail, human_only","node_id":"hazard:target:Na2O2","presentation_only":false,"ref":"safety/target.json#substances/Na2O2","science":null,"stage":"M01"},{"children":[],"detail":{"code":"NO_SUPPORTED_FAMILY","message":"no route for Na2O2 in the families Mat2Bot (milestone 1) plans (documented here: none in the evidence set); not planned rather than planned weakly","next":"","rule":"R-M03-SCOPE-001","severity":"warning","subject":"Na2O2"},"evidence":"n/a","execution":"refused","kind":"finding","lab":null,"label":"no route for Na2O2 in the families Mat2Bot (milestone 1) plans (documented here: none in the evidence set); not planned rather than planned weakly","node_id":"finding:0","presentation_only":false,"ref":"plan.json#findings/0","science":null,"stage":"M04"},{"children":["analogue:Na2O1","direction:hydrothermal","check:0"],"detail":{"attribution":"Derived from Kononova, O., Huo, H., He, T. et al. Text-mined dataset of inorganic materials synthesis recipes. Sci. Data 6, 203 (2019), doi 10.1038/s41597-019-0224-1, dataset doi 10.6084/m9.figshare.9722159.v3; Wang, Z., Kononova, O., Cruse, K. et al. Dataset of solution-based inorganic materials synthesis procedures extracted from the scientific literature. Sci. Data 9, 231 (2022), doi 10.1038/s41597-022-01317-2, dataset doi 10.6084/m9.figshare.16583387.v4 (both CC BY 4.0). Changes: parsed, normalised and filtered by Mat2Bot (scripts/build_analogue_index.py).","basis":"few_analogues","level":2,"physics":{},"promise":"A research brief by analogy, not a recipe. It says how materials like this one were reported made and how often each route was used for them. Every direction in it is a hypothesis to test; it gives no amounts and nothing in it can be run. The frequencies are about how similar known materials were reported made, never a chance that a synthesis will work: the published records hold successes only.","sentences":["Mat2Bot found no record of Na2O2 itself; it looked at 1 similar material (same elements, or a host compound).","Fewer than 3 of them count, so it gives no frequency: the similar materials are listed with their routes."],"stability":{}},"evidence":"n/a","execution":"completed","kind":"grouping","lab":null,"label":"A research brief by analogy (not a recipe): too few similar materials for a frequency","node_id":"brief","presentation_only":true,"ref":"analogues/brief.json#basis","science":null,"stage":"M03"},{"children":[],"detail":{"counts":true,"level":2,"papers":12,"routes":["hydrothermal"],"score":1.0,"tier":"same_elements"},"evidence":"unverified","execution":"completed","kind":"analogue","lab":null,"label":"Na2O: the same elements in other proportions","node_id":"analogue:Na2O1","presentation_only":false,"ref":"analogues/brief.json#analogues/0","science":null,"stage":"M03"},{"children":[],"detail":{"band":null,"frequency":null,"high":null,"low":null,"open_sources":[],"own_papers":null,"planned":"no","precursor_sets":[["NaOH",10],["NaAlO2",2]],"route":"hydrothermal","typical":[{"clusters":7,"median":99.85,"q1":79.85,"q3":100.0,"quantity":"temperature","unit":"°C"},{"clusters":9,"median":24.0,"q1":8.0,"q3":24.0,"quantity":"time","unit":"h"}]},"evidence":"unverified","execution":"completed","kind":"direction","lab":"INCOMPLETE","label":"a hydrothermal synthesis: 1 similar material, no frequency","node_id":"direction:hydrothermal","presentation_only":false,"ref":"analogues/brief.json#routes/0","science":"HYPOTHETICAL","stage":"M03"},{"children":[],"detail":{},"evidence":"n/a","execution":"completed","kind":"check","lab":null,"label":"the evidence is thin (1 similar material counted): read their papers before choosing a route","node_id":"check:0","presentation_only":false,"ref":"analogues/brief.json#first_checks/0","science":null,"stage":"M03"},{"children":["target","gate:G1","gate:G2","gateS:target","hazard:target:Na2O2"],"detail":{"events":[1,4],"how":"","message":"Na2O2: identity unresolved, phase unresolved; gates G1 PASS, G2 UNKNOWN; gate S on the product alone: UNKNOWN; Na2O2 H271, H314 (hard_fail/human_only)"},"evidence":"n/a","execution":"completed","kind":"stage","lab":null,"label":"Target","node_id":"stage:M01","presentation_only":false,"ref":"trace.json#events/M01","science":null,"stage":"M01"},{"children":[],"detail":{"events":[2],"how":"","message":"no synthesis precedent of this composition in the evidence"},"evidence":"n/a","execution":"completed","kind":"stage","lab":null,"label":"Evidence","node_id":"stage:M02","presentation_only":false,"ref":"trace.json#events/M02","science":null,"stage":"M02"},{"children":["finding:0"],"detail":{"events":[3],"how":"","message":"no route for Na2O2 in the families Mat2Bot (milestone 1) plans (documented here: none in the evidence set); not planned rather than planned weakly"},"evidence":"n/a","execution":"refused","kind":"stage","lab":null,"label":"Routes","node_id":"stage:M04","presentation_only":false,"ref":"trace.json#events/M04","science":null,"stage":"M04"},{"children":["brief","analogue:Na2O1","direction:hydrothermal","check:0"],"detail":{"events":[5],"how":"","message":"1 similar material(s), too few for a frequency"},"evidence":"n/a","execution":"completed","kind":"stage","lab":null,"label":"By analogy","node_id":"stage:M03","presentation_only":false,"ref":"trace.json#events/M03","science":null,"stage":"M03"},{"children":[],"detail":{"events":[6],"how":"","message":"not reached: no route candidate in Mat2Bot's planned families"},"evidence":"n/a","execution":"skipped","kind":"stage","lab":null,"label":"Science","node_id":"stage:M05","presentation_only":false,"ref":"trace.json#events/M05","science":null,"stage":"M05"},{"children":[],"detail":{"events":[7],"how":"","message":"not reached: no route candidate in Mat2Bot's planned families"},"evidence":"n/a","execution":"skipped","kind":"stage","lab":null,"label":"The case","node_id":"stage:M07","presentation_only":false,"ref":"trace.json#events/M07","science":null,"stage":"M07"},{"children":[],"detail":{"events":[8],"how":"","message":"not reached: no route candidate in Mat2Bot's planned families"},"evidence":"n/a","execution":"skipped","kind":"stage","lab":null,"label":"Procedure","node_id":"stage:M08","presentation_only":false,"ref":"trace.json#events/M08","science":null,"stage":"M08"},{"children":[],"detail":{"events":[9],"how":"","message":"not reached: no route candidate in Mat2Bot's planned families"},"evidence":"n/a","execution":"skipped","kind":"stage","lab":null,"label":"Laboratories","node_id":"stage:LAB","presentation_only":false,"ref":"trace.json#events/LAB","science":null,"stage":"LAB"},{"children":[],"detail":{"events":[],"how":"run `mat2bot audit <package>`; the result never comes from the package itself","message":"the package is audited after it is written: run the auditor, or a live audit fills this column"},"evidence":"n/a","execution":"not_run","kind":"stage","lab":null,"label":"Audit","node_id":"stage:AUDIT","presentation_only":false,"ref":"trace.json#nodes/stage:AUDIT","science":null,"stage":"AUDIT"}],"note":"A projection of the plan's records: every node names the record it shows and every edge a relationship that record holds; nothing here is computed anew. The audit stage is filled only by a live audit.","request_id":"x1","schema":"mat2bot/trace/1","title":"Sodium peroxide (Na2O2)"}</script><script id="trace-config" type="application/json">{"audit_url": "audit.json", "links": {"home": "../../index.html", "report": "report.html", "package": "package.zip"}, "mat2bot": "0.2.0"}</script><div id="trace-app" data-title="Sodium peroxide (Na2O2)"></div><script>/* Mat2Bot Trace viewer: a knowledge graph of the plan's records (folded to the stages at first, each opening on a
click), a flow map (the stages with arrows, each stage's branches under it), a components view (a stage's records as cards with their typed edges) and a provenance panel (one record),
over trace.json and nothing else. Every drawn node is a node of the trace and every drawn line an edge of it; the
audit column is filled only from a live audit the host gives (config.audit_url or config.audit). Plain JS, no library.
Standalone (trace.html) it keeps its place in the address bar; embedded (the one-box page) it keeps it in memory. */
(function () {
"use strict";
const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const WORDS = {
execution: { completed: ["ran", "ok"], skipped: ["skipped", "off"], refused: ["stopped: refused", "warn"], failed: ["failed", "bad"], not_run: ["not run", "off"] },
science: { PASS: ["holds", "ok"], FAIL: ["fails", "bad"], UNKNOWN: ["not settled", "warn"], STRONGLY_SUPPORTED: ["strongly supported", "ok"],
PARTIALLY_SUPPORTED: ["supported, with caveats", "warn"], HYPOTHETICAL: ["hypothetical", "warn"], BLOCKED: ["rejected", "bad"],
open: ["doubt open", "warn"], eliminated: ["doubt ruled out", "ok"], sustained: ["doubt confirmed", "bad"], refused: ["model refused", "warn"],
"unresolved values": ["values unresolved", "warn"], placeholders: ["placeholders to decide", "warn"],
"known phase": ["a known form", "ok"], "known composition structure unmatched": ["structure matches no known form", "warn"],
contradictory: ["the request contradicts itself", "bad"], "known composition phase unspecified": ["form not named", "warn"],
"known composition other phase": ["not a known form", "warn"], unresolved: ["not in the registry", "acc"] },
audit: { PASS: ["passed", "ok"], FAIL: ["failed", "bad"], UNKNOWN: ["could not be checked", "warn"], NOT_RUN: ["not applicable", "off"] },
evidence: { verified: ["evidence verified", "ok"], unverified: ["evidence not verified", "warn"], missing: ["record missing", "bad"] },
lab: { FULLY_SUPPORTED: ["robot can run it", "ok"], HYBRID: ["robot and people", "ok"], INCOMPLETE: ["not ready", "warn"], BLOCKED: ["cannot be done here", "bad"],
missing: ["equipment missing", "bad"], automated: ["automated", "ok"], human_bench: ["a person", "acc"], external: ["outside facility", "acc"],
human_only: ["a person", "acc"] },
};
const EDGE_WORDS = { depends_on: "comes after", supported_by: "rests on", computed_from: "computed from", refuted_by: "doubted by", resolved_by: "settled by",
produced: "produced", requires_equipment: "needs equipment", rejected_for: "rejected because", cites: "cites", mapped_to: "done with" };
const KIND_WORDS = { stage: "stage", target: "the target", finding: "finding", route: "route", rival: "rejected route", claim: "claim", inference: "inference",
evidence: "evidence", calculation: "calculation", model_output: "model", assumption: "assumption", doubt: "doubt", step: "step", hazard: "hazard",
laboratory: "laboratory", capability: "equipment", grouping: "group", analogue: "similar material", direction: "direction (a hypothesis)",
check: "first check" };
const STAGE_WORDS = { M01: "Target", M02: "Evidence", M04: "Routes", M03: "By analogy", M05: "Science", M07: "The case", M08: "Procedure", LAB: "Laboratories", AUDIT: "Audit" };
function chip(attr, value) {
if (value == null || value === "n/a" || value === "") return "";
const w = (WORDS[attr] || {})[value] || [String(value).replace(/_/g, " "), "acc"];
return `<span class="chip ${w[1]}" title="${esc(attr)}: ${esc(value)}">${esc(w[0])}</span>`;
}
const OF_KIND = { stage: "execution", finding: "execution", evidence: "evidence", assumption: "evidence", laboratory: "lab", capability: "lab" };
function tone(n) {
// one attribute per kind (stages and findings: what ran; evidence: whether it was verified; laboratories: the lab's
// verdict; everything else: the science), so the ring never merges what records/trace.py keeps apart
const attr = OF_KIND[n.kind] || "science";
if (attr === "execution") return { refused: "bad", failed: "bad", skipped: "off", not_run: "off", completed: n.kind === "finding" ? "warn" : "ok" }[n.execution] || "";
if (attr === "evidence") return { verified: "ok", unverified: "warn", missing: "bad" }[n.evidence] || "";
if (attr === "lab") return { FULLY_SUPPORTED: "ok", HYBRID: "ok", INCOMPLETE: "warn", BLOCKED: "bad", missing: "bad" }[n.lab] || "";
if (n.execution === "refused" || n.execution === "failed") return "bad";
if (n.execution === "skipped" || n.execution === "not_run") return "off";
const s = n.science;
if (["FAIL", "BLOCKED", "sustained", "contradictory"].includes(s)) return "bad";
if (["UNKNOWN", "PARTIALLY_SUPPORTED", "HYPOTHETICAL", "open", "refused", "unresolved values", "placeholders", "known composition structure unmatched",
"known composition phase unspecified", "known composition other phase"].includes(s)) return "warn";
if (["PASS", "STRONGLY_SUPPORTED", "eliminated", "known phase"].includes(s)) return "ok";
return "";
}
function mount(app, T, CFG) {
CFG = CFG || {};
const EMBEDDED = !!CFG.embedded;
const NODES = new Map(T.nodes.map((n) => [n.node_id, n]));
const STAGES = (T.layout && T.layout.columns) || ["M01", "M02", "M04", "M03", "M05", "M07", "M08", "LAB", "AUDIT"];
const STAGE_NODE = {};
T.nodes.forEach((n) => { if (n.kind === "stage") STAGE_NODE[n.stage] = n; });
const OUT = new Map(), IN = new Map();
T.edges.forEach((e) => { (OUT.get(e.source) || OUT.set(e.source, []).get(e.source)).push(e); (IN.get(e.target) || IN.set(e.target, []).get(e.target)).push(e); });
const chips = (n) => [chip("execution", n.kind === "stage" || n.execution !== "completed" ? n.execution : null), chip("science", n.science), chip("evidence", n.evidence), chip("lab", n.lab)].join("");
let AUDIT = CFG.audit && CFG.audit.verdict ? CFG.audit : null;
// ---------------------------------------------------------------- state: the address bar (standalone) or memory (embedded)
let S = { stage: "", node: "", cmp: [] };
function parse(h) {
const o = Object.fromEntries(h.replace(/^#/, "").split("&").filter(Boolean).map((kv) => kv.split("=").map(decodeURIComponent)));
return { stage: o.stage || "", node: o.node || "", cmp: (o.cmp || "").split(",").filter(Boolean), view: o.view || "" };
}
function state() { return EMBEDDED ? { ...S, cmp: [...S.cmp] } : parse(location.hash); }
function go(s) {
s = { stage: s.stage || "", node: s.node || "", cmp: s.cmp || [], view: s.view || "" };
if (EMBEDDED) { S = s; render(); return; }
const parts = [];
if (s.view) parts.push("view=" + encodeURIComponent(s.view));
if (s.stage) parts.push("stage=" + encodeURIComponent(s.stage));
if (s.node) parts.push("node=" + encodeURIComponent(s.node));
if (s.cmp.length) parts.push("cmp=" + encodeURIComponent(s.cmp.join(",")));
const next = "#" + parts.join("&");
if (location.hash !== next) location.hash = next; else render();
}
// ---------------------------------------------------------------- the frame
function frame(s) {
const links = CFG.links || {};
const nav = Object.entries(links).map(([k, v]) => `<a href="${esc(v)}">${esc({ report: "Technical report", package: "Download the package", audit: "Audit it now", home: "Mat2Bot" }[k] || k)}</a>`).join("");
const tabs = [["", "Graph"], ["__flow", "Flow"], ["__comp", "Components"], ["__prov", "Provenance"]];
const cur = s.node ? "__prov" : s.stage ? "__comp" : s.view === "flow" ? "__flow" : "";
const head = EMBEDDED ? "" : `<header class="tv-top"><h1>${esc(app.dataset.title || T.title || T.request_id)}: how Mat2Bot got there</h1><nav>${nav}</nav></header>
<p class="tv-sub">${esc(T.note)} Request <code>${esc(T.request_id)}</code>; ${T.nodes.length} records shown, ${T.edges.length} relationships, ${T.events.length} events.</p>`;
return head + `<div class="tv-tabs">${tabs.map(([k, l]) => `<button type="button" data-tab="${k}" ${cur === k ? 'aria-current="page"' : ""}>${l}</button>`).join("")}</div>`;
}
// ---------------------------------------------------------------- the map: a spine of stages with their branches
const NESTING = ["target", "route", "rival", "grouping", "hazard", "laboratory"];
function topLevel(stage) {
const all = (STAGE_NODE[stage] || { children: [] }).children.map((id) => NODES.get(id)).filter(Boolean);
const nested = new Set();
all.forEach((n) => { if (NESTING.includes(n.kind)) n.children.forEach((c) => nested.add(c)); });
return all.filter((n) => !nested.has(n.node_id));
}
const ORDER = { route: 0, rival: 1, target: 0, finding: 1, claim: 0, doubt: 1, assumption: 2, laboratory: 0, capability: 1, hazard: 2, calculation: 0, model_output: 1, grouping: 0, evidence: 0, step: 1 };
const DOUBT_ORDER = { sustained: 0, open: 1, eliminated: 2 };
function branches(stage) {
let ns = topLevel(stage);
if (stage === "M01") ns = [NODES.get("target"), ...(NODES.get("target") || { children: [] }).children.map((id) => NODES.get(id))].filter(Boolean);
if (stage === "M07") ns = ns.filter((n) => n.kind !== "claim" || !(n.detail && n.detail.template === "conditions-supported"));
return ns.slice().sort((a, b) => (ORDER[a.kind] ?? 5) - (ORDER[b.kind] ?? 5) || ((DOUBT_ORDER[a.science] ?? 3) - (DOUBT_ORDER[b.science] ?? 3)));
}
function shortLabel(n, max) {
let t = n.label;
if (n.kind === "route" || n.kind === "rival") t = ((n.detail && n.detail.precursors) || []).map((p) => p.split(" (")[0]).join(" + ") || t.replace(/^(Route \d+|Rejected): /, "");
if (n.kind === "laboratory") t = n.label;
if (n.kind === "doubt") t = t.replace(/ \(here:.*$/, "");
if (n.kind === "grouping") t = t.replace(/^Procedure of [^:]+: /, "Recipe: ");
t = t.replace(/^(Route \d+|Rejected): /, "");
return t.length > max ? t.slice(0, max - 1) + "…" : t;
}
function stageSummary(stage) {
const kids = (STAGE_NODE[stage] || { children: [] }).children.map((id) => NODES.get(id)).filter(Boolean);
const count = (f) => kids.filter(f).length;
if (stage === "M01") { const t = NODES.get("target"); return t ? shortLabel(t, 24) : ""; }
if (stage === "M02") return `${count((n) => n.kind === "evidence")} records`;
if (stage === "M04") return `${count((n) => n.kind === "route")} proposed, ${count((n) => n.kind === "rival")} set aside`;
if (stage === "M05") return `${count((n) => n.kind === "calculation")} numbers, ${count((n) => n.kind === "model_output" && n.execution === "refused")} refusals`;
if (stage === "M07") return `doubts: ${count((n) => n.science === "open")} open, ${count((n) => n.science === "eliminated")} ruled out`;
if (stage === "M08") return `${count((n) => n.kind === "step")} steps`;
if (stage === "LAB") return kids.filter((n) => n.kind === "laboratory").map((l) => l.label.split(":")[0]).join(", ") || "none asked";
if (stage === "M03") { const g = NODES.get("brief"); return g ? `${count((n) => n.kind === "direction")} directions, ${count((n) => n.kind === "analogue")} similar materials` : "not needed"; }
if (stage === "AUDIT") return AUDIT ? `${{ PASS: "consistent", UNKNOWN: "partly re-checked", FAIL: "inconsistent" }[AUDIT.verdict] || AUDIT.verdict}: ${AUDIT.checks.filter((c) => c.verdict === "PASS").length} checks passed` : "not run";
return "";
}
function mapView() {
const narrow = app.clientWidth < 720;
const maxKids = narrow ? 4 : 6;
const colW = 156, boxH = 60, kidH = 34, gapY = 12, gapX = 18, top = 8;
const cols = STAGES.map((st) => {
const n = STAGE_NODE[st] || { label: STAGE_WORDS[st] || st, execution: "not_run", children: [] };
const kids = st === "AUDIT" ? [] : branches(st);
return { st, n, kids: kids.slice(0, maxKids), more: Math.max(0, kids.length - maxKids), total: kids.length };
});
const parts = [];
const node = (x, y, w, h, cls, attrs, title, lines, sub) => `<g class="mnode ${cls}" ${attrs} tabindex="0" role="button"><title>${esc(title)}</title>
<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="9"></rect>
<text x="${x + 9}" y="${y + 20}">${esc(lines[0])}</text>${lines[1] ? `<text class="sub" x="${x + 9}" y="${y + 38}">${esc(lines[1])}</text>` : ""}${sub ? `<text class="sub2" x="${x + 9}" y="${y + h - 8}">${esc(sub)}</text>` : ""}</g>`;
let W, H;
if (!narrow) {
W = STAGES.length * colW + (STAGES.length - 1) * gapX;
const rows = Math.max(...cols.map((c) => c.kids.length + (c.more ? 1 : 0)), 1);
H = top + boxH + 26 + rows * (kidH + gapY) + 8;
cols.forEach((c, i) => {
const x = i * (colW + gapX);
const ex = c.st === "AUDIT" && AUDIT ? ({ PASS: "completed", FAIL: "failed" }[AUDIT.verdict] || "refused") : c.n.execution;
const w = (WORDS.execution[ex] || [ex, "off"]);
parts.push(node(x, top, colW, boxH, `stage tone-${w[1]}`, `data-stage="${esc(c.st)}"`, `${c.n.label}: ${c.n.detail && c.n.detail.message || ""}`, [STAGE_WORDS[c.st] || c.st, w[0]], stageSummary(c.st)));
if (i < cols.length - 1) parts.push(`<path class="spine" d="M${x + colW},${top + boxH / 2} L${x + colW + gapX - 4},${top + boxH / 2}" marker-end="url(#arrow)"></path>`);
let y = top + boxH + 26;
c.kids.forEach((k) => {
parts.push(`<path class="branch" d="M${x + 18},${top + boxH} L${x + 18},${y + kidH / 2} L${x + 30},${y + kidH / 2}"></path>`);
parts.push(node(x + 30, y, colW - 30, kidH, `kid tone-${tone(k)}`, `data-node="${esc(k.node_id)}"`, k.label, [shortLabel(k, 17)], ""));
y += kidH + gapY;
});
if (c.more) {
parts.push(`<path class="branch" d="M${x + 18},${top + boxH} L${x + 18},${y + kidH / 2} L${x + 30},${y + kidH / 2}"></path>`);
parts.push(node(x + 30, y, colW - 30, kidH, "kid more", `data-stage="${esc(c.st)}"`, `${c.total} in this stage`, [`+${c.more} more…`], ""));
}
});
} else {
W = Math.max(app.clientWidth - 24, 300); // inside the box's padding
const sx = 12, bx = 34, kx = 56; // the spine at the left edge, the branches beside it, the boxes after
const kidW = W - kx;
let y = top;
cols.forEach((c, i) => {
const ex = c.st === "AUDIT" && AUDIT ? ({ PASS: "completed", FAIL: "failed" }[AUDIT.verdict] || "refused") : c.n.execution;
const w = (WORDS.execution[ex] || [ex, "off"]);
parts.push(node(bx - 10, y, W - (bx - 10), boxH, `stage tone-${w[1]}`, `data-stage="${esc(c.st)}"`, `${c.n.label}: ${c.n.detail && c.n.detail.message || ""}`, [`${STAGE_WORDS[c.st] || c.st}: ${w[0]}`], stageSummary(c.st)));
let ky = y + boxH + gapY;
c.kids.forEach((k) => {
parts.push(`<path class="branch" d="M${bx},${y + boxH} L${bx},${ky + kidH / 2} L${kx},${ky + kidH / 2}"></path>`);
parts.push(node(kx, ky, kidW, kidH, `kid tone-${tone(k)}`, `data-node="${esc(k.node_id)}"`, k.label, [shortLabel(k, 40)], ""));
ky += kidH + gapY;
});
if (c.more) {
parts.push(`<path class="branch" d="M${bx},${y + boxH} L${bx},${ky + kidH / 2} L${kx},${ky + kidH / 2}"></path>`);
parts.push(node(kx, ky, kidW, kidH, "kid more", `data-stage="${esc(c.st)}"`, `${c.total} in this stage`, [`+${c.more} more…`], ""));
ky += kidH + gapY;
}
if (i < cols.length - 1) parts.push(`<path class="spine" d="M${sx},${y + boxH / 2} L${sx},${ky + 8}" marker-end="url(#arrow)"></path>`);
y = ky + 18;
});
H = y;
}
const legend = `<p class="tv-legend"><span><i class="box ok"></i> holds / verified / can run</span><span><i class="box warn"></i> open, caveat, not ready</span><span><i class="box bad"></i> fails, rejected, confirmed doubt, missing</span><span><i class="box off"></i> skipped or not run</span><span>Click a box to open it.</span></p>`;
return `<div class="tv-map"><svg viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="the stages Mat2Bot ran, with each stage's records"><defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z"></path></marker></defs>${parts.join("")}</svg></div>` + legend;
}
// ---------------------------------------------------------------- the graph: every record a circle, every relationship a line
// It starts folded: the stages (big circles, the number inside counts their records), the target, the routes, the
// laboratories and the findings. A stage opens on click (its records spring out of it) and the view zooms in on it.
// Lines between folded records are bundled into one thicker line between their stages. The layout is a live
// simulation (repulsion, springs on the links, a pull toward each stage's column so the whole still flows from the
// target on the left to the audit on the right); dragging a circle pulls its neighbours.
const KIND_COLOR = { target: "#2f5d8a", evidence: "#4e79a7", route: "#59a14f", rival: "#e15759", doubt: "#f28e2b", calculation: "#b07aa1",
model_output: "#9c755f", step: "#76b7b2", laboratory: "#edc948", capability: "#bab0ab", hazard: "#ff9da7", claim: "#86bcb6", assumption: "#d4a6c8",
finding: "#e15759", grouping: "#bab0ab", inference: "#bab0ab", analogue: "#a0cbe8", direction: "#8cd17d", check: "#f1ce63" };
const KIND_R = { target: 13, route: 12, rival: 11, laboratory: 11, grouping: 9, evidence: 8, doubt: 7, calculation: 7, model_output: 6, claim: 7,
hazard: 6, capability: 5, step: 5, assumption: 5, finding: 8, analogue: 7, direction: 10, check: 7 };
const KIND_LEGEND = [["target", "the target"], ["evidence", "published record"], ["route", "route proposed"], ["rival", "route set aside"],
["claim", "claim"], ["doubt", "doubt"], ["calculation", "number / model"], ["step", "recipe step"], ["laboratory", "laboratory"],
["hazard", "hazard"], ["capability", "equipment"]];
const KEY = ["target", "route", "rival", "laboratory", "finding", "direction"]; // shown even while their stage is folded
const K_LINK = { member: 0.07, flow: 0.004, supported_by: 0.03, computed_from: 0.03, cites: 0.02, refuted_by: 0.03, resolved_by: 0.02,
rejected_for: 0.04, depends_on: 0.06, mapped_to: 0.015, produced: 0.03, requires_equipment: 0.03 };
const REDUCED = !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
let GRAPH = null; // every record's circle with its position, kept across renders
let VIS = null; // what is drawn now: the visible circles and the lines between them
let VIEWPORT = { k: 1, tx: 0, ty: 0 };
let VIEW_MODE = "all"; // "all" / "focus": the view follows the layout; "free": the reader moved it
let OPEN = new Set(), FOCUS = "", FULL = false, HEAT = 1, QUERY = "";
const SIM = { alpha: 0, raf: 0 };
let WORLD = null, BOX = null, EL = new Map();
function graphSize() {
const W = Math.max(app.clientWidth, 640);
const H = FULL ? Math.max(window.innerHeight - 230, 400) : Math.max(Math.min(W * 0.5, 600), 420);
return { W, H };
}
function buildGraph() {
const cols = {};
STAGES.forEach((st, i) => { cols[st] = i; });
const nodes = T.nodes.filter((n) => n.kind !== "stage").map((n) => ({ id: n.node_id, n, st: n.stage, r: KIND_R[n.kind] || 6, col: cols[n.stage] ?? 0, hub: false, key: KEY.includes(n.kind) }));
STAGES.filter((st) => STAGE_NODE[st]).forEach((st) => nodes.push({ id: "stage:" + st, n: STAGE_NODE[st], st, r: 17, col: cols[st], hub: true, key: true }));
const byId = new Map(nodes.map((d) => [d.id, d]));
const links = [];
T.edges.forEach((e) => { if (byId.has(e.source) && byId.has(e.target)) links.push({ s: byId.get(e.source), t: byId.get(e.target), kind: e.kind, label: e.label }); });
STAGES.forEach((st) => { const hub = byId.get("stage:" + st); if (!hub) return; topLevel(st).forEach((n) => { const d = byId.get(n.node_id); if (d) links.push({ s: hub, t: d, kind: "member" }); }); });
T.nodes.forEach((n) => { if (NESTING.includes(n.kind)) n.children.forEach((c) => { const a = byId.get(n.node_id), b = byId.get(c); if (a && b) links.push({ s: a, t: b, kind: "member" }); }); });
const hubs = STAGES.map((st) => byId.get("stage:" + st)).filter(Boolean);
hubs.forEach((h, i) => { if (hubs[i + 1]) links.push({ s: h, t: hubs[i + 1], kind: "flow" }); }); // the stages in the order they ran
const members = {};
STAGES.forEach((st) => { members[st] = nodes.filter((d) => !d.hub && d.st === st); });
const { W, H } = graphSize();
let seed = 7;
const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
const g = { nodes, links, byId, members, W, H, rnd, hubOf: (d) => byId.get("stage:" + d.st) || null, colX: (c) => 60 + (c + 0.5) * ((g.W - 120) / STAGES.length) };
nodes.forEach((d) => { d.x = g.colX(d.col) + (rnd() - 0.5) * 40; d.y = H / 2 + (rnd() - 0.5) * H * (d.hub ? 0.2 : 0.6); d.vx = 0; d.vy = 0; d.fx = null; d.fy = null; });
return g;
}
function shown(d) { return d.hub || d.key || OPEN.has(d.st); }
function visibleGraph(g) {
const vnodes = g.nodes.filter(shown), vlinks = [], agg = new Map();
g.links.forEach((l) => {
const a = shown(l.s) ? l.s : g.hubOf(l.s), b = shown(l.t) ? l.t : g.hubOf(l.t);
if (!a || !b || a === b) return;
if (a === l.s && b === l.t) { vlinks.push({ s: a, t: b, kind: l.kind, label: l.label, n: 1 }); return; }
if (l.kind === "member") return; // a folded record is inside its stage's circle
const key = a.id + "\u0000" + b.id + "\u0000" + l.kind, got = agg.get(key);
if (got) got.n += 1; else agg.set(key, { s: a, t: b, kind: l.kind, n: 1, bundle: true });
});
agg.forEach((l) => vlinks.push(l));
return { vnodes, vlinks };
}
function step(g, vis, alpha) {
const nodes = vis.vnodes, kRep = 1800;
for (let i = 0; i < nodes.length; i++) {
const a = nodes[i];
for (let j = i + 1; j < nodes.length; j++) {
const b = nodes[j];
let dx = a.x - b.x, dy = a.y - b.y, d2 = dx * dx + dy * dy;
if (d2 < 1) { dx = g.rnd() - 0.5; dy = g.rnd() - 0.5; d2 = 1; }
const d = Math.sqrt(d2), f = (kRep * (a.hub || b.hub ? 2.2 : FOCUS && a.st === FOCUS && b.st === FOCUS ? 1.8 : 1)) / d2;
dx /= d; dy /= d;
a.vx += dx * f; a.vy += dy * f; b.vx -= dx * f; b.vy -= dy * f;
}
}
vis.vlinks.forEach((l) => {
const dx = l.t.x - l.s.x, dy = l.t.y - l.s.y, d = Math.sqrt(dx * dx + dy * dy) || 1;
const want = l.kind === "member" ? (FOCUS && l.t.st === FOCUS && !l.t.hub ? 105 : 62) : l.kind === "flow" ? 150 : 90;
const f = (d - want) * (K_LINK[l.kind] || 0.03);
l.s.vx += (dx / d) * f; l.s.vy += (dy / d) * f; l.t.vx -= (dx / d) * f; l.t.vy -= (dy / d) * f;
});
nodes.forEach((d) => {
if (d.fx != null) { d.x = d.fx; d.y = d.fy; d.vx = 0; d.vy = 0; return; }
d.vx += (g.colX(d.col) - d.x) * (d.hub ? 0.14 : 0.025); // the flow from left to right is kept
d.vy += (g.H / 2 - d.y) * (d.hub ? 0.02 : 0.004);
const sp = Math.sqrt(d.vx * d.vx + d.vy * d.vy) || 1, cap = 14 * alpha + 0.5, k = Math.min(sp, cap) / sp;
d.x += d.vx * k; d.y += d.vy * k; d.vx *= 0.4; d.vy *= 0.4;
});
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { // no two circles overlap
const a = nodes[i], b = nodes[j], dx = b.x - a.x, dy = b.y - a.y, d = Math.sqrt(dx * dx + dy * dy) || 0.01, min = a.r + b.r + 8;
if (d < min) { const push = (min - d) / 2; if (a.fx == null) { a.x -= (dx / d) * push; a.y -= (dy / d) * push; } if (b.fx == null) { b.x += (dx / d) * push; b.y += (dy / d) * push; } }
}
}
function unfold(st, on) {
const g = GRAPH, hub = g.byId.get("stage:" + st);
if (!hub || !g.members[st].length) return;
if (on && !OPEN.has(st)) { OPEN.add(st); g.members[st].filter((d) => !d.key).forEach((d) => { d.x = hub.x + (g.rnd() - 0.5) * 36; d.y = hub.y + (g.rnd() - 0.5) * 36; d.vx = 0; d.vy = 0; d.fx = null; d.fy = null; }); }
if (!on) OPEN.delete(st);
HEAT = 1;
}
function boxOf(ds) { const xs = ds.map((d) => d.x), ys = ds.map((d) => d.y); return { x0: Math.min(...xs) - 70, y0: Math.min(...ys) - 24, x1: Math.max(...xs) + 70, y1: Math.max(...ys) + 36 }; }
function fitTo(box) {
const g = GRAPH, k = Math.min(g.W / (box.x1 - box.x0 + 40), g.H / (box.y1 - box.y0 + 30), 2.2);
return { k, tx: (g.W - (box.x0 + box.x1) * k) / 2, ty: (g.H - (box.y0 + box.y1) * k) / 2 };
}
function clusterOf(st) { return [GRAPH.byId.get("stage:" + st), ...GRAPH.members[st].filter(shown)].filter(Boolean); }
function aimView() {
if (VIEW_MODE === "focus" && FOCUS && GRAPH.byId.has("stage:" + FOCUS)) return fitTo(boxOf(clusterOf(FOCUS)));
if (VIEW_MODE === "all" && VIS && VIS.vnodes.length) return fitTo(boxOf(VIS.vnodes));
return null;
}
function applyView() {
if (!WORLD) return;
WORLD.setAttribute("transform", `translate(${VIEWPORT.tx},${VIEWPORT.ty}) scale(${VIEWPORT.k})`);
WORLD.style.fontSize = `${Math.min(14, Math.max(6.5, 11 / VIEWPORT.k)).toFixed(2)}px`; // labels keep their size on screen
if (BOX) BOX.classList.toggle("zoomed", VIEWPORT.k >= 1.5);
}
function place() {
VIS.vnodes.forEach((d) => { const el = EL.get(d.id); if (el) el.setAttribute("transform", `translate(${d.x.toFixed(1)},${d.y.toFixed(1)})`); });
VIS.vlinks.forEach((l) => { if (!l.el) return; l.el.setAttribute("x1", l.s.x.toFixed(1)); l.el.setAttribute("y1", l.s.y.toFixed(1)); l.el.setAttribute("x2", l.t.x.toFixed(1)); l.el.setAttribute("y2", l.t.y.toFixed(1)); });
WORLD.querySelectorAll("ellipse.cloud").forEach((c) => {
const b = boxOf(clusterOf(c.dataset.cloud));
c.setAttribute("cx", ((b.x0 + b.x1) / 2).toFixed(1)); c.setAttribute("cy", ((b.y0 + b.y1) / 2).toFixed(1));
c.setAttribute("rx", ((b.x1 - b.x0) / 2 + 8).toFixed(1)); c.setAttribute("ry", ((b.y1 - b.y0) / 2 + 4).toFixed(1));
});
}
function tick() {
SIM.raf = 0;
if (!GRAPH || !VIS || !WORLD || !WORLD.isConnected) return;
let busy = false;
if (SIM.alpha > 0.012) { step(GRAPH, VIS, SIM.alpha); SIM.alpha *= 0.95; place(); busy = true; }
const aim = aimView();
if (aim) {
const r = REDUCED ? 1 : 0.16;
VIEWPORT = { k: VIEWPORT.k + (aim.k - VIEWPORT.k) * r, tx: VIEWPORT.tx + (aim.tx - VIEWPORT.tx) * r, ty: VIEWPORT.ty + (aim.ty - VIEWPORT.ty) * r };
if (Math.abs(aim.k - VIEWPORT.k) > 0.002 || Math.abs(aim.tx - VIEWPORT.tx) > 0.4 || Math.abs(aim.ty - VIEWPORT.ty) > 0.4) busy = true; else VIEWPORT = aim;
applyView();
}
if (busy) SIM.raf = requestAnimationFrame(tick);
}
function heat(a) {
SIM.alpha = Math.max(SIM.alpha, a);
if (REDUCED) { while (SIM.alpha > 0.012) { step(GRAPH, VIS, SIM.alpha); SIM.alpha *= 0.95; } place(); const aim = aimView(); if (aim) VIEWPORT = aim; applyView(); return; }
if (!SIM.raf) SIM.raf = requestAnimationFrame(tick);
}
function gLabel(d) { return d.hub ? STAGE_WORDS[d.n.stage] || d.n.label : shortLabel(d.n, 22); }
function toggleStage(st) {
if (!GRAPH.byId.has("stage:" + st)) return;
if (FOCUS === st) { unfold(st, false); FOCUS = ""; VIEW_MODE = "all"; } else { unfold(st, true); FOCUS = st; VIEW_MODE = "focus"; }
render();
}
function toggleFull() {
FULL = !FULL;
app.classList.toggle("tv-fullpage", FULL);
document.documentElement.classList.toggle("tv-noscroll", FULL);
HEAT = Math.max(HEAT, 0.3); VIEW_MODE = FOCUS ? "focus" : "all";
render();
if (!FULL) app.scrollIntoView({ block: "nearest" });
}
function graphView(s) {
const { W, H } = graphSize();
if (!GRAPH) { GRAPH = buildGraph(); HEAT = 1; } else if (Math.abs(GRAPH.W - W) > 40 || Math.abs(GRAPH.H - H) > 40) { GRAPH.W = W; GRAPH.H = H; HEAT = Math.max(HEAT, 0.4); }
const g = GRAPH, sel = s.node || "";
if (sel && g.byId.has(sel) && !shown(g.byId.get(sel))) unfold(g.byId.get(sel).st, true);
VIS = visibleGraph(g);
const inFocus = (d) => FOCUS && d.st === FOCUS;
const clouds = STAGES.filter((st) => g.byId.has("stage:" + st) && g.members[st].some(shown)).map((st) => `<ellipse class="cloud c${STAGES.indexOf(st) % 4} ${FOCUS === st ? "focus" : ""}" data-cloud="${st}" cx="0" cy="0" rx="0" ry="0"><title>${esc(STAGE_WORDS[st] || st)}</title></ellipse>`).join("");
const lines = VIS.vlinks.map((l, i) => {
const word = l.kind === "member" ? "part of" : l.kind === "flow" ? "next stage" : EDGE_WORDS[l.kind] || l.kind;
const far = FOCUS && !inFocus(l.s) && !inFocus(l.t);
return `<line class="gl ${l.kind} ${l.bundle ? "bundle" : ""} ${far ? "far" : ""}" data-i="${i}" data-s="${esc(l.s.id)}" data-t="${esc(l.t.id)}"${l.n > 1 ? ` style="stroke-width:${(1.2 + Math.log2(l.n)).toFixed(1)}"` : ""}><title>${l.n > 1 ? `${l.n} × ` : ""}${esc(word)}${l.label ? ": " + esc(l.label) : ""}</title></line>`;
}).join("");
const circles = VIS.vnodes.map((d) => {
const t = d.hub ? "" : tone(d.n), cnt = d.hub ? g.members[d.st].length : 0;
return `<g class="gn ${d.hub ? "hub" : ""} ${d.hub && OPEN.has(d.st) ? "open" : ""} ${FOCUS ? (inFocus(d) ? "near" : "far") : ""} tone-${t || "none"} ${d.key ? "lbl-always" : ""} ${sel === d.id ? "sel" : ""}" data-gnode="${esc(d.id)}" tabindex="0" role="button">
<title>${esc(d.n.label)}${d.hub ? ` (${cnt} records; click to ${OPEN.has(d.st) ? "fold" : "open"})` : ""}</title><circle r="${d.r}" style="fill:${d.hub ? "var(--head)" : KIND_COLOR[d.n.kind] || "#999"}"></circle>
${d.hub && cnt ? `<text class="cnt" dy="4">${cnt}</text>` : ""}<text class="gt" y="${d.r + 12}">${esc(gLabel(d))}</text></g>`;
}).join("");
const stageChips = STAGES.filter((st) => g.byId.has("stage:" + st)).map((st) => { const n = g.members[st].length;
return `<button type="button" class="tv-chip ${OPEN.has(st) ? "open" : ""} ${FOCUS === st ? "focus" : ""}" data-gstage="${st}" aria-pressed="${FOCUS === st}">${esc(STAGE_WORDS[st] || st)}${n ? ` <b>${n}</b>` : ""}</button>`; }).join("");
const legend = KIND_LEGEND.map(([k, w]) => `<span><i style="background:${KIND_COLOR[k]}"></i> ${esc(w)}</span>`).join("") +
`<span><i class="ring ok"></i> holds</span><span><i class="ring warn"></i> open / caveat</span><span><i class="ring bad"></i> fails / rejected</span><span><i class="ring off"></i> skipped / not run</span>` +
`<span><i class="ln flow"></i> stage order</span><span><i class="ln bundle"></i> several relationships, folded into one line</span>`;
const focusNote = FOCUS ? `<span class="tv-focus">Zoomed in on <b>${esc(STAGE_WORDS[FOCUS] || FOCUS)}</b> · <a href="#" data-stage="${esc(FOCUS)}">see it as a list</a></span>` : "";
return `<div class="tv-graph-bar"><input type="search" id="tv-find" placeholder="find a record (e.g. NaOH, calcite, doubt)…" aria-label="find a record" value="${esc(QUERY)}">
<button type="button" data-gall="overview" ${!OPEN.size ? 'aria-current="page"' : ""}>Overview</button><button type="button" data-gall="everything" ${OPEN.size >= STAGES.filter((st) => g.members[st] && g.members[st].length).length ? 'aria-current="page"' : ""}>Everything</button>
<button type="button" data-gzoom="in" aria-label="zoom in">+</button><button type="button" data-gzoom="out" aria-label="zoom out">−</button>
<button type="button" data-gfit="1">Fit</button><button type="button" data-glabels="1">Labels</button><button type="button" data-gfull="1" aria-pressed="${FULL}">${FULL ? "Close full page" : "Full page"}</button></div>
<div class="tv-stages">${stageChips}${focusNote}</div>
<p class="tv-hint">Click a stage to open it and zoom in (click it again to fold it back); click a small circle to read that record; hover to see what it is linked to; drag to move, scroll to zoom. The number in a big circle counts the records inside it.</p>
<div class="tv-graph ${VIS.vnodes.length <= 24 ? "few" : ""} ${FOCUS ? "focus" : ""}" id="tv-graph"><svg viewBox="0 0 ${g.W} ${g.H}" width="100%" height="${g.H}" role="img" aria-label="the plan's records as a network">
<g class="world" transform="translate(${VIEWPORT.tx},${VIEWPORT.ty}) scale(${VIEWPORT.k})">${clouds}${lines}${circles}</g></svg></div>
<p class="tv-legend tv-glegend">${legend}</p>`;
}
function wireGraph() {
BOX = app.querySelector("#tv-graph");
if (!BOX) return;
const svg = BOX.querySelector("svg"), g = GRAPH;
WORLD = svg.querySelector("g.world");
EL = new Map(); WORLD.querySelectorAll("g.gn").forEach((el) => EL.set(el.dataset.gnode, el));
WORLD.querySelectorAll("line.gl").forEach((el) => { VIS.vlinks[+el.dataset.i].el = el; });
if (HEAT) { for (let i = 0; i < 30; i++) step(g, VIS, 1); const aim = aimView(); if (aim) VIEWPORT = aim; }
place(); applyView();
const a = HEAT; HEAT = 0; if (a) heat(a); else if (aimView()) { if (!SIM.raf) SIM.raf = requestAnimationFrame(tick); }
const pt = (ev) => { const r = svg.getBoundingClientRect(); return { x: (ev.clientX - r.left) * (g.W / r.width), y: (ev.clientY - r.top) * (g.H / r.height) }; };
const zoomAt = (p, f) => { const k2 = Math.min(6, Math.max(0.2, VIEWPORT.k * f)), r = k2 / VIEWPORT.k; VIEW_MODE = "free"; VIEWPORT = { k: k2, tx: p.x - (p.x - VIEWPORT.tx) * r, ty: p.y - (p.y - VIEWPORT.ty) * r }; applyView(); };
svg.addEventListener("wheel", (ev) => { ev.preventDefault(); zoomAt(pt(ev), Math.exp(-ev.deltaY * 0.0015)); }, { passive: false });
app.querySelectorAll("[data-gzoom]").forEach((b) => b.addEventListener("click", () => zoomAt({ x: g.W / 2, y: g.H / 2 }, b.dataset.gzoom === "in" ? 1.4 : 1 / 1.4)));
let drag = null, pinch = null;
const touches = new Map();
svg.addEventListener("pointerdown", (ev) => {
touches.set(ev.pointerId, pt(ev));
if (touches.size === 2) { const [a, b] = [...touches.values()]; pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), k: VIEWPORT.k }; drag = null; return; }
const gn = ev.target.closest("g.gn"), p = pt(ev);
drag = { x: p.x, y: p.y, node: gn ? g.byId.get(gn.dataset.gnode) : null, moved: false, tx: VIEWPORT.tx, ty: VIEWPORT.ty };
svg.setPointerCapture(ev.pointerId);
});
svg.addEventListener("pointermove", (ev) => {
if (touches.has(ev.pointerId)) touches.set(ev.pointerId, pt(ev));
if (pinch && touches.size === 2) { const [a, b] = [...touches.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y) || 1; zoomAt({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, (pinch.k * d / pinch.d) / VIEWPORT.k); return; }
if (!drag) return;
const p = pt(ev), dx = p.x - drag.x, dy = p.y - drag.y;
if (Math.abs(dx) + Math.abs(dy) > 3) drag.moved = true;
if (drag.node) {
if (!drag.moved) return;
const d = drag.node;
d.fx = d.x + dx / VIEWPORT.k; d.fy = d.y + dy / VIEWPORT.k; d.x = d.fx; d.y = d.fy; drag.x = p.x; drag.y = p.y;
VIEW_MODE = "free"; heat(0.3); // the neighbours follow
} else { VIEW_MODE = "free"; VIEWPORT = { ...VIEWPORT, tx: drag.tx + dx, ty: drag.ty + dy }; applyView(); }
});
const endDrag = (ev) => {
touches.delete(ev.pointerId);
if (touches.size < 2) pinch = null;
if (!drag) return;
const d = drag; drag = null;
if (d.node && d.moved) { d.node.fx = null; d.node.fy = null; return; }
if (d.node) { if (d.node.hub) toggleStage(d.node.st); else go({ view: state().view, node: d.node.id, cmp: state().cmp }); }
};
svg.addEventListener("pointerup", endDrag); svg.addEventListener("pointercancel", endDrag);
svg.addEventListener("dblclick", () => { VIEW_MODE = FOCUS ? "focus" : "all"; if (!SIM.raf) SIM.raf = requestAnimationFrame(tick); });
const neighbours = (id) => { const set = new Set([id]); VIS.vlinks.forEach((l) => { if (l.s.id === id) set.add(l.t.id); if (l.t.id === id) set.add(l.s.id); }); return set; };
svg.addEventListener("pointerover", (ev) => { const gn = ev.target.closest("g.gn"); if (!gn || drag) return; const near = neighbours(gn.dataset.gnode);
EL.forEach((x, id) => x.classList.toggle("dim", !near.has(id)));
VIS.vlinks.forEach((l) => { if (!l.el) return; const on = l.s.id === gn.dataset.gnode || l.t.id === gn.dataset.gnode; l.el.classList.toggle("hl", on); l.el.classList.toggle("dim", !on); }); });
svg.addEventListener("pointerout", (ev) => { if (ev.target.closest("g.gn") && !drag) { WORLD.querySelectorAll(".dim,.hl").forEach((x) => { x.classList.remove("dim"); x.classList.remove("hl"); }); applySearch(); } });
const find = app.querySelector("#tv-find");
if (find) {
find.addEventListener("input", () => {
QUERY = find.value.trim();
const q = QUERY.toLowerCase();
const hit = (d) => !!q && (d.n.label + " " + JSON.stringify(d.n.detail || {})).toLowerCase().includes(q);
const need = new Set(g.nodes.filter((d) => hit(d) && !shown(d)).map((d) => d.st));
if (need.size) { need.forEach((st) => unfold(st, true)); render(); const f = app.querySelector("#tv-find"); if (f) { f.focus(); f.setSelectionRange(f.value.length, f.value.length); } return; }
applySearch();
});
if (QUERY) applySearch();
}
}
function applySearch() {
const q = QUERY.toLowerCase();
EL.forEach((x, id) => { const d = GRAPH.byId.get(id); const hit = !q || (d.n.label + " " + JSON.stringify(d.n.detail || {})).toLowerCase().includes(q); x.classList.toggle("dim", !hit); x.classList.toggle("found", !!q && hit); });
}
function overview(s) {
if (s.view !== "flow") return graphView(s) + `<details class="tv-timeline"><summary>What ran, in order (${T.events.length} events)</summary><ol class="tv-events">${T.events.map((e) => `<li class="${e.status}"><span class="seq">${e.seq}</span><span>${esc(e.stage)}</span><span>${esc(e.name)}${e.subject ? ` <small>(${esc(e.subject)})</small>` : ""}<span class="msg">${esc(e.message)}</span></span>${chip("execution", e.status)}</li>`).join("")}</ol></details>`;
const ev = T.events.map((e) => `<li class="${e.status}"><span class="seq">${e.seq}</span><span>${esc(e.stage)}</span><span>${esc(e.name)}${e.subject ? ` <small>(${esc(e.subject)})</small>` : ""}<span class="msg">${esc(e.message)}</span></span>${chip("execution", e.status)}</li>`).join("");
return mapView() + `<details class="tv-timeline"><summary>What ran, in order (${T.events.length} events)</summary><ol class="tv-events">${ev || '<li><span class="tv-empty">no events recorded</span></li>'}</ol>
<p class="tv-sub">Times are the run's own clock (a fixed clock in a reproducible package). A skipped stage was not reached; a refused one stopped on purpose.</p></details>`;
}
// ---------------------------------------------------------------- component view
function groupsOf(stage) {
const kids = topLevel(stage);
const byRoute = new Map();
kids.forEach((n) => { const r = n.detail && n.detail.route; const key = r ? "route " + r : ""; (byRoute.get(key) || byRoute.set(key, []).get(key)).push(n); });
return [...byRoute.entries()];
}
function short(n) { return n ? (n.label.length > 48 ? n.label.slice(0, 46) + "…" : n.label) : "?"; }
function relChips(n, visible) {
const out = [];
(OUT.get(n.node_id) || []).forEach((e) => { if (!visible.has(e.target)) out.push(`<a href="#node=${encodeURIComponent(e.target)}">${esc(EDGE_WORDS[e.kind])}: ${esc(short(NODES.get(e.target)))}</a>`); });
(IN.get(n.node_id) || []).forEach((e) => { if (!visible.has(e.source) && e.kind !== "cites") out.push(`<a href="#node=${encodeURIComponent(e.source)}">${esc(short(NODES.get(e.source)))} ${esc(EDGE_WORDS[e.kind])} this</a>`); });
return out.length ? `<div class="rel">${out.slice(0, 6).join(" · ")}${out.length > 6 ? ` · +${out.length - 6}` : ""}</div>` : "";
}
function card(n, visible, s, depth) {
const kidsShown = depth < 1 && n.children.length && NESTING.includes(n.kind) ? n.children : [];
const acts = [];
if (n.kind === "rival") acts.push(`<button type="button" data-why="${esc(n.node_id)}">Why was it rejected?</button>`);
if (n.kind === "route") acts.push(`<button type="button" data-cmp="${esc(n.node_id)}">${(s.cmp || []).includes(n.node_id) ? "Comparing ✓" : "Compare"}</button>`);
if (n.children.length && !kidsShown.length) acts.push(`<button type="button" data-open="${esc(n.node_id)}">Show ${n.children.length} inside</button>`);
acts.push(`<a href="#node=${encodeURIComponent(n.node_id)}">Details</a>`);
return `<div class="tv-card" data-id="${esc(n.node_id)}"><span class="k">${esc(KIND_WORDS[n.kind] || n.kind)}</span>
<button type="button" class="lbl" data-node="${esc(n.node_id)}">${esc(n.label)}</button><div class="chips">${chips(n)}</div>${relChips(n, visible)}
<div class="acts">${acts.join("")}</div>${kidsShown.length ? `<div class="tv-kids">${kidsShown.map((id) => NODES.get(id)).filter(Boolean).map((k) => card(k, visible, s, depth + 1)).join("")}</div>` : ""}</div>`;
}
function component(s) {
const st = s.stage;
const groups = groupsOf(st);
const visible = new Set();
groups.forEach(([, ns]) => ns.forEach((n) => { visible.add(n.node_id); n.children.forEach((c) => visible.add(c)); }));
const stn = STAGE_NODE[st];
const head = `<p class="tv-crumb"><a href="#">Graph</a> › ${esc(stn ? stn.label : st)} ${chip("execution", stn ? stn.execution : "not_run")}${stn && stn.detail.message ? `<br><small>${esc(stn.detail.message)}</small>` : ""}</p>`;
if (st === "AUDIT") return head + auditView();
if (!groups.length) return head + `<p class="tv-empty">Nothing was recorded for this stage${stn && stn.execution === "skipped" ? ": it was skipped" : ""}.</p>`;
const body = groups.map(([g, ns]) => `<div class="tv-group">${g ? `<h3>${esc(g)}</h3>` : ""}<div class="tv-cards">${ns.map((n) => card(n, visible, s, 0)).join("")}</div></div>`).join("");
return head + legend() + `<div class="tv-comp"><svg class="tv-edges" aria-hidden="true"></svg><div class="tv-groups">${body}</div></div>` + compare(s);
}
function legend() {
return `<p class="tv-legend"><span><i></i> rests on / cites / computed from</span><span><i class="bad dash"></i> doubted by</span><span><i class="ok dot"></i> settled by</span>
<span><i class="bad"></i> rejected because</span><span><i class="muted"></i> comes after</span><span><i class="muted dot"></i> done with</span><span><i class="bad dash"></i> needs equipment</span></p>`;
}
function auditView() {
if (!AUDIT) return `<p class="tv-empty">The package does not carry an audit of itself. ${CFG.audit_url ? "The live audit is loading…" : "Run <code>mat2bot audit <package></code> to re-derive every claim from the files alone."}</p>`;
return `<p>${esc(AUDIT.when || "")}: <b>${esc({ PASS: "consistent", UNKNOWN: "partly re-checked", FAIL: "inconsistent" }[AUDIT.verdict] || AUDIT.verdict)}</b>${CFG.links && CFG.links.audit ? ` · <a href="${esc(CFG.links.audit)}">the full audit page</a>` : ""}</p>
${AUDIT.scope ? `<p class="tv-empty">${esc(AUDIT.scope)}</p>` : ""}
<ul class="tv-audit">${AUDIT.checks.map((c) => `<li>${chip("audit", c.verdict)} ${esc(c.name)}${c.detail ? ` <small>— ${esc(c.detail)}</small>` : ""}</li>`).join("")}</ul>`;
}
function drawEdges() {
const svg = app.querySelector("svg.tv-edges");
if (!svg) return;
const box = svg.parentElement.getBoundingClientRect();
const at = (id) => { const el = app.querySelector(`.tv-card[data-id="${CSS.escape(id)}"]`); if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.left - box.left + r.width / 2, y: r.top - box.top + r.height / 2 }; };
const paths = [];
T.edges.forEach((e) => {
const a = at(e.source), b = at(e.target);
if (!a || !b) return;
const mx = (a.x + b.x) / 2;
paths.push(`<path class="${e.kind}" data-s="${esc(e.source)}" data-t="${esc(e.target)}" d="M${a.x},${a.y} C${mx},${a.y} ${mx},${b.y} ${b.x},${b.y}"><title>${esc(EDGE_WORDS[e.kind])}${e.label ? ": " + esc(e.label) : ""}</title></path>`);
});
svg.setAttribute("viewBox", `0 0 ${box.width} ${box.height}`);
svg.innerHTML = paths.join("");
}
function highlight(id, on) {
app.querySelectorAll("svg.tv-edges path").forEach((p) => { if (p.dataset.s === id || p.dataset.t === id) p.classList.toggle("hl", on); });
}
function why(id) {
app.querySelectorAll(".tv-card.hl").forEach((c) => c.classList.remove("hl"));
const targets = (OUT.get(id) || []).filter((e) => e.kind === "rejected_for").map((e) => e.target);
let first = null;
targets.forEach((t) => { const el = app.querySelector(`.tv-card[data-id="${CSS.escape(t)}"]`); if (el) { el.classList.add("hl"); first = first || el; } });
highlight(id, true);
if (first) first.scrollIntoView({ block: "center", behavior: "smooth" });
else if (targets.length) go({ stage: state().stage, node: targets[0] });
}
function compare(s) {
const ids = (s.cmp || []).slice(0, 2).map((id) => NODES.get(id)).filter(Boolean);
if (ids.length < 2) return ids.length === 1 ? `<p class="tv-sub">Pick a second route to compare with ${esc(short(ids[0]))}.</p>` : "";
const row = (name, f) => `<tr><th>${name}</th>${ids.map((n) => `<td>${f(n)}</td>`).join("")}</tr>`;
const doubts = (n) => T.nodes.filter((d) => d.kind === "doubt" && d.detail.route === n.detail.route && d.science === "open").map((d) => esc(d.label)).join("<br>") || "none open";
const labs = (n) => T.nodes.filter((l) => l.kind === "laboratory" && l.detail.route === n.detail.route).map((l) => esc(l.label)).join("<br>") || "–";
return `<div class="tv-compare"><h3>Side by side</h3><table><thead><tr><th></th>${ids.map((n) => `<th>${esc(short(n))}</th>`).join("")}</tr></thead><tbody>
${row("Support", (n) => chip("science", n.science) + ` <small>${esc(n.detail.row)}</small>`)}
${row("Precedent", (n) => esc(n.detail.precedent))}
${row("Reagents", (n) => (n.detail.precursors || []).map(esc).join("<br>"))}
${row("Conditions", (n) => Object.entries(n.detail.parameters || {}).map(([k, v]) => `${esc(k)} = ${esc(v)}`).join("<br>") || "none stated")}
${row("Equipment", (n) => (n.detail.equipment || []).map(esc).join("<br>"))}
${row("Open doubts", doubts)}${row("Laboratories", labs)}</tbody></table>
<p><button type="button" data-cmp-clear="1">Clear</button></p></div>`;
}
// ---------------------------------------------------------------- provenance panel
function link(url, text) { return url && /^https?:\/\//.test(url) ? `<a href="${esc(url)}" rel="noopener" target="_blank">${esc(text || url)}</a>` : esc(text || url || ""); }
function value(d) {
if (d.value == null && !("unit" in d)) return "";
const u = d.uncertainty;
return `<p class="num">${d.value == null ? "unresolved" : esc(Number(d.value).toPrecision(5).replace(/\.?0+$/, ""))} ${esc(d.unit || "")}${u ? ` ± ${esc(Number(u.expanded).toPrecision(2))} (k = ${esc(u.k)})` : ""}</p>
<dl>${d.method ? `<dt>method</dt><dd><code>${esc(d.method)}</code></dd>` : ""}${d.basis ? `<dt>basis</dt><dd>${esc(d.basis)}</dd>` : ""}<dt>provenance</dt><dd>${esc(d.provenance)}</dd>
${u ? `<dt>uncertainty</dt><dd>u = ${esc(Number(u.u).toPrecision(3))}, type ${esc(u.type)}; ${esc(u.basis)}</dd>` : ""}${d.domain ? `<dt>valid for</dt><dd><code>${esc(JSON.stringify(d.domain))}</code></dd>` : ""}
${d.note ? `<dt>note</dt><dd>${esc(d.note)}</dd>` : ""}</dl>${(d.sources || []).length ? `<h3>Sources</h3><ul>${d.sources.map((s) => `<li>${esc(s.citation || s.id)}${s.id && s.kind === "doi" ? " · " + link("https://doi.org/" + s.id, "doi:" + s.id) : s.url ? " · " + link(s.url, "source") : ""}${s.quote ? `<blockquote>${esc(s.quote)}</blockquote>` : ""}</li>`).join("")}</ul>` : ""}`;
}
function generic(d, skip) {
const rows = Object.entries(d).filter(([k, v]) => !skip.includes(k) && v != null && v !== "" && !(Array.isArray(v) && !v.length) && !(typeof v === "object" && !Array.isArray(v) && !Object.keys(v).length));
if (!rows.length) return "";
return `<dl>${rows.map(([k, v]) => `<dt>${esc(k.replace(/_/g, " "))}</dt><dd>${fmt(v)}</dd>`).join("")}</dl>`;
}
function fmt(v) {
if (Array.isArray(v)) return `<ul>${v.map((x) => `<li>${typeof x === "object" ? fmt(x) : esc(x)}</li>`).join("")}</ul>`;
if (typeof v === "object") return `<dl>${Object.entries(v).map(([k, x]) => `<dt>${esc(k)}</dt><dd>${fmt(x)}</dd>`).join("")}</dl>`;
if (typeof v === "string" && /^https?:\/\//.test(v)) return link(v);
if (typeof v === "string" && /^R-[A-Z0-9-]+-\d{3}$/.test(v)) return `<code>${esc(v)}</code>`;
return esc(v);
}
function panel(id) {
const n = NODES.get(id);
if (!n) return `<aside class="tv-panel"><button type="button" class="close" data-close="1">Close</button><h2>No such record</h2><p>${esc(id)} is not in this trace.</p></aside>`;
const d = n.detail || {};
let body = "";
if (n.kind === "calculation" && "value" in d) body = value(d);
else if (n.kind === "evidence") body = `${d.claim ? `<p>${esc(d.claim)}</p>` : ""}<dl>${d.citation ? `<dt>citation</dt><dd>${esc(d.citation)}</dd>` : ""}${d.doi ? `<dt>doi</dt><dd>${link("https://doi.org/" + d.doi, d.doi)}</dd>` : d.url ? `<dt>source</dt><dd>${link(d.url)}</dd>` : ""}${d.licence ? `<dt>licence</dt><dd>${esc(d.licence)}</dd>` : ""}${d.locator ? `<dt>where</dt><dd>${esc(d.locator)}</dd>` : ""}</dl>${d.quote ? `<h3>Quoted</h3><blockquote>${esc(d.quote)}</blockquote>` : ""}${generic(d, ["claim", "citation", "doi", "url", "licence", "locator", "quote", "kind", "evidence_id"])}`;
else if (n.kind === "doubt") body = `<p>${esc(d.statement)}</p><dl><dt>kind</dt><dd>${esc(d.kind)} doubt</dd><dt>status</dt><dd>${chip("science", d.status)}</dd><dt>rule</dt><dd><code>${esc(d.rule)}</code></dd>${d.closable_by ? `<dt>closed only by</dt><dd>${esc(d.closable_by)}</dd>` : ""}<dt>critical</dt><dd>${d.critical ? "yes" : "no"}</dd></dl>`;
else body = generic(d, ["route"]);
const rel = (edges, dir) => edges.map((e) => { const o = NODES.get(dir === "out" ? e.target : e.source); return o ? `<li><a href="#node=${encodeURIComponent(o.node_id)}">${esc(short(o))}</a> <small>(${esc(EDGE_WORDS[e.kind])}${e.label ? ", " + esc(e.label) : ""})</small></li>` : ""; }).join("");
const outs = OUT.get(id) || [], ins = IN.get(id) || [];
const q = [["What it rests on", outs.filter((e) => ["supported_by", "computed_from", "cites", "resolved_by", "depends_on", "mapped_to", "requires_equipment", "rejected_for"].includes(e.kind)), "out"],
["What rests on it, or questions it", ins, "in"]];
return `<aside class="tv-panel" role="dialog" aria-label="record"><button type="button" class="close" data-close="1">Close</button>
<span class="k">${esc(KIND_WORDS[n.kind] || n.kind)} · stage ${esc(n.stage)}${d.route ? ` · route ${esc(d.route)}` : ""}</span><h2>${esc(n.label)}</h2><div class="chips">${chips(n)}</div>
${body}${q.map(([t, es, dir]) => es.length ? `<h3>${t}</h3><ul>${rel(es, dir)}</ul>` : "").join("")}
${n.children.length ? `<h3>Inside</h3><ul>${n.children.map((c) => NODES.get(c)).filter(Boolean).map((c) => `<li><a href="#node=${encodeURIComponent(c.node_id)}">${esc(short(c))}</a> ${chips(c)}</li>`).join("")}</ul>` : ""}
<h3>Where it is recorded</h3><p><code>${esc(n.ref || "a presentation-only group")}</code>${n.presentation_only ? " (a grouping, not a record)" : ""}</p></aside>`;
}
// ---------------------------------------------------------------- render and events
function render() {
const s = state();
app.innerHTML = frame(s) + (s.stage ? component(s) : overview(s)) + (s.node ? panel(s.node) : "");
if (s.stage) requestAnimationFrame(drawEdges); else if (s.view !== "flow") wireGraph();
if (s.node) {
const el = app.querySelector(`.tv-card[data-id="${CSS.escape(s.node)}"]`);
if (el) { el.classList.add("sel"); highlight(s.node, true); }
const g = app.querySelector(`g.mnode[data-node="${CSS.escape(s.node)}"]`);
if (g) g.classList.add("sel");
}
}
app.addEventListener("click", (ev) => {
const b = ev.target.closest("[data-tab],[data-stage],[data-node],[data-why],[data-open],[data-cmp],[data-cmp-clear],[data-close],[data-gfit],[data-glabels],[data-gstage],[data-gall],[data-gfull],a[href^='#']");
if (!b || !app.contains(b)) return;
const s = state();
if (b.dataset.tab != null) { ev.preventDefault(); if (b.dataset.tab === "") go({}); else if (b.dataset.tab === "__flow") go({ view: "flow" }); else if (b.dataset.tab === "__comp") go({ stage: s.stage || STAGES[0], cmp: s.cmp }); else go({ stage: s.stage || (s.node ? NODES.get(s.node).stage : STAGES[0]), node: s.node || ((STAGE_NODE[s.stage || STAGES[0]] || { children: [] }).children[0] || "target"), cmp: s.cmp }); return; }
if (b.dataset.gfit) { VIEW_MODE = FOCUS ? "focus" : "all"; if (!SIM.raf) SIM.raf = requestAnimationFrame(tick); return; }
if (b.dataset.gstage) { toggleStage(b.dataset.gstage); return; }
if (b.dataset.gall) { if (b.dataset.gall === "overview") { OPEN.clear(); } else STAGES.forEach((st) => unfold(st, true)); FOCUS = ""; VIEW_MODE = "all"; HEAT = 1; render(); return; }
if (b.dataset.gfull) { toggleFull(); return; }
if (b.dataset.glabels) { const box = app.querySelector("#tv-graph"); if (box) box.classList.toggle("all-labels"); return; }
if (b.dataset.stage) { ev.preventDefault(); go({ stage: b.dataset.stage }); return; }
if (b.dataset.node) { ev.preventDefault(); go({ stage: s.stage, node: b.dataset.node, cmp: s.cmp }); return; }
if (b.dataset.why) { why(b.dataset.why); return; }
if (b.dataset.open) { b.outerHTML = `<div class="tv-kids">${NODES.get(b.dataset.open).children.map((id) => NODES.get(id)).filter(Boolean).map((k) => card(k, new Set(T.nodes.map((n) => n.node_id)), s, 1)).join("")}</div>`; requestAnimationFrame(drawEdges); return; }
if (b.dataset.cmp) { const c = s.cmp.includes(b.dataset.cmp) ? s.cmp.filter((x) => x !== b.dataset.cmp) : [...s.cmp, b.dataset.cmp].slice(-2); go({ stage: s.stage, node: s.node, cmp: c }); return; }
if (b.dataset.cmpClear) { go({ stage: s.stage, node: s.node, cmp: [] }); return; }
if (b.dataset.close) { go({ stage: s.stage, cmp: s.cmp, view: s.view }); return; }
if (b.tagName === "A" && b.getAttribute("href").startsWith("#")) { ev.preventDefault(); const h = b.getAttribute("href"); const t = parse(h); go({ ...t, stage: t.stage || s.stage, cmp: t.cmp.length ? t.cmp : s.cmp }); }
});
app.addEventListener("keydown", (ev) => { if ((ev.key === "Enter" || ev.key === " ") && ev.target.closest("g.mnode")) { ev.preventDefault(); ev.target.closest("g.mnode").dispatchEvent(new MouseEvent("click", { bubbles: true })); } });
app.addEventListener("mouseover", (ev) => { const c = ev.target.closest(".tv-card"); if (c) highlight(c.dataset.id, true); });
app.addEventListener("mouseout", (ev) => { const c = ev.target.closest(".tv-card"); if (c && c.dataset.id !== state().node) highlight(c.dataset.id, false); });
if (!EMBEDDED) window.addEventListener("hashchange", render);
window.addEventListener("resize", () => requestAnimationFrame(() => { const s = state(); if (s.stage) drawEdges(); else if (s.view === "flow") render(); else if (GRAPH) { const { W, H } = graphSize(); if (Math.abs(GRAPH.W - W) > 40 || Math.abs(GRAPH.H - H) > 40) render(); } }));
document.addEventListener("keydown", (ev) => { if (ev.key !== "Escape") return; if (state().node) { const s = state(); go({ stage: s.stage, cmp: s.cmp, view: s.view }); } else if (FULL) toggleFull(); });
render();
if (CFG.audit_url && !AUDIT) {
fetch(CFG.audit_url, { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).then((a) => {
if (a && a.verdict && Array.isArray(a.checks)) { AUDIT = a; render(); }
}).catch(() => {});
}
return { render, go, setAudit(a) { AUDIT = a; render(); } };
}
window.Mat2BotTrace = { mount };
const el = document.getElementById("trace-app");
const data = document.getElementById("trace");
if (el && data) {
const cfgEl = document.getElementById("trace-config");
mount(el, JSON.parse(data.textContent), JSON.parse((cfgEl && cfgEl.textContent) || "{}"));
}
})();
</script></body></html> |