Babu09 commited on
Commit
bcf68b0
·
verified ·
1 Parent(s): fdbad60

Mat2Bot front: one box, the story (no engine code)

Browse files
Files changed (6) hide show
  1. app.py +5 -2
  2. story/story.css +4 -0
  3. story/story.html +8 -0
  4. story/story.js +8 -2
  5. story/viewer.css +108 -0
  6. story/viewer.js +368 -0
app.py CHANGED
@@ -36,14 +36,17 @@ app = FastAPI(title="Mat2Bot", docs_url=None, redoc_url=None)
36
 
37
 
38
  def _assets() -> dict[str, str]:
39
- return {k: (HERE / "story" / f"story.{k}").read_text(encoding="utf-8") for k in ("html", "js", "css")}
 
 
40
 
41
 
42
  def fill_story(assets: dict[str, str], *, api_base: str, nav: dict[str, str], engine: str) -> str:
43
  """The same filling as mat2bot.trace.page.fill_story (kept in step by a test there)."""
44
  cfg = json.dumps({"api_base": api_base, "engine": engine}, ensure_ascii=False).replace("</", "<\\/")
45
  links = "".join(f'<a href="{html.escape(url)}">{html.escape(text)}</a>' for text, url in nav.items())
46
- return (assets["html"].replace("__CSS__", assets["css"]).replace("__CONFIG__", cfg).replace("__NAV__", links)
 
47
  .replace("__JS__", assets["js"].replace("</script", "<\\/script")))
48
 
49
 
 
36
 
37
 
38
  def _assets() -> dict[str, str]:
39
+ out = {k: (HERE / "story" / f"story.{k}").read_text(encoding="utf-8") for k in ("html", "js", "css")}
40
+ out["vjs"], out["vcss"] = (HERE / "story" / "viewer.js").read_text(encoding="utf-8"), (HERE / "story" / "viewer.css").read_text(encoding="utf-8")
41
+ return out
42
 
43
 
44
  def fill_story(assets: dict[str, str], *, api_base: str, nav: dict[str, str], engine: str) -> str:
45
  """The same filling as mat2bot.trace.page.fill_story (kept in step by a test there)."""
46
  cfg = json.dumps({"api_base": api_base, "engine": engine}, ensure_ascii=False).replace("</", "<\\/")
47
  links = "".join(f'<a href="{html.escape(url)}">{html.escape(text)}</a>' for text, url in nav.items())
48
+ return (assets["html"].replace("__VIEWER_CSS__", assets["vcss"]).replace("__CSS__", assets["css"]).replace("__CONFIG__", cfg)
49
+ .replace("__NAV__", links).replace("__VIEWER_JS__", assets["vjs"].replace("</script", "<\\/script"))
50
  .replace("__JS__", assets["js"].replace("</script", "<\\/script")))
51
 
52
 
story/story.css CHANGED
@@ -46,3 +46,7 @@ input:focus,textarea:focus{outline:2px solid var(--accent);outline-offset:1px}
46
  .st-muted{color:var(--muted)}
47
  .st-pre{white-space:pre-wrap;font-family:ui-monospace,monospace;font-size:.84rem}
48
  @media (max-width:600px){h1{font-size:1.5rem}}
 
 
 
 
 
46
  .st-muted{color:var(--muted)}
47
  .st-pre{white-space:pre-wrap;font-family:ui-monospace,monospace;font-size:.84rem}
48
  @media (max-width:600px){h1{font-size:1.5rem}}
49
+
50
+ /* the map on the story page */
51
+ .st-map{margin-top:1.6em}.st-h2{font-size:1.25rem;margin:.2em 0 .2em}.st-lead2{margin:0 0 .6em;max-width:70ch}
52
+ #map .tv-tabs{margin:.4em 0 .8em}#map .tv-panel{z-index:50}
story/story.html CHANGED
@@ -5,6 +5,7 @@
5
  <meta name="viewport" content="width=device-width,initial-scale=1">
6
  <title>Mat2Bot: how would you make it?</title>
7
  <style>__CSS__</style>
 
8
  </head>
9
  <body>
10
  <script id="story-config" type="application/json">__CONFIG__</script>
@@ -30,10 +31,17 @@
30
  <div id="status" class="st-status" aria-live="polite"></div>
31
  <div id="forms" class="st-forms"></div>
32
  </section>
 
 
 
 
 
 
33
  <section id="story" class="st-story" hidden></section>
34
  <footer class="st-foot">Plans are arguments with their evidence, not instructions to run: no experiment is authorized without a named person's sign-off.
35
  <span id="st-engine"></span></footer>
36
  </main>
 
37
  <script>__JS__</script>
38
  </body>
39
  </html>
 
5
  <meta name="viewport" content="width=device-width,initial-scale=1">
6
  <title>Mat2Bot: how would you make it?</title>
7
  <style>__CSS__</style>
8
+ <style>__VIEWER_CSS__</style>
9
  </head>
10
  <body>
11
  <script id="story-config" type="application/json">__CONFIG__</script>
 
31
  <div id="status" class="st-status" aria-live="polite"></div>
32
  <div id="forms" class="st-forms"></div>
33
  </section>
34
+ <section id="map-section" class="st-map" hidden>
35
+ <h2 class="st-h2">How Mat2Bot got there: the map</h2>
36
+ <p class="st-muted st-lead2">The stages left to right, with what each one produced underneath. Every box is one of Mat2Bot's own records: click it to see
37
+ the record, its sources and its doubts; click a stage for all of its records and the lines between them.</p>
38
+ <div id="map"></div>
39
+ </section>
40
  <section id="story" class="st-story" hidden></section>
41
  <footer class="st-foot">Plans are arguments with their evidence, not instructions to run: no experiment is authorized without a named person's sign-off.
42
  <span id="st-engine"></span></footer>
43
  </main>
44
+ <script>__VIEWER_JS__</script>
45
  <script>__JS__</script>
46
  </body>
47
  </html>
story/story.js CHANGED
@@ -52,6 +52,7 @@
52
  const out = await post("/api/plan", req);
53
  const pid = out.report.split("/").pop();
54
  status("Reading the plan's records…");
 
55
  const trace = await (await fetch(`${API}/p/${pid}/trace.json`)).json();
56
  let audit = null;
57
  try { audit = await (await fetch(`${API}/p/${pid}/audit.json`, { cache: "no-store" })).json(); } catch { /* shown as not run */ }
@@ -83,7 +84,7 @@
83
  const rivals = byKind("rival");
84
  const best = routes[0] || null;
85
  const ofRoute = (k, n) => t.nodes.filter((x) => x.kind === k && n && x.detail && x.detail.route === n.detail.route);
86
- const links = { trail: `${API}/p/${pid}/trace`, report: `${API}/p/${pid}`, zip: `${API}/p/${pid}/package.zip` };
87
  const steps = [];
88
  // 1 what you asked for
89
  const forms = (d.known_phases || []).map((p) => esc(p.name));
@@ -135,8 +136,13 @@
135
  steps.push(["Checked by an independent auditor", a ? `${chip(a.verdict === "PASS" ? ["audit PASS", "ok"] : a.verdict === "FAIL" ? ["audit FAIL", "bad"] : ["audit unknown", "warn"])} ${plural(a.checks.filter((c) => c.verdict === "PASS").length, "check passed", "checks passed")}${a.checks.some((c) => c.verdict === "FAIL") ? `, ${a.checks.filter((c) => c.verdict === "FAIL").length} failed` : ""}; ${esc(a.when || "")}. The auditor never calls the planner: it re-derives the numbers from the package alone.` : `${chip(["not run", "off"])} ${esc((stageAudit && stageAudit.detail.message) || "the package has not been audited")}`,
136
  more(a ? "Every check" : "", a ? li(a.checks.map((c) => `${chip(c.verdict === "PASS" ? ["pass", "ok"] : c.verdict === "FAIL" ? ["fail", "bad"] : ["n/a", "off"])} ${esc(c.name)}${c.detail ? ` <small>— ${esc(c.detail)}</small>` : ""}`)) : "")]);
137
  $("#story").innerHTML = steps.map(([h, sum, det], i) => `<section class="st-step"><span class="n">Step ${i + 1} of 8</span><h2>${esc(h)}</h2><p class="sum">${sum}</p>${det}</section>`).join("")
138
- + `<div class="st-links"><a class="primary" href="${esc(links.trail)}">Open the full trail: every record, clickable</a><a href="${esc(links.report)}">Technical report</a><a href="${esc(links.zip)}" download>Download the sealed package</a></div>`;
139
  $("#story").hidden = false;
 
 
 
 
 
140
  document.title = `${target.label}: how would you make it? · Mat2Bot`;
141
  if (history.replaceState) history.replaceState(null, "", `#plan=${encodeURIComponent(pid)}`);
142
  }
 
52
  const out = await post("/api/plan", req);
53
  const pid = out.report.split("/").pop();
54
  status("Reading the plan's records…");
55
+ $("#map-section").hidden = true;
56
  const trace = await (await fetch(`${API}/p/${pid}/trace.json`)).json();
57
  let audit = null;
58
  try { audit = await (await fetch(`${API}/p/${pid}/audit.json`, { cache: "no-store" })).json(); } catch { /* shown as not run */ }
 
84
  const rivals = byKind("rival");
85
  const best = routes[0] || null;
86
  const ofRoute = (k, n) => t.nodes.filter((x) => x.kind === k && n && x.detail && x.detail.route === n.detail.route);
87
+ const links = { trail: `${API}/p/${pid}/trace`, report: `${API}/p/${pid}`, zip: `${API}/p/${pid}/package.zip`, package: `${API}/p/${pid}/package.zip` };
88
  const steps = [];
89
  // 1 what you asked for
90
  const forms = (d.known_phases || []).map((p) => esc(p.name));
 
136
  steps.push(["Checked by an independent auditor", a ? `${chip(a.verdict === "PASS" ? ["audit PASS", "ok"] : a.verdict === "FAIL" ? ["audit FAIL", "bad"] : ["audit unknown", "warn"])} ${plural(a.checks.filter((c) => c.verdict === "PASS").length, "check passed", "checks passed")}${a.checks.some((c) => c.verdict === "FAIL") ? `, ${a.checks.filter((c) => c.verdict === "FAIL").length} failed` : ""}; ${esc(a.when || "")}. The auditor never calls the planner: it re-derives the numbers from the package alone.` : `${chip(["not run", "off"])} ${esc((stageAudit && stageAudit.detail.message) || "the package has not been audited")}`,
137
  more(a ? "Every check" : "", a ? li(a.checks.map((c) => `${chip(c.verdict === "PASS" ? ["pass", "ok"] : c.verdict === "FAIL" ? ["fail", "bad"] : ["n/a", "off"])} ${esc(c.name)}${c.detail ? ` <small>— ${esc(c.detail)}</small>` : ""}`)) : "")]);
138
  $("#story").innerHTML = steps.map(([h, sum, det], i) => `<section class="st-step"><span class="n">Step ${i + 1} of 8</span><h2>${esc(h)}</h2><p class="sum">${sum}</p>${det}</section>`).join("")
139
+ + `<div class="st-links"><a class="primary" href="#map-section">Back to the map</a><a href="${esc(links.trail)}">The trail on its own page</a><a href="${esc(links.report)}">Technical report</a><a href="${esc(links.zip)}" download>Download the sealed package</a></div>`;
140
  $("#story").hidden = false;
141
+ if (window.Mat2BotTrace) {
142
+ $("#map").innerHTML = "";
143
+ $("#map-section").hidden = false; // shown first, so the map measures its real width
144
+ window.Mat2BotTrace.mount($("#map"), t, { embedded: true, audit: a, links });
145
+ }
146
  document.title = `${target.label}: how would you make it? · Mat2Bot`;
147
  if (history.replaceState) history.replaceState(null, "", `#plan=${encodeURIComponent(pid)}`);
148
  }
story/viewer.css ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Mat2Bot Trace viewer. Reads trace.json; draws nothing it does not hold. Light and dark; phone first. */
2
+ :root{--bg:#fbfaf7;--fg:#1d1d1b;--muted:#5d5b55;--line:#dedad2;--card:#ffffff;--head:#f1eee7;--accent:#2f5d8a;--hl:#fff1c2;
3
+ --ok:#2e7d32;--warn:#b26a00;--bad:#c62828;--off:#8a8780;--radius:10px}
4
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#161615;--fg:#ecebe6;--muted:#a9a69e;--line:#3a3935;--card:#1f1f1d;
5
+ --head:#22211f;--accent:#8db6e0;--hl:#4a3f12;--ok:#7bc47f;--warn:#e0a64a;--bad:#ef7b7b;--off:#8a8780}}
6
+ :root[data-theme="dark"]{--bg:#161615;--fg:#ecebe6;--muted:#a9a69e;--line:#3a3935;--card:#1f1f1d;--head:#22211f;--accent:#8db6e0;--hl:#4a3f12;
7
+ --ok:#7bc47f;--warn:#e0a64a;--bad:#ef7b7b;--off:#8a8780}
8
+ *{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
9
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
10
+ a{color:var(--accent)}button{font:inherit;cursor:pointer}
11
+ #trace-app{max-width:1280px;margin:0 auto;padding:16px 16px 48px}
12
+ .tv-top{display:flex;flex-wrap:wrap;gap:.5em 1.2em;align-items:baseline;margin-bottom:.4em}
13
+ .tv-top h1{font-size:1.25rem;margin:0}.tv-top nav a{margin-right:1em;text-decoration:none}
14
+ .tv-sub{color:var(--muted);font-size:.9rem;margin:0 0 1em;max-width:90ch}
15
+ .tv-tabs{display:flex;gap:.4em;flex-wrap:wrap;margin:.6em 0 1em}
16
+ .tv-tabs button{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:.35em .9em}
17
+ .tv-tabs button[aria-current="page"]{background:var(--accent);color:var(--bg);border-color:var(--accent)}
18
+ .tv-crumb{font-size:.9rem;color:var(--muted);margin-bottom:.6em}.tv-crumb a{text-decoration:none}
19
+ /* overview: the stages */
20
+ .tv-stages{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.6em}
21
+ .tv-stage{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:.7em .8em;text-align:left;color:var(--fg);
22
+ display:flex;flex-direction:column;gap:.35em;min-height:9.5em}
23
+ .tv-stage:hover,.tv-stage:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
24
+ .tv-stage .n{font-size:.75rem;color:var(--muted);letter-spacing:.04em}.tv-stage b{font-size:1rem}
25
+ .tv-stage .sum{font-size:.84rem;color:var(--muted);margin:0}.tv-stage .sum li{list-style:none}
26
+ .tv-stage ul{margin:0;padding:0}
27
+ .chip{display:inline-block;font-size:.76rem;padding:.1em .55em;border-radius:999px;border:1px solid var(--line);background:var(--head);
28
+ white-space:nowrap;line-height:1.5}
29
+ .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)}
30
+ .chip.off{border-color:var(--off);color:var(--off)}.chip.acc{border-color:var(--accent);color:var(--accent)}
31
+ .tv-legend{display:flex;flex-wrap:wrap;gap:.4em 1em;font-size:.82rem;color:var(--muted);margin:1em 0}
32
+ .tv-legend span{display:inline-flex;align-items:center;gap:.35em}
33
+ .tv-legend i{display:inline-block;width:22px;height:0;border-top:2px solid var(--accent)}
34
+ .tv-legend i.dash{border-top-style:dashed}.tv-legend i.dot{border-top-style:dotted}.tv-legend i.bad{border-color:var(--bad)}
35
+ .tv-legend i.ok{border-color:var(--ok)}.tv-legend i.muted{border-color:var(--off)}
36
+ /* timeline */
37
+ .tv-timeline{margin-top:1.4em}.tv-timeline h2{font-size:1.05rem;margin:.2em 0 .5em}
38
+ .tv-events{display:grid;gap:.3em;margin:0;padding:0;list-style:none}
39
+ .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);
40
+ padding:.3em 0}
41
+ .tv-events li .seq{color:var(--muted);font-variant-numeric:tabular-nums}.tv-events li .msg{color:var(--muted);font-size:.84rem;display:block}
42
+ .tv-events li.skipped{opacity:.75}
43
+ /* component view */
44
+ .tv-comp{position:relative}
45
+ .tv-groups{display:grid;gap:1em}
46
+ .tv-group h3{font-size:.95rem;margin:.6em 0 .4em;color:var(--accent)}
47
+ .tv-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:.6em;position:relative;z-index:1}
48
+ .tv-card{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:.55em .7em;display:flex;flex-direction:column;gap:.3em;
49
+ font-size:.9rem}
50
+ .tv-card.hl{background:var(--hl);border-color:var(--warn)}
51
+ .tv-card.sel{outline:2px solid var(--accent)}
52
+ .tv-card .k{font-size:.72rem;color:var(--muted);letter-spacing:.04em;text-transform:uppercase}
53
+ .tv-card .lbl{text-align:left;background:none;border:0;padding:0;color:var(--fg);font:inherit;line-height:1.4;overflow-wrap:anywhere}
54
+ .tv-card .lbl:hover{color:var(--accent)}
55
+ .tv-card .chips{display:flex;flex-wrap:wrap;gap:.3em}
56
+ .tv-card .acts{display:flex;flex-wrap:wrap;gap:.3em;margin-top:.1em}
57
+ .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;
58
+ padding:.15em .5em;text-decoration:none}
59
+ .tv-card .rel{font-size:.8rem;color:var(--muted)}.tv-card .rel a{text-decoration:none}
60
+ .tv-kids{margin:.3em 0 0 .6em;padding-left:.6em;border-left:2px solid var(--line);display:grid;gap:.4em}
61
+ svg.tv-edges{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:0;overflow:visible}
62
+ svg.tv-edges path{fill:none;stroke:var(--accent);stroke-width:1.5;opacity:.55}
63
+ svg.tv-edges path.depends_on{stroke:var(--off)}svg.tv-edges path.refuted_by{stroke:var(--bad);stroke-dasharray:5 4}
64
+ svg.tv-edges path.resolved_by{stroke:var(--ok);stroke-dasharray:2 3}svg.tv-edges path.rejected_for{stroke:var(--bad)}
65
+ 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}
66
+ svg.tv-edges path.hl{opacity:1;stroke-width:3}
67
+ .tv-empty{color:var(--muted);font-style:italic}
68
+ /* compare */
69
+ .tv-compare{margin:1em 0;border:1px solid var(--line);border-radius:var(--radius);padding:.6em .9em;background:var(--card);overflow-x:auto}
70
+ .tv-compare table{border-collapse:collapse;font-size:.88rem;width:100%}
71
+ .tv-compare th,.tv-compare td{text-align:left;vertical-align:top;padding:.35em .5em;border-bottom:1px solid var(--line)}
72
+ .tv-compare th{background:var(--head)}
73
+ /* provenance panel */
74
+ .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);
75
+ padding:1em 1em 2em;overflow:auto;z-index:5;font-size:.92rem}
76
+ .tv-panel h2{font-size:1.05rem;margin:.2em 2em .4em 0;overflow-wrap:anywhere}
77
+ .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}
78
+ .tv-panel h3{font-size:.85rem;margin:1em 0 .3em;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
79
+ .tv-panel dl{margin:0;display:grid;grid-template-columns:minmax(7em,auto) 1fr;gap:.25em .8em}
80
+ .tv-panel dt{color:var(--muted)}.tv-panel dd{margin:0;overflow-wrap:anywhere}
81
+ .tv-panel code{font-size:.84em;background:var(--head);padding:.05em .3em;border-radius:4px;overflow-wrap:anywhere}
82
+ .tv-panel ul{margin:.2em 0;padding-left:1.1em}.tv-panel li{margin:.15em 0}
83
+ .tv-panel blockquote{margin:.3em 0;padding:.3em .7em;border-left:3px solid var(--accent);background:var(--head);font-size:.88rem}
84
+ .tv-panel .num{font-size:1.1rem;font-weight:600}
85
+ @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}
86
+ .tv-events li{grid-template-columns:2em 1fr;grid-auto-rows:auto}.tv-events li .msg{grid-column:1/-1}}
87
+ @media (prefers-reduced-motion:no-preference){.tv-card,.tv-stage{transition:background .15s,outline-color .15s}}
88
+ .tv-audit li{list-style:none;font-size:.84rem}
89
+ /* the map: a spine of stages with their branches (SVG) */
90
+ .tv-map{overflow-x:auto;margin:.2em 0 .4em;border:1px solid var(--line);border-radius:var(--radius);background:var(--card);padding:10px}
91
+ .tv-map svg{display:block;max-width:none;font:13px/1.2 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
92
+ .tv-map .mnode{cursor:pointer}.tv-map .mnode:focus{outline:none}
93
+ .tv-map .mnode rect{fill:var(--bg);stroke:var(--line);stroke-width:1.4}
94
+ .tv-map .mnode.stage rect{fill:var(--head);stroke-width:2}
95
+ .tv-map .mnode:hover rect,.tv-map .mnode:focus rect{stroke:var(--accent);stroke-width:2.4}
96
+ .tv-map .mnode text{fill:var(--fg);font-weight:600;pointer-events:none}
97
+ .tv-map .mnode text.sub{font-size:11.5px;font-weight:400;fill:var(--muted)}
98
+ .tv-map .mnode text.sub2{font-size:11px;font-weight:400;fill:var(--muted)}
99
+ .tv-map .mnode.kid text{font-weight:500;font-size:12.5px}
100
+ .tv-map .mnode.more rect{stroke-dasharray:4 3}.tv-map .mnode.more text{fill:var(--accent)}
101
+ .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}
102
+ .tv-map .tone-off text{fill:var(--muted)}
103
+ .tv-map path.spine{fill:none;stroke:var(--accent);stroke-width:2}.tv-map marker path{fill:var(--accent)}
104
+ .tv-map path.branch{fill:none;stroke:var(--line);stroke-width:1.5}
105
+ .tv-legend i.box{width:14px;height:14px;border:2px solid var(--accent);border-radius:4px;border-top-width:2px}
106
+ .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}
107
+ details.tv-timeline summary{cursor:pointer;color:var(--accent);font-size:.95rem;margin:.6em 0 .3em}
108
+ .tv-map .mnode.sel rect{stroke:var(--accent);stroke-width:3}
story/viewer.js ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Mat2Bot Trace viewer: a connected map of the plan's records (the stages with arrows, each stage's branches under
2
+ it), a components view (a stage's records as cards with their typed edges) and a provenance panel (one record),
3
+ over trace.json and nothing else. Every drawn node is a node of the trace and every drawn line an edge of it; the
4
+ audit column is filled only from a live audit the host gives (config.audit_url or config.audit). Plain JS, no library.
5
+ Standalone (trace.html) it keeps its place in the address bar; embedded (the one-box page) it keeps it in memory. */
6
+ (function () {
7
+ "use strict";
8
+ const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
9
+ const WORDS = {
10
+ execution: { completed: ["ran", "ok"], skipped: ["skipped", "off"], refused: ["stopped: refused", "warn"], failed: ["failed", "bad"], not_run: ["not run", "off"] },
11
+ science: { PASS: ["holds", "ok"], FAIL: ["fails", "bad"], UNKNOWN: ["not settled", "warn"], STRONGLY_SUPPORTED: ["strongly supported", "ok"],
12
+ PARTIALLY_SUPPORTED: ["supported, with caveats", "warn"], HYPOTHETICAL: ["hypothetical", "warn"], BLOCKED: ["rejected", "bad"],
13
+ open: ["doubt open", "warn"], eliminated: ["doubt ruled out", "ok"], sustained: ["doubt confirmed", "bad"], refused: ["model refused", "warn"],
14
+ "unresolved values": ["values unresolved", "warn"] },
15
+ evidence: { verified: ["evidence verified", "ok"], unverified: ["evidence not verified", "warn"], missing: ["record missing", "bad"] },
16
+ lab: { FULLY_SUPPORTED: ["robot can run it", "ok"], HYBRID: ["robot and people", "ok"], INCOMPLETE: ["not ready", "warn"], BLOCKED: ["cannot be done here", "bad"],
17
+ missing: ["equipment missing", "bad"], automated: ["automated", "ok"], human_bench: ["a person", "acc"], external: ["outside facility", "acc"],
18
+ human_only: ["a person", "acc"] },
19
+ };
20
+ const EDGE_WORDS = { depends_on: "comes after", supported_by: "rests on", computed_from: "computed from", refuted_by: "doubted by", resolved_by: "settled by",
21
+ produced: "produced", requires_equipment: "needs equipment", rejected_for: "rejected because", cites: "cites", mapped_to: "done with" };
22
+ const KIND_WORDS = { stage: "stage", target: "the target", finding: "finding", route: "route", rival: "rejected route", claim: "claim", inference: "inference",
23
+ evidence: "evidence", calculation: "calculation", model_output: "model", assumption: "assumption", doubt: "doubt", step: "step", hazard: "hazard",
24
+ laboratory: "laboratory", capability: "equipment", grouping: "group" };
25
+ const STAGE_WORDS = { M01: "Target", M02: "Evidence", M04: "Routes", M05: "Science", M07: "The case", M08: "Procedure", LAB: "Laboratories", AUDIT: "Audit" };
26
+ function chip(attr, value) {
27
+ if (value == null || value === "n/a" || value === "") return "";
28
+ const w = (WORDS[attr] || {})[value] || [String(value).replace(/_/g, " "), "acc"];
29
+ return `<span class="chip ${w[1]}" title="${esc(attr)}: ${esc(value)}">${esc(w[0])}</span>`;
30
+ }
31
+ function tone(n) {
32
+ if (n.execution === "refused" || n.execution === "failed") return "bad";
33
+ if (n.execution === "skipped" || n.execution === "not_run") return "off";
34
+ const s = n.science;
35
+ if (s) {
36
+ if (["FAIL", "BLOCKED", "sustained"].includes(s)) return "bad";
37
+ if (["UNKNOWN", "PARTIALLY_SUPPORTED", "HYPOTHETICAL", "open", "refused", "unresolved values"].includes(s)) return "warn";
38
+ if (["PASS", "STRONGLY_SUPPORTED", "eliminated"].includes(s)) return "ok";
39
+ }
40
+ if (n.lab) { if (n.lab === "BLOCKED" || n.lab === "missing") return "bad"; if (n.lab === "INCOMPLETE") return "warn"; if (["FULLY_SUPPORTED", "HYBRID"].includes(n.lab)) return "ok"; }
41
+ if (n.evidence === "missing") return "bad";
42
+ if (n.evidence === "unverified") return "warn";
43
+ if (n.evidence === "verified") return "ok";
44
+ return "";
45
+ }
46
+
47
+ function mount(app, T, CFG) {
48
+ CFG = CFG || {};
49
+ const EMBEDDED = !!CFG.embedded;
50
+ const NODES = new Map(T.nodes.map((n) => [n.node_id, n]));
51
+ const STAGES = (T.layout && T.layout.columns) || ["M01", "M02", "M04", "M05", "M07", "M08", "LAB", "AUDIT"];
52
+ const STAGE_NODE = {};
53
+ T.nodes.forEach((n) => { if (n.kind === "stage") STAGE_NODE[n.stage] = n; });
54
+ const OUT = new Map(), IN = new Map();
55
+ 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); });
56
+ 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("");
57
+ let AUDIT = CFG.audit && CFG.audit.verdict ? CFG.audit : null;
58
+ // ---------------------------------------------------------------- state: the address bar (standalone) or memory (embedded)
59
+ let S = { stage: "", node: "", cmp: [] };
60
+ function parse(h) {
61
+ const o = Object.fromEntries(h.replace(/^#/, "").split("&").filter(Boolean).map((kv) => kv.split("=").map(decodeURIComponent)));
62
+ return { stage: o.stage || "", node: o.node || "", cmp: (o.cmp || "").split(",").filter(Boolean) };
63
+ }
64
+ function state() { return EMBEDDED ? { ...S, cmp: [...S.cmp] } : parse(location.hash); }
65
+ function go(s) {
66
+ s = { stage: s.stage || "", node: s.node || "", cmp: s.cmp || [] };
67
+ if (EMBEDDED) { S = s; render(); return; }
68
+ const parts = [];
69
+ if (s.stage) parts.push("stage=" + encodeURIComponent(s.stage));
70
+ if (s.node) parts.push("node=" + encodeURIComponent(s.node));
71
+ if (s.cmp.length) parts.push("cmp=" + encodeURIComponent(s.cmp.join(",")));
72
+ const next = "#" + parts.join("&");
73
+ if (location.hash !== next) location.hash = next; else render();
74
+ }
75
+ // ---------------------------------------------------------------- the frame
76
+ function frame(s) {
77
+ const links = CFG.links || {};
78
+ 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("");
79
+ const tabs = [["", "Map"], ["__comp", "Components"], ["__prov", "Provenance"]];
80
+ const cur = s.node ? "__prov" : s.stage ? "__comp" : "";
81
+ 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>
82
+ <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>`;
83
+ 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>`;
84
+ }
85
+ // ---------------------------------------------------------------- the map: a spine of stages with their branches
86
+ const NESTING = ["target", "route", "rival", "grouping", "hazard", "laboratory"];
87
+ function topLevel(stage) {
88
+ const all = (STAGE_NODE[stage] || { children: [] }).children.map((id) => NODES.get(id)).filter(Boolean);
89
+ const nested = new Set();
90
+ all.forEach((n) => { if (NESTING.includes(n.kind)) n.children.forEach((c) => nested.add(c)); });
91
+ return all.filter((n) => !nested.has(n.node_id));
92
+ }
93
+ 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 };
94
+ const DOUBT_ORDER = { sustained: 0, open: 1, eliminated: 2 };
95
+ function branches(stage) {
96
+ let ns = topLevel(stage);
97
+ if (stage === "M01") ns = [NODES.get("target"), ...(NODES.get("target") || { children: [] }).children.map((id) => NODES.get(id))].filter(Boolean);
98
+ if (stage === "M07") ns = ns.filter((n) => n.kind !== "claim" || !(n.detail && n.detail.template === "conditions-supported"));
99
+ return ns.slice().sort((a, b) => (ORDER[a.kind] ?? 5) - (ORDER[b.kind] ?? 5) || ((DOUBT_ORDER[a.science] ?? 3) - (DOUBT_ORDER[b.science] ?? 3)));
100
+ }
101
+ function shortLabel(n, max) {
102
+ let t = n.label;
103
+ if (n.kind === "route" || n.kind === "rival") t = ((n.detail && n.detail.precursors) || []).map((p) => p.split(" (")[0]).join(" + ") || t.replace(/^(Route \d+|Rejected): /, "");
104
+ if (n.kind === "laboratory") t = n.label;
105
+ if (n.kind === "doubt") t = t.replace(/ \(here:.*$/, "");
106
+ if (n.kind === "grouping") t = t.replace(/^Procedure of [^:]+: /, "Recipe: ");
107
+ t = t.replace(/^(Route \d+|Rejected): /, "");
108
+ return t.length > max ? t.slice(0, max - 1) + "…" : t;
109
+ }
110
+ function stageSummary(stage) {
111
+ const kids = (STAGE_NODE[stage] || { children: [] }).children.map((id) => NODES.get(id)).filter(Boolean);
112
+ const count = (f) => kids.filter(f).length;
113
+ if (stage === "M01") { const t = NODES.get("target"); return t ? shortLabel(t, 24) : ""; }
114
+ if (stage === "M02") return `${count((n) => n.kind === "evidence")} records`;
115
+ if (stage === "M04") return `${count((n) => n.kind === "route")} proposed, ${count((n) => n.kind === "rival")} set aside`;
116
+ if (stage === "M05") return `${count((n) => n.kind === "calculation")} numbers, ${count((n) => n.kind === "model_output" && n.execution === "refused")} refusals`;
117
+ if (stage === "M07") return `doubts: ${count((n) => n.science === "open")} open, ${count((n) => n.science === "eliminated")} ruled out`;
118
+ if (stage === "M08") return `${count((n) => n.kind === "step")} steps`;
119
+ if (stage === "LAB") return kids.filter((n) => n.kind === "laboratory").map((l) => l.label.split(":")[0]).join(", ") || "none asked";
120
+ if (stage === "AUDIT") return AUDIT ? `${AUDIT.verdict}: ${AUDIT.checks.filter((c) => c.verdict === "PASS").length} checks passed` : "not run";
121
+ return "";
122
+ }
123
+ function mapView() {
124
+ const narrow = app.clientWidth < 720;
125
+ const maxKids = narrow ? 4 : 6;
126
+ const colW = 156, boxH = 60, kidH = 34, gapY = 12, gapX = 18, top = 8;
127
+ const cols = STAGES.map((st) => {
128
+ const n = STAGE_NODE[st] || { label: STAGE_WORDS[st] || st, execution: "not_run", children: [] };
129
+ const kids = st === "AUDIT" ? [] : branches(st);
130
+ return { st, n, kids: kids.slice(0, maxKids), more: Math.max(0, kids.length - maxKids), total: kids.length };
131
+ });
132
+ const parts = [];
133
+ const node = (x, y, w, h, cls, attrs, title, lines, sub) => `<g class="mnode ${cls}" ${attrs} tabindex="0" role="button"><title>${esc(title)}</title>
134
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="9"></rect>
135
+ <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>`;
136
+ let W, H;
137
+ if (!narrow) {
138
+ W = STAGES.length * colW + (STAGES.length - 1) * gapX;
139
+ const rows = Math.max(...cols.map((c) => c.kids.length + (c.more ? 1 : 0)), 1);
140
+ H = top + boxH + 26 + rows * (kidH + gapY) + 8;
141
+ cols.forEach((c, i) => {
142
+ const x = i * (colW + gapX);
143
+ const ex = c.st === "AUDIT" && AUDIT ? (AUDIT.verdict === "PASS" ? "completed" : "failed") : c.n.execution;
144
+ const w = (WORDS.execution[ex] || [ex, "off"]);
145
+ 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)));
146
+ 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>`);
147
+ let y = top + boxH + 26;
148
+ c.kids.forEach((k) => {
149
+ parts.push(`<path class="branch" d="M${x + 18},${top + boxH} L${x + 18},${y + kidH / 2} L${x + 30},${y + kidH / 2}"></path>`);
150
+ parts.push(node(x + 30, y, colW - 30, kidH, `kid tone-${tone(k)}`, `data-node="${esc(k.node_id)}"`, k.label, [shortLabel(k, 17)], ""));
151
+ y += kidH + gapY;
152
+ });
153
+ if (c.more) {
154
+ parts.push(`<path class="branch" d="M${x + 18},${top + boxH} L${x + 18},${y + kidH / 2} L${x + 30},${y + kidH / 2}"></path>`);
155
+ parts.push(node(x + 30, y, colW - 30, kidH, "kid more", `data-stage="${esc(c.st)}"`, `${c.total} in this stage`, [`+${c.more} more…`], ""));
156
+ }
157
+ });
158
+ } else {
159
+ W = Math.max(app.clientWidth - 24, 300); // inside the box's padding
160
+ const sx = 12, bx = 34, kx = 56; // the spine at the left edge, the branches beside it, the boxes after
161
+ const kidW = W - kx;
162
+ let y = top;
163
+ cols.forEach((c, i) => {
164
+ const ex = c.st === "AUDIT" && AUDIT ? (AUDIT.verdict === "PASS" ? "completed" : "failed") : c.n.execution;
165
+ const w = (WORDS.execution[ex] || [ex, "off"]);
166
+ 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)));
167
+ let ky = y + boxH + gapY;
168
+ c.kids.forEach((k) => {
169
+ parts.push(`<path class="branch" d="M${bx},${y + boxH} L${bx},${ky + kidH / 2} L${kx},${ky + kidH / 2}"></path>`);
170
+ parts.push(node(kx, ky, kidW, kidH, `kid tone-${tone(k)}`, `data-node="${esc(k.node_id)}"`, k.label, [shortLabel(k, 40)], ""));
171
+ ky += kidH + gapY;
172
+ });
173
+ if (c.more) {
174
+ parts.push(`<path class="branch" d="M${bx},${y + boxH} L${bx},${ky + kidH / 2} L${kx},${ky + kidH / 2}"></path>`);
175
+ parts.push(node(kx, ky, kidW, kidH, "kid more", `data-stage="${esc(c.st)}"`, `${c.total} in this stage`, [`+${c.more} more…`], ""));
176
+ ky += kidH + gapY;
177
+ }
178
+ 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>`);
179
+ y = ky + 18;
180
+ });
181
+ H = y;
182
+ }
183
+ 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>`;
184
+ 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;
185
+ }
186
+ function overview() {
187
+ 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("");
188
+ 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>
189
+ <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>`;
190
+ }
191
+ // ---------------------------------------------------------------- component view
192
+ function groupsOf(stage) {
193
+ const kids = topLevel(stage);
194
+ const byRoute = new Map();
195
+ 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); });
196
+ return [...byRoute.entries()];
197
+ }
198
+ function short(n) { return n ? (n.label.length > 48 ? n.label.slice(0, 46) + "…" : n.label) : "?"; }
199
+ function relChips(n, visible) {
200
+ const out = [];
201
+ (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>`); });
202
+ (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>`); });
203
+ return out.length ? `<div class="rel">${out.slice(0, 6).join(" · ")}${out.length > 6 ? ` · +${out.length - 6}` : ""}</div>` : "";
204
+ }
205
+ function card(n, visible, s, depth) {
206
+ const kidsShown = depth < 1 && n.children.length && NESTING.includes(n.kind) ? n.children : [];
207
+ const acts = [];
208
+ if (n.kind === "rival") acts.push(`<button type="button" data-why="${esc(n.node_id)}">Why was it rejected?</button>`);
209
+ if (n.kind === "route") acts.push(`<button type="button" data-cmp="${esc(n.node_id)}">${(s.cmp || []).includes(n.node_id) ? "Comparing ✓" : "Compare"}</button>`);
210
+ if (n.children.length && !kidsShown.length) acts.push(`<button type="button" data-open="${esc(n.node_id)}">Show ${n.children.length} inside</button>`);
211
+ acts.push(`<a href="#node=${encodeURIComponent(n.node_id)}">Details</a>`);
212
+ return `<div class="tv-card" data-id="${esc(n.node_id)}"><span class="k">${esc(KIND_WORDS[n.kind] || n.kind)}</span>
213
+ <button type="button" class="lbl" data-node="${esc(n.node_id)}">${esc(n.label)}</button><div class="chips">${chips(n)}</div>${relChips(n, visible)}
214
+ <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>`;
215
+ }
216
+ function component(s) {
217
+ const st = s.stage;
218
+ const groups = groupsOf(st);
219
+ const visible = new Set();
220
+ groups.forEach(([, ns]) => ns.forEach((n) => { visible.add(n.node_id); n.children.forEach((c) => visible.add(c)); }));
221
+ const stn = STAGE_NODE[st];
222
+ const head = `<p class="tv-crumb"><a href="#">Map</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>`;
223
+ if (st === "AUDIT") return head + auditView();
224
+ if (!groups.length) return head + `<p class="tv-empty">Nothing was recorded for this stage${stn && stn.execution === "skipped" ? ": it was skipped" : ""}.</p>`;
225
+ 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("");
226
+ return head + legend() + `<div class="tv-comp"><svg class="tv-edges" aria-hidden="true"></svg><div class="tv-groups">${body}</div></div>` + compare(s);
227
+ }
228
+ function legend() {
229
+ 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>
230
+ <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>`;
231
+ }
232
+ function auditView() {
233
+ 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 &lt;package&gt;</code> to re-derive every claim from the files alone."}</p>`;
234
+ return `<p>${esc(AUDIT.when || "")}: <b>${esc(AUDIT.verdict)}</b>${CFG.links && CFG.links.audit ? ` · <a href="${esc(CFG.links.audit)}">the full audit page</a>` : ""}</p>
235
+ <ul class="tv-audit">${AUDIT.checks.map((c) => `<li>${chip("science", c.verdict === "UNKNOWN" ? "UNKNOWN" : c.verdict)} ${esc(c.name)}${c.detail ? ` <small>— ${esc(c.detail)}</small>` : ""}</li>`).join("")}</ul>`;
236
+ }
237
+ function drawEdges() {
238
+ const svg = app.querySelector("svg.tv-edges");
239
+ if (!svg) return;
240
+ const box = svg.parentElement.getBoundingClientRect();
241
+ 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 }; };
242
+ const paths = [];
243
+ T.edges.forEach((e) => {
244
+ const a = at(e.source), b = at(e.target);
245
+ if (!a || !b) return;
246
+ const mx = (a.x + b.x) / 2;
247
+ 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>`);
248
+ });
249
+ svg.setAttribute("viewBox", `0 0 ${box.width} ${box.height}`);
250
+ svg.innerHTML = paths.join("");
251
+ }
252
+ function highlight(id, on) {
253
+ app.querySelectorAll("svg.tv-edges path").forEach((p) => { if (p.dataset.s === id || p.dataset.t === id) p.classList.toggle("hl", on); });
254
+ }
255
+ function why(id) {
256
+ app.querySelectorAll(".tv-card.hl").forEach((c) => c.classList.remove("hl"));
257
+ const targets = (OUT.get(id) || []).filter((e) => e.kind === "rejected_for").map((e) => e.target);
258
+ let first = null;
259
+ targets.forEach((t) => { const el = app.querySelector(`.tv-card[data-id="${CSS.escape(t)}"]`); if (el) { el.classList.add("hl"); first = first || el; } });
260
+ highlight(id, true);
261
+ if (first) first.scrollIntoView({ block: "center", behavior: "smooth" });
262
+ else if (targets.length) go({ stage: state().stage, node: targets[0] });
263
+ }
264
+ function compare(s) {
265
+ const ids = (s.cmp || []).slice(0, 2).map((id) => NODES.get(id)).filter(Boolean);
266
+ if (ids.length < 2) return ids.length === 1 ? `<p class="tv-sub">Pick a second route to compare with ${esc(short(ids[0]))}.</p>` : "";
267
+ const row = (name, f) => `<tr><th>${name}</th>${ids.map((n) => `<td>${f(n)}</td>`).join("")}</tr>`;
268
+ 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";
269
+ const labs = (n) => T.nodes.filter((l) => l.kind === "laboratory" && l.detail.route === n.detail.route).map((l) => esc(l.label)).join("<br>") || "–";
270
+ 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>
271
+ ${row("Support", (n) => chip("science", n.science) + ` <small>${esc(n.detail.row)}</small>`)}
272
+ ${row("Precedent", (n) => esc(n.detail.precedent))}
273
+ ${row("Reagents", (n) => (n.detail.precursors || []).map(esc).join("<br>"))}
274
+ ${row("Conditions", (n) => Object.entries(n.detail.parameters || {}).map(([k, v]) => `${esc(k)} = ${esc(v)}`).join("<br>") || "none stated")}
275
+ ${row("Equipment", (n) => (n.detail.equipment || []).map(esc).join("<br>"))}
276
+ ${row("Open doubts", doubts)}${row("Laboratories", labs)}</tbody></table>
277
+ <p><button type="button" data-cmp-clear="1">Clear</button></p></div>`;
278
+ }
279
+ // ---------------------------------------------------------------- provenance panel
280
+ function link(url, text) { return url && /^https?:\/\//.test(url) ? `<a href="${esc(url)}" rel="noopener" target="_blank">${esc(text || url)}</a>` : esc(text || url || ""); }
281
+ function value(d) {
282
+ if (d.value == null && !("unit" in d)) return "";
283
+ const u = d.uncertainty;
284
+ 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>
285
+ <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>
286
+ ${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>` : ""}
287
+ ${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>` : ""}`;
288
+ }
289
+ function generic(d, skip) {
290
+ 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));
291
+ if (!rows.length) return "";
292
+ return `<dl>${rows.map(([k, v]) => `<dt>${esc(k.replace(/_/g, " "))}</dt><dd>${fmt(v)}</dd>`).join("")}</dl>`;
293
+ }
294
+ function fmt(v) {
295
+ if (Array.isArray(v)) return `<ul>${v.map((x) => `<li>${typeof x === "object" ? fmt(x) : esc(x)}</li>`).join("")}</ul>`;
296
+ if (typeof v === "object") return `<dl>${Object.entries(v).map(([k, x]) => `<dt>${esc(k)}</dt><dd>${fmt(x)}</dd>`).join("")}</dl>`;
297
+ if (typeof v === "string" && /^https?:\/\//.test(v)) return link(v);
298
+ if (typeof v === "string" && /^R-[A-Z0-9-]+-\d{3}$/.test(v)) return `<code>${esc(v)}</code>`;
299
+ return esc(v);
300
+ }
301
+ function panel(id) {
302
+ const n = NODES.get(id);
303
+ 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>`;
304
+ const d = n.detail || {};
305
+ let body = "";
306
+ if (n.kind === "calculation" && "value" in d) body = value(d);
307
+ 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"])}`;
308
+ 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>`;
309
+ else body = generic(d, ["route"]);
310
+ 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("");
311
+ const outs = OUT.get(id) || [], ins = IN.get(id) || [];
312
+ 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"],
313
+ ["What rests on it, or questions it", ins, "in"]];
314
+ return `<aside class="tv-panel" role="dialog" aria-label="record"><button type="button" class="close" data-close="1">Close</button>
315
+ <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>
316
+ ${body}${q.map(([t, es, dir]) => es.length ? `<h3>${t}</h3><ul>${rel(es, dir)}</ul>` : "").join("")}
317
+ ${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>` : ""}
318
+ <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>`;
319
+ }
320
+ // ---------------------------------------------------------------- render and events
321
+ function render() {
322
+ const s = state();
323
+ app.innerHTML = frame(s) + (s.stage ? component(s) : overview(s)) + (s.node ? panel(s.node) : "");
324
+ if (s.stage) requestAnimationFrame(drawEdges);
325
+ if (s.node) {
326
+ const el = app.querySelector(`.tv-card[data-id="${CSS.escape(s.node)}"]`);
327
+ if (el) { el.classList.add("sel"); highlight(s.node, true); }
328
+ const g = app.querySelector(`g.mnode[data-node="${CSS.escape(s.node)}"]`);
329
+ if (g) g.classList.add("sel");
330
+ }
331
+ }
332
+ app.addEventListener("click", (ev) => {
333
+ const b = ev.target.closest("[data-tab],[data-stage],[data-node],[data-why],[data-open],[data-cmp],[data-cmp-clear],[data-close],a[href^='#']");
334
+ if (!b || !app.contains(b)) return;
335
+ const s = state();
336
+ if (b.dataset.tab != null) { ev.preventDefault(); if (b.dataset.tab === "") go({}); 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; }
337
+ if (b.dataset.stage) { ev.preventDefault(); go({ stage: b.dataset.stage }); return; }
338
+ if (b.dataset.node) { ev.preventDefault(); go({ stage: s.stage, node: b.dataset.node, cmp: s.cmp }); return; }
339
+ if (b.dataset.why) { why(b.dataset.why); return; }
340
+ 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; }
341
+ 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; }
342
+ if (b.dataset.cmpClear) { go({ stage: s.stage, node: s.node, cmp: [] }); return; }
343
+ if (b.dataset.close) { go({ stage: s.stage, cmp: s.cmp }); return; }
344
+ 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 }); }
345
+ });
346
+ 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 })); } });
347
+ app.addEventListener("mouseover", (ev) => { const c = ev.target.closest(".tv-card"); if (c) highlight(c.dataset.id, true); });
348
+ app.addEventListener("mouseout", (ev) => { const c = ev.target.closest(".tv-card"); if (c && c.dataset.id !== state().node) highlight(c.dataset.id, false); });
349
+ if (!EMBEDDED) window.addEventListener("hashchange", render);
350
+ window.addEventListener("resize", () => requestAnimationFrame(() => { if (state().stage) drawEdges(); else render(); }));
351
+ document.addEventListener("keydown", (ev) => { if (ev.key === "Escape" && state().node) { const s = state(); go({ stage: s.stage, cmp: s.cmp }); } });
352
+ render();
353
+ if (CFG.audit_url && !AUDIT) {
354
+ fetch(CFG.audit_url, { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).then((a) => {
355
+ if (a && a.verdict && Array.isArray(a.checks)) { AUDIT = a; render(); }
356
+ }).catch(() => {});
357
+ }
358
+ return { render, go, setAudit(a) { AUDIT = a; render(); } };
359
+ }
360
+
361
+ window.Mat2BotTrace = { mount };
362
+ const el = document.getElementById("trace-app");
363
+ const data = document.getElementById("trace");
364
+ if (el && data) {
365
+ const cfgEl = document.getElementById("trace-config");
366
+ mount(el, JSON.parse(data.textContent), JSON.parse((cfgEl && cfgEl.textContent) || "{}"));
367
+ }
368
+ })();