Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

wip(second-brain/ux): Memory Ledger console UX

xerj-org271580e4c3f4
diff --git a/engine/crates/xerj-console-api/src/seed.rs b/engine/crates/xerj-console-api/src/seed.rs
index 0db681187..a892dd935 100644
--- a/engine/crates/xerj-console-api/src/seed.rs
+++ b/engine/crates/xerj-console-api/src/seed.rs
@@ -1,10 +1,10 @@
//! First-launch seeding of the built-in dashboards as **editable backend data**.
//!
-//! The SPA historically defined its 13 flagship dashboards in code
+//! The SPA historically defined its flagship dashboards in code
//! (`xerj-ux/src/dashboards/*.js` + `registry.js`). That made them a fixed,
//! un-editable set: a layout tweak or a rename never survived a reload, and
//! there was no server object to attach a per-panel query to. This module
-//! materialises those same 13 dashboards as rows in `.xerj_dashboards` on
+//! materialises those same 14 dashboards as rows in `.xerj_dashboards` on
//! first launch, so from that point on they are *data* the operator can edit
//! (title, layout, panel geometry, per-panel query/viz) and that persists
//! through the CRUD surface in [`crate::dashboards`].
@@ -125,7 +125,7 @@ fn pd(
}
}
-/// The 13 built-in dashboards, in registry order. Titles are the panel
+/// The 14 built-in dashboards, in registry order. Titles are the panel
/// `eyebrow` strings from the `.js` sources; dynamic eyebrows are captured as
/// a stable static string.
fn seed_specs() -> Vec<DashboardSpec> {
@@ -273,6 +273,29 @@ fn seed_specs() -> Vec<DashboardSpec> {
),
],
},
+ DashboardSpec {
+ // Second brain — the graph-memory ego ledger (contract §7.4).
+ // Live-data-only in the SPA: its panels read /_graph/{brain}/*
+ // and never bind mock data, so the seeded skeleton is pure
+ // structure. NOTE (module-doc contract): adding this id needs
+ // NO `SEED_REVISION` bump — absent ids are created on every
+ // boot; the revision only migrates *changed* skeletons.
+ registry_id: "second-brain",
+ name: "Second Brain",
+ section: Some("dashboards"),
+ group: Some("ai"),
+ panels: vec![
+ p("edgesLive", "metric", "LIVE EDGES", 3),
+ p("edgesTotal", "metric", "TOTAL ASSERTED", 3),
+ p("invalidated", "metric", "INVALIDATED (KEPT)", 3),
+ p("detectors", "metric", "DETECTORS", 3),
+ p("typeDist", "dist", "EDGE TYPES", 6),
+ p("edgeTimeline", "series", "EDGES OVER TIME", 6),
+ p("ego", "ego", "EGO · 1 HOP FROM SELECTED NODE", 12),
+ p("hubs", "topn", "HUBS · IN / OUT", 6),
+ p("notShown", "honesty", "WHAT THIS VIEW DID NOT SHOW", 6),
+ ],
+ },
// ── Logs group ──────────────────────────────────────────────────────
DashboardSpec {
registry_id: "logs-overview",
@@ -572,8 +595,13 @@ fn height_for(kind: &str) -> u32 {
"citations" => 3,
"heatmap" | "ribbon3d" | "embedspace" | "chord" | "pcoords" | "attention" | "flowband"
| "multiples" | "treemap" | "scatter" | "stacked" | "anomalyband" => 6,
- // line, topn, table, events, dist, bar, histogram, markdown, and the
- // section-specific view types (hits, facet, plan, clusters, …).
+ // The second-brain ego ledger stacks three columns of edges plus a
+ // full-width belief-time scrubber — it is the tallest single panel
+ // we seed.
+ "ego" => 8,
+ // line, series, topn, table, events, dist, bar, histogram, honesty,
+ // markdown, and the section-specific view types (hits, facet, plan,
+ // clusters, …).
_ => 4,
}
}
@@ -741,12 +769,12 @@ mod tests {
use super::*;
#[test]
- fn seeds_the_thirteen_dashboards() {
+ fn seeds_the_fourteen_dashboards() {
let specs = seed_specs();
assert_eq!(
specs.len(),
- 13,
- "must seed exactly the 13 registry dashboards"
+ 14,
+ "must seed exactly the 14 registry dashboards"
);
// Deterministic ids, all `default-` prefixed and unique.
let mut ids: Vec<String> = specs
@@ -759,6 +787,7 @@ mod tests {
assert_eq!(ids.len(), n, "seed ids must be unique");
assert!(ids.iter().all(|id| id.starts_with("default-")));
assert!(ids.contains(&"default-ai-overview".to_string()));
+ assert!(ids.contains(&"default-second-brain".to_string()));
assert!(ids.contains(&"default-settings".to_string()));
}
@@ -773,6 +802,10 @@ mod tests {
by("ai-overview"),
(Some("dashboards".into()), Some("ai".into()))
);
+ assert_eq!(
+ by("second-brain"),
+ (Some("dashboards".into()), Some("ai".into()))
+ );
assert_eq!(
by("logs-overview"),
(Some("dashboards".into()), Some("logs".into()))
diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.css
index 20891de2d..e68dd4da0 100644
--- a/xerj-ux/assets/base.css
+++ b/xerj-ux/assets/base.css
@@ -1697,3 +1697,232 @@ html.mobile-preview .nav-sub {
padding: 4px 0 8px;
letter-spacing: 0.02em;
}
+
+/* ---- Second Brain · ego ledger ---------------------------- */
+/* All color through tokens; the only accent uses are the as-of
+ caret, the EXPIRED tag, evidence rules, and hover/focus — one
+ accent colour, correct in both themes by construction. */
+
+.sb-controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--sp-1) var(--sp-4);
+ align-items: baseline;
+ font-size: var(--fs-13);
+ padding-bottom: var(--sp-2);
+ border-bottom: 1px solid var(--z-faint);
+ margin-bottom: var(--sp-3);
+}
+.sb-cval { color: var(--z-ink); font-weight: 700; }
+.sb-clink { font-family: var(--font-data); color: var(--z-mute); cursor: pointer; }
+.sb-clink:hover { color: var(--z-accent); }
+.sb-cerr { color: var(--z-accent); font-size: var(--fs-11); letter-spacing: 0.04em; }
+
+.sb-ledger {
+ display: grid;
+ grid-template-columns: minmax(200px, 1fr) 48px minmax(260px, 1.15fr) 48px minmax(200px, 1fr);
+ column-gap: 0;
+ align-items: start;
+ margin-bottom: var(--sp-4);
+}
+.sb-col { min-width: 0; }
+.sb-rail {
+ position: relative;
+ align-self: stretch;
+ min-height: 40px;
+ color: var(--z-mute); /* the 1px focus→group traces inherit this */
+}
+.sb-trace { position: absolute; inset: 0; display: block; shape-rendering: crispEdges; }
+
+.sb-focuscard {
+ border: 1px solid var(--z-faint);
+ padding: var(--sp-3);
+ min-width: 0;
+}
+.sb-ftitle {
+ font-family: var(--font-display);
+ font-weight: 800;
+ font-size: var(--fs-32);
+ line-height: 1;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ margin-top: 6px;
+ overflow-wrap: anywhere;
+}
+.sb-ftext {
+ font-family: var(--font-prose);
+ font-size: var(--fs-13);
+ line-height: 1.6;
+ color: var(--z-mute);
+ margin-top: var(--sp-1);
+}
+.sb-fdeg {
+ display: flex;
+ gap: var(--sp-3);
+ margin-top: var(--sp-2);
+ font-size: var(--fs-13);
+ color: var(--z-mute);
+}
+.sb-fnum { color: var(--z-ink); font-weight: 700; }
+.sb-fprov { margin-top: var(--sp-1); font-size: var(--fs-11); overflow-wrap: anywhere; }
+
+.sb-group { margin-bottom: var(--sp-3); }
+.sb-grouphead {
+ display: flex;
+ justify-content: space-between;
+ align-items: baseline;
+ gap: var(--sp-2);
+ border-top: 1px solid var(--z-mute); /* the 1px rule the traces land on */
+ padding-top: 6px;
+ margin-bottom: 4px;
+}
+.sb-ghtype {
+ font-weight: 600;
+ font-size: var(--fs-11);
+ letter-spacing: var(--track-label);
+ text-transform: uppercase;
+ color: var(--z-ink);
+}
+.sb-ghcount { font-family: var(--font-data); font-size: var(--fs-11); color: var(--z-mute); white-space: nowrap; }
+
+.sb-erow { border-bottom: 1px solid var(--z-faint); }
+.sb-erow-main { display: flex; gap: var(--sp-2); align-items: baseline; padding: 6px 0; }
+.sb-ename {
+ flex: 1 1 auto;
+ min-width: 0;
+ text-align: left;
+ font-family: var(--font-data);
+ font-size: var(--fs-13);
+ color: var(--z-ink);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ cursor: pointer;
+}
+.sb-ename:hover, .sb-ename:focus-visible { color: var(--z-accent); }
+.sb-emeta {
+ display: flex;
+ gap: var(--sp-1);
+ align-items: baseline;
+ font-family: var(--font-data);
+ font-size: var(--fs-11);
+ color: var(--z-mute);
+ white-space: nowrap;
+ cursor: pointer;
+}
+.sb-emeta:hover .sb-eev, .sb-emeta:focus-visible .sb-eev { color: var(--z-accent); }
+.sb-ehop2 { color: var(--z-ink); }
+.sb-extag { display: none; color: var(--z-accent); letter-spacing: var(--track-label); font-size: var(--fs-11); }
+.sb-erow.sb-expired .sb-extag { display: inline; }
+.sb-erow.sb-expired .sb-ename,
+.sb-erow.sb-expired .sb-ewin { text-decoration: line-through; color: var(--z-mute); }
+.sb-erow.sb-off { display: none; }
+.sb-sidenote { font-size: var(--fs-11); letter-spacing: 0.06em; padding: var(--sp-2) 0; }
+
+.sb-evbody { padding: 2px 0 10px; }
+.sb-evquote {
+ font-family: var(--font-prose);
+ font-size: var(--fs-13);
+ line-height: 1.6;
+ color: var(--z-ink);
+ border-left: 1px solid var(--z-accent);
+ padding-left: var(--sp-2);
+ margin: 4px 0 8px;
+}
+.sb-evquote.sb-evnone { color: var(--z-mute); border-left-color: var(--z-faint); }
+.sb-evmeta { display: flex; flex-direction: column; gap: 2px; font-size: var(--fs-11); overflow-wrap: anywhere; }
+
+/* Belief-time scrubber */
+.sb-scrub { margin-top: var(--sp-4); }
+.sb-strip {
+ position: relative;
+ margin-top: 28px; /* air for the floating caret label */
+ border-top: 1px solid var(--z-faint);
+ border-bottom: 1px solid var(--z-faint);
+ cursor: crosshair;
+ touch-action: none;
+}
+.sb-striplines { width: 100%; color: var(--z-ink); }
+.sb-lseg.sb-l-live { stroke-opacity: 1; }
+.sb-lseg.sb-l-expired { stroke-opacity: 0.45; }
+.sb-lseg.sb-l-future { stroke-opacity: 0.15; }
+.sb-ltick { stroke-opacity: 0.7; }
+.sb-caret {
+ position: absolute;
+ top: -6px;
+ bottom: -6px;
+ width: 13px; /* wide hit target for a 1px line */
+ margin-left: -7px;
+ cursor: ew-resize;
+ touch-action: none;
+}
+.sb-caret::after {
+ content: '';
+ position: absolute;
+ left: 6px;
+ top: 0;
+ bottom: 0;
+ width: 1px;
+ background: var(--z-accent);
+}
+.sb-caret:focus-visible { outline: 1px solid var(--z-accent); outline-offset: 2px; }
+.sb-caret-label {
+ position: absolute;
+ top: -24px;
+ transform: translateX(-50%);
+ color: var(--z-accent);
+ font-size: var(--fs-11);
+ letter-spacing: 0.06em;
+ white-space: nowrap;
+ pointer-events: none;
+}
+.sb-scrub-legend {
+ display: flex;
+ justify-content: space-between;
+ gap: var(--sp-2);
+ margin-top: var(--sp-1);
+ font-size: var(--fs-11);
+ letter-spacing: 0.06em;
+}
+.sb-scrub-legend .mid { flex: 1; text-align: center; }
+.sb-busy { opacity: 0.55; transition: opacity 0.15s; }
+
+/* Honesty panel — always rendered, zeros included */
+.sb-honesty { font-size: var(--fs-13); }
+.sb-honesty .sb-hgroup { margin: var(--sp-2) 0 6px; }
+.sb-honesty .sb-hgroup:first-child { margin-top: 0; }
+.sb-hrow {
+ display: flex;
+ justify-content: space-between;
+ gap: var(--sp-2);
+ padding: 3px 0;
+ border-bottom: 1px solid var(--z-faint);
+}
+.sb-hk { color: var(--z-mute); }
+.sb-hv { font-weight: 700; }
+.sb-hids { padding: 4px 0; font-size: var(--fs-11); }
+
+/* Hubs */
+.sb-hubs { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
+.sb-hubs .key { margin-bottom: 8px; }
+.sb-hub-active .row__label { color: var(--z-accent); }
+
+/* Empty / live-only states */
+.sb-empty { padding: var(--sp-2) 0 var(--sp-4); max-width: 760px; }
+.sb-empty .sb-ftext { margin: var(--sp-2) 0; }
+.sb-cmd {
+ font-size: var(--fs-13);
+ color: var(--z-ink);
+ border-left: 1px solid var(--z-accent);
+ padding: var(--sp-1) var(--sp-2);
+ margin: var(--sp-2) 0;
+ overflow-x: auto;
+ white-space: pre;
+}
+
+/* Narrow screens: stack — focus card first, then in, then out. */
+@media (max-width: 1100px) {
+ .sb-ledger { grid-template-columns: 1fr; row-gap: var(--sp-3); }
+ .sb-rail { display: none; }
+ .sb-focuscard { order: -1; }
+}
diff --git a/xerj-ux/src/dashboards/registry.js b/xerj-ux/src/dashboards/registry.js
index 133697fa0..9defad6ae 100644
--- a/xerj-ux/src/dashboards/registry.js
+++ b/xerj-ux/src/dashboards/registry.js
@@ -16,6 +16,7 @@ import { aiOverview } from './ai-overview.js';
import { ragQuality } from './rag-quality.js';
import { vectorIndex } from './vector-index.js';
import { agentMemory } from './agent-memory.js';
+import { secondBrain } from './second-brain.js';
import { anomalyDetect } from './anomaly-detect.js';
import { ingestPipeline } from './ingest-pipeline.js';
import { logsOverview } from './logs-overview.js';
@@ -38,12 +39,13 @@ const DEFAULT_GROUP = {
'rag-quality': 'ai',
'vector-index': 'ai',
'agent-memory': 'ai',
+ 'second-brain': 'ai',
'logs-overview': 'logs',
'anomaly-detect': 'logs',
'ingest-pipeline':'logs',
'system': 'infra',
};
-for (const d of [aiOverview, ragQuality, vectorIndex, agentMemory, anomalyDetect, ingestPipeline, logsOverview, system]) {
+for (const d of [aiOverview, ragQuality, vectorIndex, agentMemory, secondBrain, anomalyDetect, ingestPipeline, logsOverview, system]) {
d.section = 'dashboards';
d.group = DEFAULT_GROUP[d.id] || 'other';
}
@@ -53,10 +55,10 @@ searchDiscover.section = 'discover';
const all = [
// Dashboards section, ordered by group so the first member of each
// group is the one the group tab lands on when clicked.
- // AI: ai-overview, rag-quality, vector-index, agent-memory
+ // AI: ai-overview, rag-quality, vector-index, agent-memory, second-brain
// Logs: logs-overview, anomaly-detect, ingest-pipeline
// Infra: system
- aiOverview, ragQuality, vectorIndex, agentMemory,
+ aiOverview, ragQuality, vectorIndex, agentMemory, secondBrain,
logsOverview, anomalyDetect, ingestPipeline,
system,
// Top-level sections (one view each)
diff --git a/xerj-ux/src/dashboards/second-brain.js b/xerj-ux/src/dashboards/second-brain.js
new file mode 100644
index 000000000..5f53f431e
--- /dev/null
+++ b/xerj-ux/src/dashboards/second-brain.js
@@ -0,0 +1,61 @@
+// ============================================================
+// Dashboard — SECOND BRAIN
+//
+// The relationship layer over documents that already exist: edges are
+// ordinary XERJ documents, bi-temporal and soft-delete-only, asserted
+// by deterministic detectors (or by hand) with the exact source quote
+// as evidence. This dashboard is an EGO LEDGER — inbound edges left,
+// the focus memory centre, outbound edges right — with a belief-time
+// scrubber to replay what the brain believed at any moment. A global
+// force-directed graph was rejected by design (non-deterministic
+// layout, collapses past ~200 nodes); see ux/ego-ledger.js.
+//
+// LIVE DATA ONLY. data/backends/xerj.js routes this dashboard to
+// data/second-brain-api.js, which reads /_graph/{brain}/overview and
+// /_graph/{brain}/ego and NEVER falls back to mock — an empty or
+// unreachable brain renders an honest state that says how to fill it
+// (`xerj autoindex <folder>`), not invented beliefs.
+// ============================================================
+
+import { renderPanelBody } from '../ux/ego-ledger.js';
+import { sbAfterRender } from '../data/second-brain-api.js';
+
+/** One panel body: renderPanelBody draws the inner HTML; the
+ * `data-sb-body` wrapper is the in-place re-render target the
+ * interaction controller patches after refocus / as-of commits. */
+const body = (id, data) => `<div data-sb-body="${id}">${renderPanelBody(id, data)}</div>`;
+
+export const secondBrain = {
+ id: 'second-brain',
+ name: 'Second Brain',
+ render: ({ data, time }) => {
+ // Traces (the 1px focus→group lines) need real layout; schedule a
+ // post-paint measure+draw pass. No-op outside a browser.
+ sbAfterRender();
+ return {
+ title: 'SECOND BRAIN',
+ kicker: 'GRAPH MEMORY · EVIDENCE · TIME TRAVEL',
+ meta: [time, 'XERJ-GRAPH'],
+ panels: [
+ { id: 'edgesLive', eyebrow: 'LIVE EDGES', cols: 3, type: 'metric',
+ render: () => body('edgesLive', data) },
+ { id: 'edgesTotal', eyebrow: 'TOTAL ASSERTED', cols: 3, type: 'metric',
+ render: () => body('edgesTotal', data) },
+ { id: 'invalidated', eyebrow: 'INVALIDATED (KEPT)', cols: 3, type: 'metric',
+ render: () => body('invalidated', data) },
+ { id: 'detectors', eyebrow: 'DETECTORS', cols: 3, type: 'metric',
+ render: () => body('detectors', data) },
+ { id: 'typeDist', eyebrow: 'EDGE TYPES', cols: 6, type: 'dist',
+ render: () => body('typeDist', data) },
+ { id: 'edgeTimeline', eyebrow: 'EDGES OVER TIME', cols: 6, type: 'series',
+ render: () => body('edgeTimeline', data) },
+ { id: 'ego', eyebrow: 'EGO · 1 HOP FROM SELECTED NODE', cols: 12, type: 'ego',
+ render: () => body('ego', data) },
+ { id: 'hubs', eyebrow: 'HUBS · IN / OUT', cols: 6, type: 'topn',
+ render: () => body('hubs', data) },
+ { id: 'notShown', eyebrow: 'WHAT THIS VIEW DID NOT SHOW', cols: 6, type: 'honesty',
+ render: () => body('notShown', data) },
+ ],
+ };
+ },
+};
diff --git a/xerj-ux/src/data/backends/xerj.js b/xerj-ux/src/data/backends/xerj.js
index 74849a82a..98ec29c60 100644
--- a/xerj-ux/src/data/backends/xerj.js
+++ b/xerj-ux/src/data/backends/xerj.js
@@ -9,6 +9,8 @@
// `probe()` is intentionally GET / so it costs ~0 on the engine.
// ============================================================
+import { liveSecondBrain } from '../second-brain-api.js';
+
// Aggregation materialisation bypass.
//
// Xerj v1.0.0-rc.1 has a known bug at
@@ -95,6 +97,11 @@ export async function search(baseUrl, dashId, ctx, signal) {
case 'rag-quality': return liveRagQuality(baseUrl, ctx, signal);
case 'vector-index': return liveVectorIndex(baseUrl, ctx, signal);
case 'agent-memory': return liveAgentMemory(baseUrl, ctx, signal);
+ // Second brain NEVER returns null: its adapter shapes every failure
+ // (engine down, no brains, 404 brain) into an honest state object,
+ // so the mock fallback in data/query.js can never fire for it —
+ // a fabricated brain would be worse than an empty one.
+ case 'second-brain': return liveSecondBrain(baseUrl, ctx, signal);
case 'anomaly-detect': return liveAnomalyDetect(baseUrl, ctx, signal);
case 'ingest-pipeline': return liveIngestPipeline(baseUrl, ctx, signal);
default: return null; // signals "fall back to mock"
diff --git a/xerj-ux/src/data/second-brain-api.js b/xerj-ux/src/data/second-brain-api.js
new file mode 100644
index 000000000..2c9da0d43
--- /dev/null
+++ b/xerj-ux/src/data/second-brain-api.js
@@ -0,0 +1,546 @@
+// ============================================================
+// Xerj Console — SECOND BRAIN data layer + interaction controller
+//
+// This dashboard reads the LIVE graph endpoints ONLY:
+//
+// GET /_cat/indices/.xerj-memory-*-edges → discover brains
+// GET /_graph/{brain}/overview → §4.4 of the contract
+// GET /_graph/{brain}/ego → §4.3 of the contract
+//
+// There is deliberately NO mock fallback: a fake brain would defeat
+// the product ("what does my agent believe?" answered with invented
+// beliefs). Every failure path returns a SHAPED object — never null —
+// so data/query.js can never silently substitute mock data; the
+// dashboard renders an honest unreachable / empty state instead.
+//
+// The second half of this file is the interaction controller. The app
+// shell re-renders pages as whole HTML strings, so ledger interactions
+// (refocus, belief-time scrub, evidence reveal) are handled here with
+// document-level delegated listeners + in-place re-render of only the
+// second-brain panel bodies (`[data-sb-body]`), each drawn by
+// ux/ego-ledger.js#renderPanelBody. Scrub previews are client-side
+// over already-fetched edges; RELEASING the caret re-queries the
+// server with `as_of` — the server owns the bi-temporal cut.
+// ============================================================
+
+import {
+ renderPanelBody, drawLedgerTraces, edgeStateAt, fmtTs,
+} from '../ux/ego-ledger.js';
+
+/** Panel ids of the second-brain dashboard, in render order. The
+ * controller patches exactly these after an interaction. */
+export const SB_PANEL_IDS = [
+ 'edgesLive', 'edgesTotal', 'invalidated', 'detectors',
+ 'typeDist', 'edgeTimeline', 'ego', 'hubs', 'notShown',
+];
+
+/** Returned edge budget for the belief query. Hops=2 so neighbour rows
+ * can carry their onward-degree count; 1000 is the ego endpoint's
+ * clamp ceiling. Clips are surfaced by the honesty panel + '≥' counts. */
+const EGO_LIMIT = 1000;
+
+const K = {
+ brain: 'xerj.sb.brain',
+ perBrain: (b) => `xerj.sb.state.${b}`,
+};
+
+// ----- module state -------------------------------------------------
+//
+// A singleton, on purpose: the console is a single-page app and the
+// ledger must survive the shell's whole-page re-renders (theme flips,
+// time-range clicks) without losing focus/as-of. Persisted so a reload
+// reopens the same view.
+
+const S = {
+ baseUrl: '',
+ connected: false,
+ error: null, // transport-level error (engine unreachable)
+ uiError: null, // last interaction-level error (shown inline, non-fatal)
+ brains: [],
+ brain: null,
+ focus: null,
+ asOf: null, // epoch-ms | null = NOW
+ trail: [],
+ overview: null, // §4.4 body (or exists:false body)
+ ego: null, // §4.3 body — the belief at the caret
+ timeline: null, // §4.3 body — hop-1, include_expired, pinned at NOW
+};
+
+function loadBrainState() {
+ try {
+ const raw = sessionStorage.getItem(K.perBrain(S.brain));
+ const st = raw ? JSON.parse(raw) : {};
+ S.focus = st.focus || null;
+ S.asOf = Number.isFinite(st.asOf) ? st.asOf : null;
+ S.trail = Array.isArray(st.trail) ? st.trail : [];
+ } catch {
+ S.focus = null; S.asOf = null; S.trail = [];
+ }
+}
+
+function saveBrainState() {
+ try {
+ if (!S.brain) return;
+ sessionStorage.setItem(
+ K.perBrain(S.brain),
+ JSON.stringify({ focus: S.focus, asOf: S.asOf, trail: S.trail.slice(-8) }),
+ );
+ } catch { /* storage full/blocked — view still works, just not sticky */ }
+}
+
+// ----- HTTP ---------------------------------------------------------
+
+async function getJson(url, signal) {
+ const r = await fetch(url, { signal, headers: { accept: 'application/json' } });
+ const text = await r.text();
+ let body = null;
+ try { body = text ? JSON.parse(text) : null; } catch { /* non-JSON error page */ }
+ if (!r.ok) {
+ // The graph API 404s an unknown brain WITH a shaped body
+ // (`exists: false`) — that is a valid answer, not an error.
+ if (body && body.exists === false) return body;
+ const reason = body && body.error && body.error.reason
+ ? body.error.reason
+ : `HTTP ${r.status}`;
+ throw new Error(reason);
+ }
+ return body;
+}
+
+/**
+ * Brains = the reserved `.xerj-memory-{brain}-edges` indices. `_cat`
+ * on this engine emits plain text (no format=json), so parse lines;
+ * tolerate a JSON array in case a later build adds it. A wildcard
+ * matching nothing is an empty 200 — an engine with no brains is a
+ * normal state, not an error.
+ */
+async function discoverBrains(baseUrl, signal) {
+ const r = await fetch(`${baseUrl}/_cat/indices/.xerj-memory-*-edges`, { signal });
+ if (r.status === 404) return [];
+ if (!r.ok) throw new Error(`_cat/indices HTTP ${r.status}`);
+ const text = await r.text();
+ let names = [];
+ const trimmed = text.trim();
+ if (trimmed.startsWith('[')) {
+ try { names = JSON.parse(trimmed).map((i) => i.index).filter(Boolean); } catch { names = []; }
+ } else if (trimmed) {
+ // cat line: `health status NAME uuid pri rep docs deleted size size`
+ names = trimmed.split('\n')
+ .map((l) => l.trim().split(/\s+/)[2])
+ .filter(Boolean);
+ }
+ return names
+ .filter((n) => n.startsWith('.xerj-memory-') && n.endsWith('-edges'))
+ .map((n) => n.slice('.xerj-memory-'.length, -'-edges'.length))
+ .filter((b) => b.length > 0)
+ .sort();
+}
+
+const enc = encodeURIComponent;
+
+function fetchOverview(signal) {
+ const qs = new URLSearchParams({ top: '10', histogram_interval: 'day' });
+ if (S.asOf != null) qs.set('as_of', String(S.asOf));
+ return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/overview?${qs}`, signal);
+}
+
+/**
+ * The belief at the caret. `include_expired=true` so an invalidated
+ * fact comes back struck-through + EXPIRED instead of silently gone;
+ * hops=2 feeds the neighbour onward-counts; include_nodes hydrates
+ * titles/previews for the focus card and rows.
+ */
+function fetchBelief(signal) {
+ const qs = new URLSearchParams({
+ node: S.focus, hops: '2', direction: 'both',
+ limit: String(EGO_LIMIT),
+ include_expired: 'true', include_nodes: 'true', include_evidence: 'true',
+ });
+ if (S.asOf != null) qs.set('as_of', String(S.asOf));
+ return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/ego?${qs}`, signal);
+}
+
+/**
+ * The scrubber's interval set: hop-1, include_expired, pinned at NOW.
+ * Pinned so scrubbing left never removes rows from the strip — only
+ * their visibility state changes. Refetched on focus change only.
+ */
+function fetchTimeline(signal) {
+ const qs = new URLSearchParams({
+ node: S.focus, hops: '1', direction: 'both',
+ limit: String(EGO_LIMIT),
+ include_expired: 'true', include_evidence: 'false',
+ });
+ return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/ego?${qs}`, signal);
+}
+
+// ----- data assembly (§7.3 shape, extras under `sb`) ---------------
+
+function assemble() {
+ const o = S.overview && S.overview.exists !== false ? S.overview : null;
+ const ed = (o && o.edges) || { total: 0, live: 0, invalidated: 0 };
+ const num = (v) => new Intl.NumberFormat('en').format(v || 0);
+ const detectors = (o && o.detectors) || [];
+ const detTail = o && o.not_shown && o.not_shown.detectors_not_listed > 0 ? '+' : '';
+ return {
+ brain: S.brain,
+ overview: S.overview,
+ ego: S.ego,
+ metrics: {
+ edgesLive: { formatted: num(ed.live), hint: 'visible at as-of' },
+ edgesTotal: { formatted: num(ed.total), hint: 'incl. invalidated' },
+ invalidated: { formatted: num(ed.invalidated), hint: 'soft-deleted, kept for time travel' },
+ detectors: { formatted: num(detectors.length) + detTail, hint: 'deterministic, versioned' },
+ },
+ series: {
+ created: ((o && o.created_over_time) || []).map((b) => b.count),
+ createdT: ((o && o.created_over_time) || []).map((b) => b.t),
+ },
+ sb: {
+ connected: S.connected,
+ error: S.error,
+ uiError: S.uiError,
+ brains: S.brains.slice(),
+ focus: S.focus,
+ asOf: S.asOf,
+ trail: S.trail.slice(),
+ timeline: S.timeline,
+ },
+ };
+}
+
+/** Default focus: the strongest hub. Deterministic (out over in, then
+ * the agg's own count-desc order). */
+function defaultFocus() {
+ const o = S.overview;
+ if (!o || o.exists === false || !o.hubs) return null;
+ const out = o.hubs.out && o.hubs.out[0];
+ const inn = o.hubs.in && o.hubs.in[0];
+ return (out && out.id) || (inn && inn.id) || null;
+}
+
+// ----- backend adapter entry (data/backends/xerj.js dispatches here) —
+
+export async function liveSecondBrain(baseUrl, _ctx, signal) {
+ S.baseUrl = (baseUrl || '').replace(/\/+$/, '');
+ S.uiError = null;
+ try {
+ S.brains = await discoverBrains(S.baseUrl, signal);
+ S.connected = true;
+ S.error = null;
+ } catch (e) {
+ S.connected = false;
+ S.error = String((e && e.message) || e);
+ S.brains = []; S.brain = null; S.overview = null; S.ego = null; S.timeline = null;
+ const data = assemble();
+ // Surface transport failure on the nav status pill too (query.js
+ // flags `data.error` as live-error — visibly NOT "live · ok").
+ data.error = `graph API unreachable: ${S.error}`;
+ return data;
+ }
+
+ let persisted = null;
+ try { persisted = localStorage.getItem(K.brain); } catch { /* private mode */ }
+ S.brain = persisted && S.brains.includes(persisted) ? persisted : (S.brains[0] || null);
+ if (!S.brain) {
+ S.overview = null; S.ego = null; S.timeline = null;
+ return assemble();
+ }
+ loadBrainState();
+
+ try {
+ S.overview = await fetchOverview(signal);
+ } catch (e) {
+ S.overview = null; S.ego = null; S.timeline = null;
+ const data = assemble();
+ data.error = `overview failed: ${String((e && e.message) || e)}`;
+ return data;
+ }
+
+ const hasEdges = S.overview && S.overview.exists !== false
+ && S.overview.edges && S.overview.edges.total > 0;
+ if (!hasEdges) {
+ S.ego = null; S.timeline = null;
+ return assemble();
+ }
+
+ if (!S.focus) S.focus = defaultFocus();
+ if (S.focus) {
+ try {
+ const [belief, timeline] = await Promise.all([
+ fetchBelief(signal), fetchTimeline(signal),
+ ]);
+ S.ego = belief;
+ S.timeline = timeline;
+ } catch (e) {
+ S.ego = null; S.timeline = null;
+ S.uiError = String((e && e.message) || e);
+ }
+ } else {
+ S.ego = null; S.timeline = null;
+ }
+ saveBrainState();
+ return assemble();
+}
+
+// ====================================================================
+// Interaction controller
+// ====================================================================
+
+let inflight = null; // AbortController of the interaction in flight
+
+function abortInflight() {
+ if (inflight) { inflight.abort(); inflight = null; }
+}
+
+/** Re-render every second-brain panel body currently in the DOM from
+ * module state, then redraw the traces post-paint. */
+function patchPanels() {
+ if (typeof document === 'undefined') return;
+ const data = assemble();
+ for (const id of SB_PANEL_IDS) {
+ const el = document.querySelector(`[data-sb-body="${id}"]`);
+ if (el) el.innerHTML = renderPanelBody(id, data);
+ }
+ showUiError();
+ scheduleTraces();
+}
+
+function showUiError() {
+ const slot = document.querySelector('[data-sb-error]');
+ if (!slot) return;
+ slot.textContent = S.uiError ? `QUERY FAILED · ${String(S.uiError).slice(0, 90)}` : '';
+}
+
+function setBusy(on) {
+ const el = document.querySelector('[data-sb-body="ego"]');
+ if (el) el.classList.toggle('sb-busy', !!on);
+}
+
+let traceRaf = 0;
+function scheduleTraces() {
+ if (typeof requestAnimationFrame === 'undefined') return;
+ if (traceRaf) cancelAnimationFrame(traceRaf);
+ traceRaf = requestAnimationFrame(() => {
+ traceRaf = 0;
+ drawLedgerTraces(document);
+ });
+}
+
+/**
+ * Post-render hook. The dashboard's render() calls this every time the
+ * shell rebuilds the page so the trace overlay (which needs real
+ * layout) is drawn after paint. Safe under Node (no-op) — the render
+ * functions themselves stay pure.
+ */
+export function sbAfterRender() {
+ scheduleTraces();
+}
+
+// ----- interaction ops ----------------------------------------------
+
+async function refetch({ overview = false, belief = false, timeline = false }) {
+ abortInflight();
+ inflight = typeof AbortController !== 'undefined' ? new AbortController() : null;
+ const signal = inflight && inflight.signal;
+ setBusy(true);
+ S.uiError = null;
+ try {
+ const jobs = [];
+ if (overview) jobs.push(fetchOverview(signal).then((r) => { S.overview = r; }));
+ if (belief && S.focus) jobs.push(fetchBelief(signal).then((r) => { S.ego = r; }));
+ if (timeline && S.focus) jobs.push(fetchTimeline(signal).then((r) => { S.timeline = r; }));
+ await Promise.all(jobs);
+ } catch (e) {
+ if (!(e && e.name === 'AbortError')) {
+ S.uiError = String((e && e.message) || e);
+ }
+ } finally {
+ setBusy(false);
+ }
+ saveBrainState();
+ patchPanels();
+}
+
+function refocus(id) {
+ if (!id || id === S.focus) return;
+ if (S.focus) {
+ S.trail = S.trail.filter((t) => t !== S.focus);
+ S.trail.push(S.focus);
+ S.trail = S.trail.slice(-8);
+ }
+ S.focus = id;
+ S.ego = null; S.timeline = null;
+ patchPanels(); // immediate: focus card swaps to the new node id
+ refetch({ belief: true, timeline: true });
+}
+
+function switchBrain(name) {
+ if (!name || name === S.brain) return;
+ try { localStorage.setItem(K.brain, name); } catch { /* private mode */ }
+ S.brain = name;
+ S.overview = null; S.ego = null; S.timeline = null;
+ loadBrainState();
+ patchPanels();
+ (async () => {
+ await refetch({ overview: true });
+ if (!S.focus) S.focus = defaultFocus();
+ if (S.focus) await refetch({ belief: true, timeline: true });
+ })();
+}
+
+/** Commit an as-of. `null` = NOW. Overview + belief re-query (both are
+ * as-of-dependent); the timeline stays pinned at NOW by design. */
+function commitAsOf(ms) {
+ S.asOf = ms;
+ refetch({ overview: true, belief: true });
+}
+
+// ----- belief-time scrub (preview client-side, commit server-side) ---
+
+function stripDomain(scrub) {
+ const d0 = Number(scrub.getAttribute('data-d0'));
+ const d1 = Number(scrub.getAttribute('data-d1'));
+ return Number.isFinite(d0) && Number.isFinite(d1) && d1 > d0 ? [d0, d1] : null;
+}
+
+function msFromClientX(strip, dom, clientX) {
+ const rect = strip.getBoundingClientRect();
+ const frac = Math.max(0, Math.min(1, (clientX - rect.left) / Math.max(1, rect.width)));
+ return Math.round(dom[0] + frac * (dom[1] - dom[0]));
+}
+
+/** ≥99% of the way to the right edge counts as NOW (as_of unset). */
+function normalizeAsOf(ms, dom) {
+ return (dom[1] - ms) / (dom[1] - dom[0]) < 0.01 ? null : ms;
+}
+
+/** Move the caret + relabel + restate every strip line and ledger row
+ * for a candidate as-of. Pure DOM, no queries — this is the mid-drag
+ * preview over edges the server already returned. */
+function previewAsOf(scrub, ms) {
+ const dom = stripDomain(scrub);
+ if (!dom) return;
+ const pct = ((ms - dom[0]) / (dom[1] - dom[0])) * 100;
+ const caret = scrub.querySelector('[data-sb-caret]');
+ const label = scrub.querySelector('[data-sb-caret-label]');
+ const atNow = normalizeAsOf(ms, dom) == null;
+ if (caret) caret.style.left = `${pct}%`;
+ if (label) {
+ label.style.left = `${pct}%`;
+ label.textContent = atNow ? 'NOW' : fmtTs(ms);
+ }
+ const t = atNow ? null : ms;
+ for (const seg of scrub.querySelectorAll('.sb-lseg')) {
+ const e = { valid_at: Number(seg.getAttribute('data-va')), invalid_at: seg.hasAttribute('data-vi') ? Number(seg.getAttribute('data-vi')) : null };
+ const state = edgeStateAt(e, t);
+ seg.classList.remove('sb-l-live', 'sb-l-future', 'sb-l-expired');
+ seg.classList.add(`sb-l-${state}`);
+ }
+ for (const row of document.querySelectorAll('[data-sb-edge][data-va]')) {
+ const e = { valid_at: Number(row.getAttribute('data-va')), invalid_at: row.hasAttribute('data-vi') ? Number(row.getAttribute('data-vi')) : null };
+ const state = edgeStateAt(e, t);
+ row.classList.toggle('sb-off', state === 'future');
+ row.classList.toggle('sb-expired', state === 'expired');
+ }
+}
+
+// ----- event wiring (once per page load) ----------------------------
+
+let wired = false;
+let drag = null; // { scrub, dom, ms }
+
+function onPointerDown(e) {
+ const caret = e.target.closest && e.target.closest('[data-sb-caret]');
+ if (!caret) return;
+ const scrub = caret.closest('[data-sb-scrub]');
+ const dom = scrub && stripDomain(scrub);
+ if (!dom) return;
+ e.preventDefault();
+ drag = { scrub, dom, ms: S.asOf == null ? dom[1] : S.asOf };
+ if (caret.setPointerCapture && e.pointerId != null) {
+ try { caret.setPointerCapture(e.pointerId); } catch { /* older engines */ }
+ }
+}
+
+function onPointerMove(e) {
+ if (!drag) return;
+ const strip = drag.scrub.querySelector('[data-sb-strip]');
+ if (!strip) { drag = null; return; }
+ drag.ms = msFromClientX(strip, drag.dom, e.clientX);
+ previewAsOf(drag.scrub, drag.ms);
+}
+
+function onPointerUp() {
+ if (!drag) return;
+ const ms = normalizeAsOf(drag.ms, drag.dom);
+ drag = null;
+ commitAsOf(ms);
+}
+
+function onClick(e) {
+ const t = e.target;
+ if (!t || !t.closest) return;
+
+ const brainBtn = t.closest('[data-sb-brain]');
+ if (brainBtn) { switchBrain(brainBtn.getAttribute('data-sb-brain')); return; }
+
+ if (t.closest('[data-sb-now]')) { commitAsOf(null); return; }
+
+ const focusBtn = t.closest('[data-sb-focus]');
+ if (focusBtn) { refocus(focusBtn.getAttribute('data-sb-focus')); return; }
+
+ const evBtn = t.closest('[data-sb-evidence]');
+ if (evBtn) {
+ const row = evBtn.closest('[data-sb-edge]');
+ const body = row && row.querySelector('[data-sb-evbody]');
+ if (body) body.hidden = !body.hidden;
+ return;
+ }
+
+ // Click on the strip (not the caret) = jump the caret there.
+ const strip = t.closest('[data-sb-strip]');
+ if (strip && !t.closest('[data-sb-caret]')) {
+ const scrub = strip.closest('[data-sb-scrub]');
+ const dom = scrub && stripDomain(scrub);
+ if (dom) {
+ const ms = msFromClientX(strip, dom, e.clientX);
+ previewAsOf(scrub, ms);
+ commitAsOf(normalizeAsOf(ms, dom));
+ }
+ }
+}
+
+let keyCommit = 0;
+function onKeyDown(e) {
+ const caret = e.target && e.target.closest && e.target.closest('[data-sb-caret]');
+ if (!caret) return;
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
+ const scrub = caret.closest('[data-sb-scrub]');
+ const dom = scrub && stripDomain(scrub);
+ if (!dom) return;
+ e.preventDefault();
+ const step = Math.max(60_000, Math.round((dom[1] - dom[0]) / 100));
+ const cur = S.asOf == null ? dom[1] : S.asOf;
+ const next = Math.max(dom[0], Math.min(dom[1], cur + (e.key === 'ArrowRight' ? step : -step)));
+ previewAsOf(scrub, next);
+ // Debounce the server commit so holding the key doesn't queue queries.
+ clearTimeout(keyCommit);
+ keyCommit = setTimeout(() => commitAsOf(normalizeAsOf(next, dom)), 250);
+}
+
+function onResize() {
+ scheduleTraces();
+}
+
+(function wire() {
+ if (wired || typeof document === 'undefined') return;
+ wired = true;
+ document.addEventListener('click', onClick);
+ document.addEventListener('pointerdown', onPointerDown);
+ document.addEventListener('pointermove', onPointerMove);
+ document.addEventListener('pointerup', onPointerUp);
+ document.addEventListener('pointercancel', onPointerUp);
+ document.addEventListener('keydown', onKeyDown);
+ window.addEventListener('resize', onResize);
+})();
diff --git a/xerj-ux/src/ux/ego-ledger.js b/xerj-ux/src/ux/ego-ledger.js
new file mode 100644
index 000000000..89445f54e
--- /dev/null
+++ b/xerj-ux/src/ux/ego-ledger.js
@@ -0,0 +1,611 @@
+// ============================================================
+// XERJ.ai — SECOND BRAIN · EGO LEDGER primitives
+//
+// The graph view is a LEDGER, not a hairball. A global force-directed
+// graph was rejected on purpose: it collapses past ~200 nodes, its
+// layout is non-deterministic (fatal for a memory you revisit — the
+// same brain must always draw the same picture), and it optimises for
+// looking at over navigating. The ledger is an ego view:
+//
+// LEFT column = inbound edges, grouped by type
+// CENTRE = the focus card (one node, its text, its provenance)
+// RIGHT column = outbound edges, grouped by type
+//
+// Graph gestalt comes from 1px orthogonal traces drawn from the focus
+// card to each GROUP HEADER (never to every row — zero occlusion, zero
+// simulation). Hop 2 appears as a count on each neighbour row — a
+// promise of the next query, not 27 more drawn nodes. The signature
+// interaction is the BELIEF-TIME strip: every edge's validity interval
+// on one time axis with a draggable as-of caret.
+//
+// Honesty rules (§0 invariant 8 of the second-brain contract): every
+// cap this view applies is labelled in place ("TOP 12 OF 41"), the
+// honesty panel always renders — zeros prove absence — and the
+// lexical-embedder disclosure rides the timeline panel.
+//
+// Every export is a pure HTML-string renderer except
+// `drawLedgerTraces`, which measures the live DOM (trace geometry
+// depends on final text layout, so it must run post-paint).
+// ============================================================
+
+import { esc, fmt, num, Num } from './text.js';
+import { Series, Dist } from './charts.js';
+
+// Rows shown per edge-type group before the in-band "TOP n OF m" cap.
+export const LEDGER_GROUP_CAP = 12;
+// Validity rows drawn in the belief-time strip (top by weight, then
+// valid_at, then edge_id — deterministic), cap labelled in the legend.
+export const SCRUB_ROW_CAP = 64;
+
+// ----- time ---------------------------------------------------------
+
+/** Epoch-ms → 'YYYY-MM-DD HH:MM' (UTC — belief time is server time). */
+export const fmtTs = (ms) => {
+ if (ms == null || !Number.isFinite(Number(ms))) return '—';
+ return new Date(Number(ms)).toISOString().slice(0, 16).replace('T', ' ');
+};
+
+/** Epoch-ms → 'YYYY-MM-DD' (UTC). Row-width-friendly. */
+export const fmtDay = (ms) => {
+ if (ms == null || !Number.isFinite(Number(ms))) return '—';
+ return new Date(Number(ms)).toISOString().slice(0, 10);
+};
+
+/** An edge's validity window as text: '2026-07-25 → NOW' / '→ 2026-07-26'. */
+const fmtWindow = (validAt, invalidAt) =>
+ `${fmtDay(validAt)} → ${invalidAt == null ? 'NOW' : fmtDay(invalidAt)}`;
+
+// ----- bi-temporal cut (client-side preview only) -------------------
+//
+// The SERVER owns the as-of cut (`ego?as_of=`). These helpers exist so
+// the scrubber can preview visibility over already-fetched edges while
+// the caret is mid-drag; the release commits an honest re-query.
+
+export const edgeStateAt = (edge, asOfMs) => {
+ const t = asOfMs == null ? Date.now() : asOfMs;
+ if (Number(edge.valid_at) > t) return 'future';
+ if (edge.invalid_at != null && Number(edge.invalid_at) <= t) return 'expired';
+ return 'live';
+};
+
+// ----- neighbours + grouping ---------------------------------------
+
+/** The node on the far end of an edge, given the expansion direction. */
+const farEnd = (edge) => (edge.direction === 'in' ? edge.src : edge.dst);
+
+/** Display name for a node id: hydrated title if present, else the id. */
+const nodeName = (id, nodes) =>
+ (nodes && nodes[id] && nodes[id].title) ? nodes[id].title : id;
+
+/**
+ * Hop-1 edges of one side, grouped by type. Order is deterministic:
+ * groups by live-count desc then type asc; rows keep the server's
+ * contract order (hop asc, weight desc, edge_id asc) untouched — the
+ * same data always draws the same picture.
+ */
+export function groupEdges(edges, side) {
+ const byType = new Map();
+ for (const e of edges || []) {
+ if (e.hop !== 1) continue;
+ if ((side === 'out') !== (e.direction === 'out')) continue;
+ if (!byType.has(e.type)) byType.set(e.type, []);
+ byType.get(e.type).push(e);
+ }
+ const groups = [...byType.entries()].map(([type, list]) => ({ type, list }));
+ groups.sort((a, b) => b.list.length - a.list.length || (a.type < b.type ? -1 : a.type > b.type ? 1 : 0));
+ return groups;
+}
+
+/**
+ * Per-neighbour hop-2 degree: how many hop-2 edges touch this node,
+ * counting only edges live at the caret. When the server clipped the
+ * result set the count is a floor, rendered '≥n' — never a fake exact.
+ */
+export function hop2Counts(edges, asOfMs) {
+ const counts = new Map();
+ for (const e of edges || []) {
+ if (e.hop !== 2) continue;
+ if (edgeStateAt(e, asOfMs) !== 'live') continue;
+ counts.set(e.src, (counts.get(e.src) || 0) + 1);
+ counts.set(e.dst, (counts.get(e.dst) || 0) + 1);
+ }
+ return counts;
+}
+
+// ----- evidence -----------------------------------------------------
+
+/** The exact source quote that taught this edge, plus its full paper trail. */
+const EvidenceBlock = (e) => {
+ const ev = e.evidence || {};
+ const quote = ev.quote
+ ? `<p class="sb-evquote">“${esc(ev.quote)}”</p>`
+ : `<p class="sb-evquote sb-evnone">no evidence recorded for this edge</p>`;
+ const src = ev.source
+ ? `<span>${esc(ev.source)}${ev.offset != null ? ` · byte ${esc(ev.offset)}` : ''}</span>`
+ : '';
+ const invalid = e.invalid_at != null
+ ? ` · invalid ${esc(fmtTs(e.invalid_at))}` : '';
+ const expired = e.expired_at != null
+ ? ` · expiry recorded ${esc(fmtTs(e.expired_at))}` : '';
+ return `
+ <div class="sb-evbody" data-sb-evbody hidden>
+ ${quote}
+ <div class="sb-evmeta mono faint">
+ ${src}
+ <span>${esc(e.detector || 'unknown-detector')} · conf ${esc(fmt(e.confidence ?? 1, { decimals: 2 }))} · w ${esc(fmt(e.weight ?? 1, { decimals: 2 }))}</span>
+ <span>valid ${esc(fmtTs(e.valid_at))}${invalid}${expired}</span>
+ <span>edge ${esc(e.edge_id)}</span>
+ </div>
+ </div>`;
+};
+
+// ----- rows + groups ------------------------------------------------
+
+const edgeRow = (e, side, { nodes, counts, asOf, clipped }) => {
+ const id = farEnd(e);
+ const state = edgeStateAt(e, asOf);
+ const n = counts.get(id) || 0;
+ const hop2 = n > 0
+ ? (side === 'out'
+ ? `· ${clipped ? '≥' : ''}${num(n)} →`
+ : `← ${clipped ? '≥' : ''}${num(n)} ·`)
+ : '';
+ const evMark = (e.evidence && e.evidence.quote) ? 'ev' : '·';
+ return `
+ <div class="sb-erow${state === 'expired' ? ' sb-expired' : ''}${state === 'future' ? ' sb-off' : ''}"
+ data-sb-edge="${esc(e.edge_id)}" data-va="${esc(e.valid_at)}"${e.invalid_at != null ? ` data-vi="${esc(e.invalid_at)}"` : ''}>
+ <div class="sb-erow-main">
+ <button type="button" class="sb-ename" data-sb-focus="${esc(id)}"
+ title="Refocus the ledger on ${esc(id)}">${esc(nodeName(id, nodes))}</button>
+ <button type="button" class="sb-emeta" data-sb-evidence="${esc(e.edge_id)}"
+ title="Show the evidence that taught this edge">
+ <span class="sb-ewin">${esc(fmtWindow(e.valid_at, e.invalid_at))}</span>
+ <span class="sb-eev">${evMark}</span>
+ <span class="sb-ehop2">${esc(hop2)}</span>
+ <span class="sb-extag">EXPIRED</span>
+ </button>
+ </div>
+ ${EvidenceBlock(e)}
+ </div>`;
+};
+
+const groupBlock = (g, side, ctx) => {
+ const total = g.list.length;
+ const shown = Math.min(total, LEDGER_GROUP_CAP);
+ const countLabel = shown < total
+ ? `TOP ${num(shown)} OF ${num(total)}`
+ : `${num(shown)} OF ${num(total)}`;
+ const arrowType = side === 'in' ? `← ${g.type}` : `${g.type} →`;
+ return `
+ <div class="sb-group">
+ <div class="sb-grouphead" data-sb-grouphead="${side}">
+ <span class="sb-ghtype">${esc(arrowType.toUpperCase())}</span>
+ <span class="sb-ghcount">${esc(countLabel)}</span>
+ </div>
+ ${g.list.slice(0, LEDGER_GROUP_CAP).map((e) => edgeRow(e, side, ctx)).join('')}
+ </div>`;
+};
+
+// ----- focus card ---------------------------------------------------
+
+const FocusCard = ({ ego, nodes, brain }) => {
+ const id = ego.node;
+ const hop1 = (ego.edges || []).filter((e) => e.hop === 1);
+ const nIn = hop1.filter((e) => e.direction === 'in').length;
+ const nOut = hop1.length - nIn;
+ const types = new Set(hop1.map((e) => e.type)).size;
+ const earliest = hop1.length
+ ? Math.min(...hop1.map((e) => Number(e.valid_at)))
+ : null;
+ const meta = nodes && nodes[id];
+ const preview = meta && meta.preview
+ ? `<p class="sb-ftext">${esc(meta.preview)}</p>`
+ : '';
+ const dangling = !meta && ego.not_shown
+ && Array.isArray(ego.not_shown.dangling_ids)
+ && ego.not_shown.dangling_ids.includes(id);
+ return `
+ <div class="sb-focuscard" data-sb-focuscard>
+ <div class="key">FOCUS</div>
+ <div class="sb-ftitle">${esc(nodeName(id, nodes))}</div>
+ ${preview}
+ <div class="sb-fdeg mono">
+ <span>← IN <span class="sb-fnum">${num(nIn)}</span></span>
+ <span>OUT <span class="sb-fnum">${num(nOut)}</span> →</span>
+ <span>${num(types)} TYPES</span>
+ </div>
+ <div class="sb-fprov mono faint">
+ ${esc(meta && meta.index ? meta.index : `brain ${brain}`)} · ${esc(id)}${dangling ? ' · NO BACKING DOC' : ''}${earliest != null ? ` · in graph since ${esc(fmtDay(earliest))}` : ''}
+ </div>
+ </div>`;
+};
+
+// ----- controls line ------------------------------------------------
+
+const EgoControls = ({ brain, brains, focus, asOf, trail }) => {
+ const others = (brains || []).filter((b) => b !== brain);
+ const brainSwitch = others.length
+ ? `<span class="sb-cswitch">${others.map((b) =>
+ `<button type="button" class="sb-clink" data-sb-brain="${esc(b)}">${esc(b)}</button>`).join('<span class="faint"> · </span>')}</span>`
+ : '';
+ const crumbs = (trail || []).filter((t) => t !== focus).slice(-4);
+ const trailHtml = crumbs.length
+ ? `<span class="sb-ctrail">${crumbs.map((t) =>
+ `<button type="button" class="sb-clink" data-sb-focus="${esc(t)}">${esc(t)}</button>`).join('<span class="faint"> → </span>')}<span class="faint"> → </span></span>`
+ : '';
+ return `
+ <div class="sb-controls mono">
+ <span><span class="key">BRAIN</span> <span class="sb-cval">${esc(brain || '—')}</span> ${brainSwitch}</span>
+ <span><span class="key">FOCUS</span> ${trailHtml}<span class="sb-cval">${esc(focus || '—')}</span></span>
+ <span><span class="key">AS OF</span> <span class="sb-cval${asOf != null ? ' accent' : ''}">${asOf != null ? esc(fmtTs(asOf)) + ' UTC' : 'NOW'}</span>${asOf != null ? ` <button type="button" class="sb-clink" data-sb-now>RESET</button>` : ''}</span>
+ <span class="sb-cerr" data-sb-error></span>
+ </div>`;
+};
+
+// ----- belief-time scrubber ----------------------------------------
+
+/**
+ * Full-width strip of edge-validity intervals over one time axis with a
+ * draggable as-of caret. The interval set comes from a timeline query
+ * pinned at NOW with include_expired=true, so scrubbing left never
+ * makes the strip itself lose rows — only their visibility state
+ * changes. Dragging previews client-side; releasing re-queries the
+ * server with `as_of` (the caret is a query parameter, not a filter).
+ */
+export const BeliefScrubber = ({ timeline, asOf }) => {
+ const edges = (timeline && timeline.edges) || [];
+ if (!edges.length) {
+ return `<div class="sb-scrub" data-sb-scrub><div class="panel-empty mono faint">NO VALIDITY INTERVALS YET · EVERY EDGE DRAWS ITS LIFETIME HERE</div></div>`;
+ }
+ // Deterministic row order: weight desc, valid_at asc, edge_id asc.
+ const rows = [...edges].sort((a, b) =>
+ (b.weight - a.weight)
+ || (Number(a.valid_at) - Number(b.valid_at))
+ || (a.edge_id < b.edge_id ? -1 : 1)
+ ).slice(0, SCRUB_ROW_CAP);
+
+ const now = Date.now();
+ const d0raw = Math.min(...rows.map((e) => Number(e.valid_at)));
+ const span = Math.max(now - d0raw, 60_000);
+ const d0 = d0raw - span * 0.04; // 4% air before the first assertion
+ const d1 = now;
+ const pctOf = (ms) => Math.max(0, Math.min(100, ((ms - d0) / (d1 - d0)) * 100));
+
+ const rowH = 4;
+ const h = rows.length * rowH + 6;
+ const caretMs = asOf == null ? d1 : asOf;
+ const caretPct = pctOf(caretMs);
+
+ const lines = rows.map((e, i) => {
+ const y = 4 + i * rowH;
+ const x1 = pctOf(Number(e.valid_at));
+ const x2 = e.invalid_at != null ? pctOf(Number(e.invalid_at)) : 100;
+ const state = edgeStateAt(e, asOf);
+ const tick = e.invalid_at != null
+ ? `<line class="sb-ltick" x1="${x2}%" x2="${x2}%" y1="${y - 2}" y2="${y + 2}" stroke="currentColor" stroke-width="1"/>`
+ : '';
+ return `<line class="sb-lseg sb-l-${state}" data-va="${esc(e.valid_at)}"${e.invalid_at != null ? ` data-vi="${esc(e.invalid_at)}"` : ''} x1="${x1}%" x2="${x2}%" y1="${y}" y2="${y}" stroke="currentColor" stroke-width="1"/>${tick}`;
+ }).join('');
+
+ const capNote = edges.length > rows.length
+ ? ` · TOP ${num(rows.length)} OF ${num(edges.length)} BY WEIGHT`
+ : '';
+
+ return `
+ <div class="sb-scrub" data-sb-scrub data-d0="${d0}" data-d1="${d1}">
+ <div class="key">BELIEF TIME · DRAG THE CARET · WHAT DID THIS BRAIN BELIEVE, WHEN</div>
+ <div class="sb-strip" data-sb-strip style="height:${h}px;">
+ <svg class="chart sb-striplines" width="100%" height="${h}" aria-hidden="true">${lines}</svg>
+ <div class="sb-caret" data-sb-caret style="left:${caretPct}%;" role="slider" tabindex="0"
+ aria-label="Belief as-of caret" aria-valuemin="${d0}" aria-valuemax="${d1}" aria-valuenow="${caretMs}"></div>
+ <div class="sb-caret-label mono" data-sb-caret-label style="left:${caretPct}%;">${asOf == null ? 'NOW' : esc(fmtTs(caretMs))}</div>
+ </div>
+ <div class="sb-scrub-legend mono faint">
+ <span>${esc(fmtTs(d0raw))} UTC</span>
+ <span class="mid">${num(rows.length)} VALIDITY INTERVALS${esc(capNote)} · EXPIRED EDGES KEEP THEIR ROW</span>
+ <span><button type="button" class="text-btn" data-sb-now>NOW</button></span>
+ </div>
+ </div>`;
+};
+
+// ----- the ledger ---------------------------------------------------
+
+const sideCol = (groups, side, ctx, label) => {
+ const inner = groups.length
+ ? groups.map((g) => groupBlock(g, side, ctx)).join('')
+ : `<div class="sb-sidenote mono faint">${esc(label)}</div>`;
+ return `<div class="sb-col sb-col-${side}">${inner}</div>`;
+};
+
+/** The three-column ego ledger + rails + scrubber. */
+export const EgoLedger = ({ data }) => {
+ const sb = data.sb || {};
+ const ego = data.ego;
+ const asOf = sb.asOf ?? null;
+ if (!ego) {
+ // Controls stay up even without a belief response so the user can
+ // switch brain / reset the caret out of a dead end.
+ return `
+ ${EgoControls({ brain: data.brain, brains: sb.brains, focus: sb.focus, asOf, trail: sb.trail })}
+ <div class="panel-empty mono faint">${sb.focus ? 'LOADING BELIEF · ' + esc(String(sb.focus).toUpperCase()) : 'NO FOCUS NODE · PICK A HUB BELOW TO OPEN THE LEDGER'}</div>`;
+ }
+ const nodes = ego.nodes || {};
+ const clipped = !!(ego.not_shown && ego.not_shown.edges_clipped > 0);
+ const counts = hop2Counts(ego.edges, asOf);
+ const ctx = { nodes, counts, asOf, clipped };
+ const inGroups = groupEdges(ego.edges, 'in');
+ const outGroups = groupEdges(ego.edges, 'out');
+ const hop1 = (ego.edges || []).filter((e) => e.hop === 1);
+
+ const body = hop1.length
+ ? `
+ <div class="sb-ledger" data-sb-ledger>
+ ${sideCol(inGroups, 'in', ctx, 'NOTHING POINTS HERE AT THIS AS-OF')}
+ <div class="sb-rail" data-sb-rail="in" aria-hidden="true"></div>
+ ${FocusCard({ ego, nodes, brain: data.brain })}
+ <div class="sb-rail" data-sb-rail="out" aria-hidden="true"></div>
+ ${sideCol(outGroups, 'out', ctx, 'THIS NODE POINTS AT NOTHING AT THIS AS-OF')}
+ </div>`
+ : `
+ <div class="sb-ledger" data-sb-ledger>
+ <div class="sb-col sb-col-in"></div>
+ <div class="sb-rail" data-sb-rail="in" aria-hidden="true"></div>
+ ${FocusCard({ ego, nodes, brain: data.brain })}
+ <div class="sb-rail" data-sb-rail="out" aria-hidden="true"></div>
+ <div class="sb-col sb-col-out"></div>
+ </div>
+ <div class="panel-empty mono faint">NO EDGES TOUCH ${esc(ego.node.toUpperCase())} AT THIS AS-OF · SCRUB TO NOW OR PICK A HUB BELOW</div>`;
+
+ return `
+ ${EgoControls({ brain: data.brain, brains: sb.brains, focus: ego.node, asOf, trail: sb.trail })}
+ ${body}
+ ${BeliefScrubber({ timeline: sb.timeline, asOf })}`;
+};
+
+// ----- honesty panel ------------------------------------------------
+
+const hrow = (k, v, emph) => `
+ <div class="sb-hrow">
+ <span class="sb-hk">${esc(k)}</span>
+ <span class="sb-hv${emph && v !== '0' ? ' accent' : ''}">${esc(v)}</span>
+ </div>`;
+
+/**
+ * Definition list over every `not_shown` counter of both endpoints plus
+ * the view's own caps. ALWAYS renders, zeros included — this panel
+ * exists to prove absence, not just to report presence.
+ */
+export const HonestyList = ({ data }) => {
+ const ns = (data.ego && data.ego.not_shown) || {};
+ const on = (data.overview && data.overview.not_shown) || {};
+ const z = (v) => num(v || 0);
+ const dangling = Array.isArray(ns.dangling_ids) && ns.dangling_ids.length
+ ? `<div class="sb-hids mono faint">dangling: ${ns.dangling_ids.slice(0, 8).map(esc).join(', ')}${ns.dangling_ids.length > 8 ? ` +${ns.dangling_ids.length - 8} more` : ''}</div>`
+ : '';
+ const timelineEdges = (data.sb && data.sb.timeline && data.sb.timeline.edges) || [];
+ const scrubHidden = Math.max(0, timelineEdges.length - SCRUB_ROW_CAP);
+ return `
+ <div class="sb-honesty mono">
+ <div class="sb-hgroup key">EGO QUERY</div>
+ ${hrow('edges clipped', z(ns.edges_clipped), true)}
+ ${hrow('frontier clipped', z(ns.frontier_clipped), true)}
+ ${hrow('expired excluded', z(ns.expired_excluded), false)}
+ ${hrow('type filtered', z(ns.type_filtered), false)}
+ ${hrow('segments without columns', z(ns.segments_without_columns), true)}
+ ${hrow('memtable docs scanned', z(ns.memtable_docs_scanned), false)}
+ ${hrow('dangling node refs', z(ns.dangling_nodes), true)}
+ ${dangling}
+ <div class="sb-hgroup key">OVERVIEW AGGS</div>
+ ${hrow('types not listed', z(on.types_not_listed), true)}
+ ${hrow('detectors not listed', z(on.detectors_not_listed), true)}
+ ${hrow('hubs (out) not listed', z(on.hubs_out_not_listed), false)}
+ ${hrow('hubs (in) not listed', z(on.hubs_in_not_listed), false)}
+ <div class="sb-hgroup key">THIS VIEW</div>
+ ${hrow('ledger rows per group', `≤ ${num(LEDGER_GROUP_CAP)} (capped groups say so)`, false)}
+ ${hrow('scrubber rows hidden', z(scrubHidden), false)}
+ </div>`;
+};
+
+// ----- hubs ---------------------------------------------------------
+
+const hubList = (items, notListed, side, focus) => {
+ if (!items || !items.length) return `<div class="faint mono">No hubs yet.</div>`;
+ const max = Math.max(...items.map((i) => i.live_edges), 1);
+ const rows = items.map((i) => {
+ const frac = Math.max(0, Math.min(1, i.live_edges / max));
+ return `
+ <div class="row clickable${i.id === focus ? ' sb-hub-active' : ''}" data-sb-focus="${esc(i.id)}" role="button"
+ title="Refocus the ledger on ${esc(i.id)}">
+ <div class="row__label">${esc(i.id)}</div>
+ <div class="row__val">${esc(num(i.live_edges))}</div>
+ <div class="row__bar">
+ <svg class="chart" height="6" viewBox="0 0 200 6" preserveAspectRatio="none">
+ <line x1="0" y1="5" x2="${(frac * 200).toFixed(1)}" y2="5" stroke="currentColor" stroke-width="1"/>
+ </svg>
+ </div>
+ <div class="row__pct">${side === 'out' ? 'out' : 'in'}</div>
+ </div>`;
+ }).join('');
+ const tail = notListed > 0
+ ? `<div class="hint">+ ${num(notListed)} more not listed</div>` : '';
+ return rows + tail;
+};
+
+export const HubsPanel = ({ data }) => {
+ const o = data.overview || {};
+ const hubs = o.hubs || { out: [], in: [] };
+ const ns = o.not_shown || {};
+ const focus = data.sb ? data.sb.focus : null;
+ return `
+ <div class="sb-hubs">
+ <div>
+ <div class="key">OUT · MOST ASSERTIVE</div>
+ ${hubList(hubs.out, ns.hubs_out_not_listed, 'out', focus)}
+ </div>
+ <div>
+ <div class="key">IN · MOST CITED</div>
+ ${hubList(hubs.in, ns.hubs_in_not_listed, 'in', focus)}
+ </div>
+ </div>
+ <div class="hint" style="margin-top:var(--sp-1);">click a hub to refocus the ledger</div>`;
+};
+
+// ----- small panels -------------------------------------------------
+
+const TypeDistPanel = ({ data }) => {
+ const o = data.overview || {};
+ const types = o.types || [];
+ if (!types.length) return `<div class="panel-empty mono faint">NO LIVE EDGES AT THIS AS-OF</div>`;
+ const tail = o.not_shown && o.not_shown.types_not_listed > 0
+ ? `<div class="hint">+ ${num(o.not_shown.types_not_listed)} types not listed</div>` : '';
+ return Dist({ segments: types.map((t) => ({ label: t.type, value: t.live })) }) + tail;
+};
+
+const TimelinePanel = ({ data }) => {
+ const o = data.overview || {};
+ const series = (data.series && data.series.created) || [];
+ const ts = (data.series && data.series.createdT) || [];
+ // §0 invariant 8: the default embedder is lexical feature-hashing; any
+ // surface that could imply neural semantics must say otherwise.
+ const embedderNote = o.embedder === 'lexical-feature-hash'
+ ? `<div class="hint" style="margin-top:var(--sp-1);">recall is lexical (feature hashing) — not neural</div>`
+ : (o.embedder ? `<div class="hint" style="margin-top:var(--sp-1);">embedder · ${esc(o.embedder)}</div>` : '');
+ if (series.length < 2) {
+ const one = series.length === 1
+ ? `<div class="mono">${esc(num(series[0]))} edges asserted · ${esc(fmtDay(ts[0]))}</div>` : '';
+ return `${one || '<div class="panel-empty mono faint">NO ASSERTIONS RECORDED YET</div>'}${embedderNote}`;
+ }
+ return Series(series, {
+ h: 120,
+ labels: [fmtDay(ts[0]), fmtDay(ts[ts.length - 1])],
+ unit: 'edges',
+ }) + embedderNote;
+};
+
+const metricPanel = (data, id) => {
+ const m = data.metrics && data.metrics[id];
+ if (!m) return `<div class="panel-empty mono faint">—</div>`;
+ return Num({
+ value: m.formatted,
+ unit: id === 'detectors' ? 'active' : 'edges',
+ hint: m.hint,
+ emphasis: id === 'edgesLive',
+ });
+};
+
+// ----- empty / disconnected states ---------------------------------
+
+/**
+ * The dashboard reads the LIVE graph endpoints only — no demo numbers.
+ * Anything else on this page would be a fake brain.
+ */
+const LiveOnlyNote = () => `
+ <div class="sb-empty">
+ <div class="mono">THIS DASHBOARD READS THE LIVE ENGINE · IT NEVER SHOWS DEMO DATA</div>
+ <div class="mono faint" style="margin-top:var(--sp-1);">start xerj, point the console at it (SETTINGS → BACKEND · XERJ), reload</div>
+ </div>`;
+
+/** A brand-new brain: tell the user exactly how to fill it. */
+export const EmptyBrainNote = ({ brain, connected, error }) => {
+ if (!connected) {
+ return `
+ <div class="sb-empty">
+ <div class="mono">ENGINE UNREACHABLE${error ? ` · ${esc(String(error).slice(0, 80).toUpperCase())}` : ''}</div>
+ <div class="mono faint" style="margin-top:var(--sp-1);">start xerj and reload — this dashboard reads the live graph API only</div>
+ </div>`;
+ }
+ const b = brain || 'notes';
+ return `
+ <div class="sb-empty">
+ <div class="sb-ftitle">THIS BRAIN IS EMPTY</div>
+ <p class="sb-ftext">No edges yet. A second brain grows from documents you already have —
+ point the deterministic detectors at any folder and every wiki-link, relative link and
+ file adjacency becomes an edge with evidence:</p>
+ <pre class="sb-cmd mono">xerj autoindex ~/notes --brain ${esc(b)}</pre>
+ <p class="sb-ftext">or assert the first edge yourself:</p>
+ <pre class="sb-cmd mono">curl -X POST localhost:9200/_graph/${esc(b)}/link \\
+ -H 'content-type: application/json' \\
+ -d '{"src":"note-a","dst":"note-b","type":"cites"}'</pre>
+ <div class="mono faint">then reload — the ledger, hubs and belief-time strip fill themselves</div>
+ </div>`;
+};
+
+// ----- panel dispatcher ---------------------------------------------
+//
+// One function renders the INNER body of every second-brain panel so
+// the interaction controller (data/second-brain-api.js) can re-render
+// any panel in place after a refocus / as-of commit without the app's
+// whole-page render loop.
+
+export function renderPanelBody(id, data) {
+ if (!data || !data.sb) return LiveOnlyNote();
+ const sb = data.sb;
+ const hasBrain = !!(data.overview && data.overview.exists !== false);
+ const hasEdges = hasBrain && data.overview.edges && data.overview.edges.total > 0;
+
+ switch (id) {
+ case 'edgesLive':
+ case 'edgesTotal':
+ case 'invalidated':
+ case 'detectors':
+ return metricPanel(data, id);
+ case 'typeDist':
+ return hasEdges ? TypeDistPanel({ data }) : `<div class="panel-empty mono faint">NO EDGE TYPES YET</div>`;
+ case 'edgeTimeline':
+ return hasEdges ? TimelinePanel({ data }) : `<div class="panel-empty mono faint">NO ASSERTIONS YET</div>`;
+ case 'ego':
+ return hasEdges
+ ? EgoLedger({ data })
+ : EmptyBrainNote({ brain: data.brain, connected: sb.connected, error: sb.error });
+ case 'hubs':
+ return hasEdges ? HubsPanel({ data }) : `<div class="panel-empty mono faint">NO HUBS YET</div>`;
+ case 'notShown':
+ // Always renders — zeros prove absence.
+ return HonestyList({ data });
+ default:
+ return `<div class="panel-empty mono faint">UNKNOWN PANEL · ${esc(id)}</div>`;
+ }
+}
+
+// ----- post-paint trace drawing -------------------------------------
+
+const crisp = (v) => Math.round(v) + 0.5;
+
+/**
+ * Draw the 1px orthogonal traces from the focus card to each group
+ * header. Runs against the live DOM because the endpoints are text
+ * blocks whose heights depend on final layout — this is a measure +
+ * draw pass, not a simulation. Same data + same viewport ⇒ same
+ * traces (deterministic by construction).
+ */
+export function drawLedgerTraces(scope) {
+ if (typeof document === 'undefined') return;
+ const root = scope || document;
+ const ledger = root.querySelector('[data-sb-ledger]');
+ if (!ledger) return;
+ const card = ledger.querySelector('[data-sb-focuscard]');
+ if (!card) return;
+ const cardRect = card.getBoundingClientRect();
+ for (const side of ['in', 'out']) {
+ const rail = ledger.querySelector(`[data-sb-rail="${side}"]`);
+ if (!rail) continue;
+ const rr = rail.getBoundingClientRect();
+ if (rr.width < 8 || rr.height < 8) { rail.innerHTML = ''; continue; }
+ const W = rr.width;
+ const H = rr.height;
+ const fy = crisp(Math.max(6, Math.min(H - 6, cardRect.top + cardRect.height / 2 - rr.top)));
+ const midX = crisp(W / 2);
+ let d = '';
+ for (const head of ledger.querySelectorAll(`[data-sb-grouphead="${side}"]`)) {
+ const hr = head.getBoundingClientRect();
+ const hy = crisp(Math.max(2, Math.min(H - 2, hr.top + hr.height / 2 - rr.top)));
+ // Left rail: header edge at x=0, focus edge at x=W. Right rail mirrored.
+ d += side === 'in'
+ ? `M0 ${hy} H${midX} V${fy} H${W} `
+ : `M${W} ${hy} H${midX} V${fy} H0 `;
+ }
+ rail.innerHTML = d
+ ? `<svg class="sb-trace" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" aria-hidden="true"><path d="${d}" fill="none" stroke="currentColor" stroke-width="1"/></svg>`
+ : '';
+ }
+}