Author SHA1 Message Date
onibot e365f6d1e8 feat: floop-inspect — the post-mortem HTML debugger (PR B)
One run dir in -> ONE self-contained inspect.html out. The events are
inlined as JSON; the page opens offline from file:// with ZERO network
references. Four views (owner 26/10: IDE-like debugging a posteriori):

- timeline: every component as a bar in time order — LLM calls (with
  real durations) vs code nodes colored differently; click a bar -> its
  in/out in the header detail line. The 'which expert are we inside'
  view.
- kg: the snapshot graph on canvas (spring layout, vanilla JS): nodes
  sized by degree, edges with temporal windows, THIS RUN's touched edges
  highlighted in accent blue, click a node/edge -> detail (subject, rel,
  object, window, last-touch event).
- facts: the two-pass debug table — claims per chunk, each claim ->
  typed fact (or declined), each merge verdict with reason.
- probes: per question what the hybrid probe returned (seeds, rows,
  semantic adds, tau) and the prover's DSL + verdict + bindings.

Fixed on real render (browser-verified): the KG canvas measured 0x0
while its tab was hidden (display:none) — layout now runs lazily on
first visible draw and every tab activation dispatches a resize, so
the canvas paints correctly (verified: painted pixels present, all
four tabs render content).

TDD: inspect_html 3/3 (self-contained offline, honest error without
events, empty run renders). Suite: 32 test files green.
Usage: python -m floop.inspect_html runs/<ts>/
2026-10-27 07:47:21 +01:00
2 changed files with 425 additions and 0 deletions
+317
View File
@@ -0,0 +1,317 @@
"""floop-inspect — the post-mortem HTML debugger (PR B).
One run dir in -> ONE self-contained inspect.html out. The events are
inlined as JSON; the page opens offline from file:// with zero network
references. Four views (owner 26/10):
- timeline: every component as a bar in time order (LLM vs code
colored), the 'where inside which expert are we' view
- kg: the snapshot graph (canvas, force layout, temporal windows +
last-touch highlighted)
- facts: the two-pass debug table (claim -> typed fact -> merge
verdict, rejections with reason)
- probes: per question, what the semantic search returned
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
def generate(run_dir: str | Path) -> Path:
run_dir = Path(run_dir)
ev_path = run_dir / "events.jsonl"
if not ev_path.exists():
print(f"no events.jsonl in {run_dir} — nothing to inspect",
file=sys.stderr)
raise SystemExit(1)
events = []
for line in ev_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line:
try:
events.append(json.loads(line))
except json.JSONDecodeError:
pass # torn line mid-crash: skip, honest
html = _render(events)
out = run_dir / "inspect.html"
out.write_text(html, encoding="utf-8")
return out
def main(argv: list[str]) -> int:
if len(argv) != 2:
print("usage: python -m floop.inspect_html <run_dir>", file=sys.stderr)
return 2
out = generate(argv[1])
print(f"inspect: {out}")
return 0
def _render(events: list[dict]) -> str:
payload = json.dumps(events, default=str)
return _TEMPLATE.replace("__EVENTS__", payload)
# ---- the page (vanilla JS, no deps, no network) ---------------------------
_TEMPLATE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>floop-inspect</title>
<style>
:root { --bg:#111; --fg:#ddd; --dim:#888; --acc:#4cc2ff; --llm:#c678dd;
--ok:#98c379; --bad:#e06c75; --line:#2a2a2a; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--fg);
font:13px/1.45 "JetBrains Mono","Fira Code",monospace; }
header { padding:10px 16px; border-bottom:1px solid var(--line);
position:sticky; top:0; background:var(--bg); z-index:9; }
header b { color:var(--acc); }
nav button { background:none; border:1px solid var(--line); color:var(--dim);
padding:4px 12px; margin-right:6px; cursor:pointer; border-radius:3px;
font:inherit; }
nav button.on { color:var(--fg); border-color:var(--acc); }
.view { display:none; padding:14px 16px; }
.view.on { display:block; }
#timeline { width:100%; height:60vh; }
.bar { position:absolute; height:18px; border-radius:3px; opacity:.9; }
.bar:hover { outline:1px solid #fff; }
.bar.llm { background:var(--llm); } .bar.code { background:var(--acc); }
.bar.bad { background:var(--bad); }
table { border-collapse:collapse; width:100%; margin-top:8px; }
th,td { text-align:left; padding:4px 8px; border-bottom:1px solid var(--line);
vertical-align:top; max-width:480px; overflow-wrap:break-word; }
th { color:var(--dim); font-weight:normal; }
td.ok { color:var(--ok); } td.bad { color:var(--bad); }
.pill { display:inline-block; border-radius:8px; padding:0 8px;
border:1px solid var(--line); color:var(--dim); font-size:11px; }
#kg { width:100%; height:65vh; background:#0b0b0b; border-radius:6px; }
#detail { color:var(--dim); padding:6px 0; min-height:24px; }
h3 { color:var(--acc); margin:14px 0 4px; font-size:13px; }
.final { border:1px solid var(--ok); border-radius:4px; padding:8px 12px;
margin:8px 0; }
</style>
</head>
<body>
<header>
<b>floop-inspect</b> — post-mortem debugger &nbsp;
<span id="stats"></span>
<nav>
<button data-v="timeline" class="on">timeline</button>
<button data-v="kg">kg</button>
<button data-v="facts">facts</button>
<button data-v="probes">probes</button>
</nav>
<div id="detail">hover/click a bar or node</div>
</header>
<div id="timeline" class="view on"></div>
<div id="kg" class="view"><canvas id="kgc"></canvas></div>
<div id="facts" class="view"></div>
<div id="probes" class="view"></div>
<script>
const EV = __EVENTS__;
const $ = (s) => document.querySelector(s);
// ---------- stats ----------
const llms = EV.filter(e => e.event === 'llm.done');
const total = llms.reduce((a,e) => a + (e.dur_s||0), 0);
$('#stats').textContent =
`${EV.length} events · ${llms.length} llm calls · ${total.toFixed(1)}s llm time` +
(EV.some(e=>e.event==='run.final') ? '' : ' · no final answer');
// ---------- tabs ----------
document.querySelectorAll('nav button').forEach(b => b.onclick = () => {
document.querySelectorAll('nav button').forEach(x=>x.classList.remove('on'));
document.querySelectorAll('.view').forEach(x=>x.classList.remove('on'));
b.classList.add('on'); $('#'+b.dataset.v).classList.add('on');
window.dispatchEvent(new Event('resize')); // hidden views measure 0 —
}); // remeasure on every activation
// ---------- timeline ----------
(() => {
const box = $('#timeline');
const t0 = EV.length ? (new Date('2000-01-01T'+EV[0].ts)).getTime() : 0;
const tN = EV.length ? (new Date('2000-01-01T'+EV[EV.length-1].ts)).getTime() : 1;
const span = Math.max(tN - t0, 1);
const W = () => box.clientWidth, H = () => box.clientHeight;
const rows = new Map(); // comp -> row index
const bars = [];
// pair llm.done with the nearest preceding comp.start of the same stage
let open = {};
for (const e of EV) {
if (e.event === 'comp.start') open[e.comp] = e;
else if (e.event === 'llm.done') {
bars.push({...e, kind:'llm', label:e.stage, ev:e});
} else if (e.event === 'comp.out' || e.event === 'state' ||
e.event === 'comp.done') {
const c = e.comp || '?';
bars.push({ts:e.ts, dur:0, kind:'code', label:c, ev:e});
} else if (e.event === 'fact.merged' || e.event === 'fact.rejected' ||
e.event === 'claims.done' || e.event === 'type.done' ||
e.event === 'probe.done' || e.event === 'prover.done') {
bars.push({ts:e.ts, dur:0, kind:'code', label:e.event, ev:e});
}
}
bars.forEach(b => { if (!rows.has(b.label)) rows.set(b.label, rows.size); });
const rowH = 24;
const px = (ts) => ((new Date('2000-01-01T'+ts)).getTime() - t0) / span * (W()-140) + 120;
const durPx = (d) => Math.max(d/span*(W()-140), 4);
bars.forEach(b => {
const x = px(b.ts), w = b.kind==='llm' ? Math.max(durPx((b.dur_s||0)*1000),4) : 8;
const y = 10 + rows.get(b.label)*rowH;
const el = document.createElement('div');
el.className = 'bar ' + (b.kind==='llm'?'llm':'code') +
(b.ev.event==='fact.rejected' ? ' bad':'');
el.style.left = x+'px'; el.style.top = y+'px';
el.style.width = Math.min(w, W()-x-2)+'px';
el.dataset.d = JSON.stringify(b.ev).slice(0,600);
el.title = b.label;
el.onclick = () => { $('#detail').textContent =
b.label + ' — ' + (b.ev.dur_s? b.ev.dur_s+'s · ':'') + el.dataset.d; };
box.appendChild(el);
});
// row labels
for (const [label, i] of rows) {
const s = document.createElement('div');
s.textContent = label;
s.style.cssText = `position:absolute;left:4px;top:${10+i*rowH}px;color:var(--dim);font-size:11px;width:112px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`;
box.appendChild(s);
}
})();
// ---------- facts ----------
(() => {
const box = $('#facts');
const rows = [];
for (const e of EV) {
if (e.event === 'claims.done')
rows.push(`<h3>${e.page} — ${e.heading||''} (${(e.out&&e.out.n_claims)||0} claims)</h3>` +
((e.out&&e.out.claims)||[]).map(c=>`<div>· ${esc(c)}</div>`).join(''));
if (e.event === 'type.done')
rows.push(`<div style="color:var(--dim)">type: ${esc(e.claim||'')} → ` +
(e.out&&e.out.fact ? `<span class="ok">${esc(JSON.stringify(e.out.fact))}</span>` :
'<span class="bad">null (declined)</span>') + `</div>`);
if (e.event === 'fact.merged')
rows.push(`<div class="ok">merged: ${esc(fmt_fact(e.fact))}</div>`);
if (e.event === 'fact.rejected')
rows.push(`<div class="bad">rejected (${esc(e.reason)}): ${esc(fmt_fact(e.fact))}</div>`);
}
const snap = EV.find(e => e.event === 'kg.snapshot');
if (snap) rows.push(`<h3>KG final: ${snap.kg.n_live}/${snap.kg.n_edges} live · ${snap.kg.n_conflicts} conflicts</h3>`);
const fin = EV.find(e => e.event === 'run.final');
if (fin) rows.push(`<div class="final"><b>final:</b> ${esc(fin.out||'')}</div>`);
box.innerHTML = rows.join('') || '<i>no extraction events</i>';
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;');}
function fmt_fact(f){return f ? `${f.subject} | ${f.relation} | ${f.object}` : '';}
})();
// ---------- probes ----------
(() => {
const box = $('#probes');
const rows = [];
for (const e of EV) {
if (e.event === 'probe.done')
rows.push(`<h3>probe — ${esc(e.q||'')}</h3>
<div>seeds: ${(e.seeds||[]).map(esc).join(', ')}</div>
<div>rows: <span class="ok">${e.rows}</span> · semantic adds: <span class="pill">${e.semantic}</span> · tau=${e.tau||'—'}</div>`);
if (e.event === 'prover.done')
rows.push(`<h3>prover — ${esc(e.q||'')}</h3>
<div>verdict: <b class="${e.verdict==='ambiguous'||e.verdict==='closed'?'ok':'bad'}">${e.verdict}</b>${e.reason?' ('+esc(e.reason)+')':''}</div>
<div>bindings (${e.n_bindings||0}): ${(e.bindings||[]).map(esc).join(' · ')}</div>
<div style="color:var(--dim)">dsl: ${esc(JSON.stringify(e.dsl))}</div>`);
}
box.innerHTML = rows.join('') || '<i>no probe/prover events</i>';
function esc(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;');}
})();
// ---------- kg canvas (force-ish layout: subjects orbit values) ----------
(() => {
const cv = $('#kgc'), ctx = cv.getContext('2d');
const snap = EV.find(e => e.event === 'kg.snapshot');
if (!snap) { $('#kg').innerHTML = '<i style="padding:20px;display:inline-block">no kg.snapshot in this run</i>'; return; }
const edges = (snap.kg.edges||[]).filter(e => !e.retracted);
const el = $('#kg');
let nodes = null, ns = null;
function layout(){
// node set
nodes = new Map();
const nid = (name) => { if (!nodes.has(name)) nodes.set(name, {
x: Math.random()*cv.width, y: Math.random()*cv.height,
vx:0, vy:0, name, deg:0}); return nodes.get(name); };
edges.forEach(e => { nid(e.subject).deg++; nid(e.object).deg++; });
ns = [...nodes.values()];
const K = 24, REP = 1400;
for (let it=0; it<220; it++) {
for (const n of ns) {
let fx=0, fy=0;
for (const m of ns) if (m!==n) {
let dx=n.x-m.x, dy=n.y-m.y, d2=dx*dx+dy*dy||1;
fx += REP*dx/d2; fy += REP*dy/d2;
}
n.vx=(n.vx+fx)*.85; n.vy=(n.vy+fy)*.85; n.x+=n.vx; n.y+=n.vy;
}
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
let dx=b.x-a.x, dy=b.y-a.y, d=Math.sqrt(dx*dx+dy*dy)||1;
const f=(d-K)/d*.12;
a.vx+=dx*f; a.vy+=dy*f; b.vx-=dx*f; b.vy-=dy*f;
a.x+=a.vx*.02; a.y+=a.vy*.02; b.x-=b.vx*.02; b.y-=b.vy*.02;
});
}
}
function resize0(){ if (cv.width !== el.clientWidth) cv.width = el.clientWidth;
if (cv.height !== el.clientHeight) cv.height = el.clientHeight; }
function draw(){
resize0();
if (cv.width === 0 || cv.height === 0) return; // hidden: retry on activation
if (!nodes) layout();
ctx.fillStyle = '#0b0b0b'; ctx.fillRect(0,0,cv.width,cv.height);
ctx.strokeStyle = '#3a3a3a';
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y);
ctx.strokeStyle = e.last_touch ? '#4cc2ff' : '#3a3a3a';
ctx.lineWidth = e.last_touch ? 1.6 : .8; ctx.stroke();
});
ctx.font = '10px monospace';
ns.forEach(n => {
const r = 4 + Math.min(n.deg,8);
ctx.beginPath(); ctx.arc(n.x,n.y,r,0,7);
ctx.fillStyle = '#c678dd'; ctx.fill();
ctx.fillStyle = '#999';
ctx.fillText(n.name.slice(0,18), n.x+r+2, n.y+3);
});
// edge labels near midpoints (windows)
ctx.fillStyle = '#777';
edges.forEach(e => {
const a=nodes.get(e.subject), b=nodes.get(e.object);
const lab = e.rel + (e.t_start?` [${e.t_start}${e.t_end?('–'+e.t_end):'–'}]`:'');
ctx.fillText(lab.slice(0,24), (a.x+b.x)/2+3, (a.y+b.y)/2-3);
});
}
window.addEventListener('resize', draw);
draw();
cv.onclick = (m) => {
const rect = cv.getBoundingClientRect();
const x = m.clientX-rect.left, y = m.clientY-rect.top;
for (const n of ns) if ((n.x-x)**2+(n.y-y)**2 < 400) {
$('#detail').textContent = n.name + ` (deg ${n.deg})`; return; }
for (const e of edges) {
const a=nodes.get(e.subject), b=nodes.get(e.object);
const mx=(a.x+b.x)/2, my=(a.y+b.y)/2;
if ((mx-x)**2+(my-y)**2 < 500) {
$('#detail').textContent = `${e.subject} — ${e.rel} — ${e.object}` +
(e.t_start?` [${e.t_start}..${e.t_end||'now'}]`:'') +
(e.last_touch?` · touched @${e.last_touch.ts} (${e.last_touch.page})`:' · untouched this run');
return; }
}
};
})();
</script>
</body>
</html>
"""
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+108
View File
@@ -0,0 +1,108 @@
"""floop-inspect tests (PR B: the post-mortem HTML debugger).
Law: one run dir in, ONE self-contained inspect.html out — the events
JSON inlined, zero network references (opens offline from file://),
every tab present (timeline, KG, facts, probes), and the run's final
answer visible. A run dir without events.jsonl errors honestly."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from floop.inspect_html import generate
EVENTS = [
{"seq": 1, "ts": "10:00:00.000", "run_ts": "10:00:00.000",
"event": "comp.start", "comp": "INIT", "desc": "decompose: q0"},
{"seq": 2, "ts": "10:00:01.000", "run_ts": "10:00:00.000",
"event": "llm.done", "stage": "INIT", "call_seq": 1, "dur_s": 0.9,
"file": "prompts/01-INIT.txt", "exception": None},
{"seq": 3, "ts": "10:00:01.100", "run_ts": "10:00:00.000",
"event": "comp.out", "comp": "INIT", "out": "Q1 sub"},
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
"event": "claims.done", "page": "Pedro Sanchez",
"heading": "Career", "out": {"n_claims": 1,
"claims": ["PM of Spain since 2018"]}},
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
"event": "type.done", "page": "Pedro Sanchez",
"claim": "PM of Spain since 2018",
"out": {"fact": {"subject": "Pedro Sanchez",
"relation": "prime minister of", "object": "Spain"}}},
{"seq": 6, "ts": "10:00:03.500", "run_ts": "10:00:00.000",
"event": "fact.merged", "eid": 7,
"fact": {"subject": "Pedro Sanchez", "relation": "prime minister of",
"object": "Spain"}, "page": "Pedro Sanchez"},
{"seq": 7, "ts": "10:00:04.000", "run_ts": "10:00:00.000",
"event": "probe.done", "q": "Q1 sub", "seeds": ["pedro"], "rows": 3,
"semantic": 1, "tau": 0.45},
{"seq": 8, "ts": "10:00:05.000", "run_ts": "10:00:00.000",
"event": "prover.done", "q": "Q1 sub", "verdict": "ambiguous",
"dsl": {"lookup": {"subject": "pedro sanchez",
"rel_any": ["prime minister of"], "bind": "x"}},
"n_bindings": 2, "bindings": ["Spain", "PSOE"]},
{"seq": 9, "ts": "10:00:06.000", "run_ts": "10:00:00.000",
"event": "kg.snapshot",
"kg": {"n_edges": 1, "n_live": 1, "n_conflicts": 0,
"edges": [{"eid": 7, "subject": "pedro sanchez",
"rel": "prime minister of", "object": "Spain",
"t_start": "2018", "t_end": None, "retracted": False,
"last_touch": {"seq": 6, "ts": "10:00:03.500",
"page": "Pedro Sanchez"}}]}},
{"seq": 10, "ts": "10:00:07.000", "run_ts": "10:00:00.000",
"event": "run.final", "out": "Spain and PSOE"},
]
def _make_run(tmp: Path, events) -> Path:
run_dir = tmp / "run"
run_dir.mkdir(parents=True)
(run_dir / "events.jsonl").write_text(
"\n".join(json.dumps(e) for e in events), encoding="utf-8")
return run_dir
def test_generate_writes_selfcontained_html():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = _make_run(tmp, EVENTS)
out = generate(run_dir)
assert out == run_dir / "inspect.html", out
html = out.read_text(encoding="utf-8")
# self-contained: zero network refs, JSON inlined
assert "http://" not in html and "https://" not in html, "network ref!"
assert '"PM of Spain since 2018"' in html # events inlined
for tab in ("timeline", "kg", "facts", "probes"):
assert f'id="{tab}"' in html, tab # all tabs present
assert "Spain and PSOE" in html # final answer in
assert "prime minister of" in html # KG data in
print("ok: one self-contained inspect.html (offline, all tabs, inlined)")
def test_missing_events_errors_honestly():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = tmp / "run"
run_dir.mkdir()
try:
generate(run_dir)
raise AssertionError("must fail")
except SystemExit as e:
assert e.code not in (0, None), e
print("ok: no events.jsonl -> honest error (exit != 0)")
def test_empty_events_still_renders():
import tempfile
tmp = Path(tempfile.mkdtemp())
run_dir = _make_run(tmp, [])
out = generate(run_dir)
assert out.exists()
print("ok: empty run renders an honest empty view")
if __name__ == "__main__":
test_generate_writes_selfcontained_html()
test_missing_events_errors_honestly()
test_empty_events_still_renders()
print("\ninspect_run: 3/3 ok")