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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
build(console): track xerj-ux so the engine bundles a working Console
xerj-orgac87d7f274ea
diff --git a/.gitignore b/.gitignoreindex 083b99d6b..99f094975 100644--- a/.gitignore+++ b/.gitignore@@ -70,7 +70,9 @@ engine/build.log# OSS release hygiene (added by RELEASE_HYGIENE_AUDIT). Additive only —# NOTE: ignoring a path does not untrack files already committed. To stop# shipping the internal dirs below, maintainers must also run:-# git rm -r --cached brief xerj-ux landing/resources/xerj-sales-kit.zip+# git rm -r --cached brief landing/resources/xerj-sales-kit.zip+# (xerj-ux/ is intentionally tracked — the Console UI ships with the+# open-source engine so the binary bundles a working console.)# ----------------------------------------------------------------------# Local Cloudflare Wrangler state (may contain account/session data).@@ -79,7 +81,6 @@ engine/build.log# Internal go-to-market material — not part of the OSS engine.# (Recommended for a separate repo; see docs/RELEASE_HYGIENE_AUDIT.md.)brief/-xerj-ux/landing/resources/xerj-sales-kit.zip# Re-include root OSS scaffolding so the default *.md / no-extension@@ -97,3 +98,8 @@ landing/resources/xerj-sales-kit.zip!docs/ARCHITECTURE.md!ROADMAP.md!docs/**/*.md++# Transient demo-capture artifacts (local paths + ephemeral tokens)+demo/screenshots/manifest.json+demo/.flow-data/+demo/.flow-chrome/diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.cssnew file mode 100644index 000000000..ffcb74958--- /dev/null+++ b/xerj-ux/assets/base.css@@ -0,0 +1,1542 @@+/* ============================================================+ XERJ.ai — Base styles+ Only typographic roles and layout. Zero decoration.+ ============================================================ */++*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }++html, body {+ background: var(--z-paper);+ color: var(--z-ink);+ min-height: 100vh;+}++body {+ font-family: var(--font-prose);+ font-size: var(--fs-13);+ font-weight: 400;+ line-height: 1.45;+ font-feature-settings: 'kern', 'ss01', 'cv11';+ -webkit-font-smoothing: antialiased;+ text-rendering: optimizeLegibility;+ padding: var(--page-y) var(--page-x);+ max-width: 1680px;+ margin: 0 auto;+}++::selection { background: var(--z-accent); color: var(--z-paper); }++a {+ color: inherit;+ text-decoration: none;+ text-underline-offset: 4px;+ text-decoration-thickness: 1px;+}+a:hover { text-decoration: underline; }++button {+ background: none;+ border: none;+ padding: 0;+ font: inherit;+ color: inherit;+ cursor: pointer;+ letter-spacing: inherit;+ text-transform: inherit;+}++/* ---- Typographic roles ----------------------------------- */++.h-scene {+ font-family: var(--font-display);+ font-weight: 900;+ font-size: var(--fs-96);+ line-height: 0.88;+ letter-spacing: var(--track-tight);+ text-transform: uppercase;+}+@media (max-width: 1200px) { .h-scene { font-size: 72px; } }++.h-section {+ font-family: var(--font-display);+ font-weight: 800;+ font-size: var(--fs-32);+ line-height: 1;+ letter-spacing: 0.02em;+ text-transform: uppercase;+}++.key {+ font-family: var(--font-prose);+ font-weight: 600;+ font-size: var(--fs-11);+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ color: var(--z-mute);+}++.hint {+ font-family: var(--font-data);+ font-size: var(--fs-11);+ color: var(--z-mute);+ letter-spacing: 0.04em;+}++.mono {+ font-family: var(--font-data);+ font-variant-numeric: tabular-nums;+}++.num-big {+ font-family: var(--font-display);+ font-weight: 800;+ font-size: var(--fs-56);+ line-height: 0.92;+ letter-spacing: var(--track-tight);+ font-variant-numeric: tabular-nums;+}++.num-md {+ font-family: var(--font-data);+ font-weight: 700;+ font-size: var(--fs-32);+ line-height: 1;+ font-variant-numeric: tabular-nums;+}++.num-unit {+ font-family: var(--font-prose);+ font-weight: 500;+ font-size: 0.28em;+ color: var(--z-mute);+ letter-spacing: 0.14em;+ text-transform: uppercase;+ margin-left: 0.4em;+ vertical-align: 0.6em;+}++.accent { color: var(--z-accent); }+.faint { color: var(--z-mute); }+.dim { color: var(--z-mute); }++/* ---- Layout grid ----------------------------------------- */++.canvas {+ display: grid;+ grid-template-columns: repeat(12, 1fr);+ column-gap: var(--gap-x);+ row-gap: var(--gap-y);+ align-items: start;+ position: relative;+}+/* Edit mode: uniform cells so drag/drop feels like a real grid. */+.canvas.edit {+ align-items: stretch;+ grid-auto-rows: minmax(140px, auto);+}++.panel { min-width: 0; }+.panel > .key { margin-bottom: 12px; }+.panel > .h-section { margin-bottom: 16px; }++.stack { display: flex; flex-direction: column; gap: var(--sp-1); }+.stack-2 { display: flex; flex-direction: column; gap: var(--sp-2); }+.stack-3 { display: flex; flex-direction: column; gap: var(--sp-3); }+.row-flex { display: flex; align-items: baseline; gap: var(--sp-2); flex-wrap: wrap; }++/* ---- Charts ---------------------------------------------- */++.chart {+ display: block;+ color: var(--z-ink);+ shape-rendering: geometricPrecision;+ overflow: visible;+}+.chart line, .chart polyline {+ vector-effect: non-scaling-stroke;+ stroke-linecap: butt;+ stroke-linejoin: round;+}+/* Horizontal 1px bars need pixel snapping; diagonals need AA. */+.chart line { shape-rendering: crispEdges; }+.chart polyline { shape-rendering: geometricPrecision; }++/* ---- Top-N row ------------------------------------------- */++.row {+ display: grid;+ grid-template-columns: 1fr 88px 1fr 56px;+ gap: var(--sp-2);+ align-items: baseline;+ padding: 5px 0;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+ line-height: 1.3;+}+.row__label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.row__val { text-align: right; font-weight: 700; }+.row__pct { text-align: right; color: var(--z-mute); font-size: var(--fs-11); }+.row__bar { min-width: 0; display: flex; align-items: center; }+.row__bar svg { width: 100%; }+.row.clickable { cursor: pointer; }+.row.clickable:hover .row__label { color: var(--z-accent); }++/* ---- Distribution ---------------------------------------- */++.dist-bar { width: 100%; height: 10px; margin-bottom: var(--sp-2); }+.dist-legend {+ display: flex;+ gap: var(--sp-4);+ flex-wrap: wrap;+}+.dist-legend > * { min-width: 140px; }++/* ---- Flowband -------------------------------------------- */++/* Horizontal allocation band. Labels sit in an HTML flex layer+ where each item's grow factor equals the raw value, so label+ widths match segment widths exactly. min-width:0 + overflow+ hidden ensures tiny slices don't push big ones out of line. */+.flowband-wrap { margin: var(--sp-2) 0 var(--sp-4); color: var(--z-ink); }+.flowband-svg { color: var(--z-ink); }+.flowband-labels { gap: var(--sp-2); }+.flowband-labels .fb-seg {+ overflow: hidden;+ padding-right: var(--sp-2);+}+.flowband-labels .fb-label {+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--z-ink);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.flowband-labels .fb-value {+ font-family: var(--font-data);+ font-variant-numeric: tabular-nums;+ font-size: 10px;+ color: var(--z-mute);+ margin-top: 2px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++/* ---- Heatmap --------------------------------------------- */++/* Heatmap uses monospace so the inline `width: Xch` cell spans+ actually align — `ch` == character width only for monospace.+ Proportional fonts make $-prefixed cells overflow the slot. */+.heatmap {+ font-family: var(--font-mono);+ font-size: var(--fs-13);+ line-height: 1.55;+ letter-spacing: 0;+ font-variant-numeric: tabular-nums;+}+.heatmap-row { display: block; white-space: nowrap; }+.heatmap-row .row-label {+ display: inline-block;+ width: 5ch;+ color: var(--z-mute);+ margin-right: 1.5ch;+ font-size: var(--fs-13);+ letter-spacing: 0;+ text-transform: uppercase;+ font-family: var(--font-mono);+}++/* ---- Series (full-width line) ---------------------------- */++.series { width: 100%; }+.series-legend {+ display: flex;+ justify-content: space-between;+ margin-top: var(--sp-1);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ color: var(--z-mute);+ letter-spacing: 0.06em;+}+.series-legend .mid { flex: 1; text-align: center; }++/* ---- Multiples ------------------------------------------- */++.multiples {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));+ gap: var(--sp-3) var(--sp-4);+}+.mult {+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ min-width: 0;+}+.mult-head {+ display: flex;+ justify-content: space-between;+ align-items: baseline;+ color: var(--z-mute);+ letter-spacing: 0.06em;+ text-transform: uppercase;+}+.mult-head .name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ margin-right: var(--sp-1);+}+.mult-head .val { color: var(--z-ink); font-weight: 700; font-variant-numeric: tabular-nums; }++/* ---- Chrome: nav + scene + time ------------------------- */++.nav {+ display: flex;+ align-items: baseline;+ gap: var(--sp-4);+ margin-bottom: var(--sp-8);+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+}+.nav .brand {+ color: var(--z-ink);+ font-family: var(--font-display);+ font-weight: 900;+ font-size: var(--fs-13);+ letter-spacing: 0.24em;+ margin-right: var(--sp-3);+}+.nav a { color: var(--z-mute); }+.nav a:hover { color: var(--z-ink); }+.nav a.active { color: var(--z-ink); }+.nav .spacer { flex: 1; }+.nav .status { color: var(--z-mute); font-family: var(--font-data); font-weight: 500; letter-spacing: 0.1em; margin-left: var(--sp-3); }++/* Secondary nav row — dashboards list, visible only when+ * activeSection === 'dashboards'. Slightly smaller than primary,+ * mono font to distinguish from product-level sections. */+.nav-sub {+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ margin-top: -22px; /* pull up closer to the primary row */+ margin-bottom: var(--sp-8);+ /* No left padding — align with the brand/primary nav column. */+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ flex-wrap: wrap;+}+.nav-sub a {+ color: var(--z-mute);+ padding: 2px 0;+}+.nav-sub a:hover { color: var(--z-ink); }+.nav-sub a.active { color: var(--z-accent); }++/* Grouped sub-nav — folders / dropdowns. A group is either "open"+ (its dashboards render inline next to the label) or collapsed+ (just the label, click to switch groups). Typography-only — no+ boxes or borders. */+.nav-sub .group {+ display: inline-flex;+ align-items: baseline;+ gap: var(--sp-2);+ margin-right: var(--sp-4);+}+.nav-sub .group-label {+ background: none;+ border: 0;+ padding: 2px 0;+ font: inherit;+ text-transform: uppercase;+ letter-spacing: 0.12em;+ color: var(--z-mute);+ cursor: pointer;+}+.nav-sub .group-label:hover { color: var(--z-ink); }+.nav-sub .group.open .group-label {+ color: var(--z-ink);+ font-weight: 700;+}+.nav-sub .group.open .group-label::after {+ content: ' :';+ color: var(--z-mute);+ margin-left: 2px;+ font-weight: 400;+}+.nav-sub .group .members {+ display: inline-flex;+ align-items: baseline;+ gap: var(--sp-3);+}++/* Theme toggle — text only, matches .time button styling */+.theme {+ display: inline-flex;+ align-items: baseline;+ gap: 8px;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.theme .dash { color: var(--z-faint); }+.theme button { color: var(--z-mute); }+.theme button:hover { color: var(--z-ink); }+.theme button.active { color: var(--z-accent); }++.scene {+ margin-bottom: var(--sp-6);+}+.scene .kicker {+ margin-bottom: var(--sp-2);+ display: flex;+ gap: var(--sp-2);+ align-items: baseline;+}+.scene .kicker .dash { color: var(--z-faint); }++.time, .refresh {+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.time .key, .refresh .key { margin: 0 var(--sp-2) 0 0; color: var(--z-mute); }+.time button, .refresh button { color: var(--z-mute); background: none; border: 0; font: inherit; cursor: pointer; }+.time button:hover, .refresh button:hover { color: var(--z-ink); }+.time button.active, .refresh button.active { color: var(--z-accent); }++/* Absolute time range inputs, only shown when RANGE = CUSTOM. */+.time .custom-range {+ display: inline-flex;+ align-items: baseline;+ gap: var(--sp-2);+ margin-left: var(--sp-3);+}+.time .custom-range input[type="datetime-local"] {+ background: none;+ border: 0;+ border-bottom: 1px solid var(--z-line);+ color: var(--z-ink);+ font: inherit;+ font-family: var(--font-mono);+ font-size: var(--fs-11);+ padding: 2px 0;+ color-scheme: dark;+ outline: none;+}+.time .custom-range input[type="datetime-local"]:focus { border-bottom-color: var(--z-accent); }+.time .custom-range .dash { color: var(--z-mute); }++/* Row wrapping the time + refresh controls at the top of a dashboard. */+.dash-ctrls {+ display: flex;+ align-items: baseline;+ gap: var(--sp-8);+ margin-bottom: var(--sp-6);+ flex-wrap: wrap;+}++/* -----------------------------------------------------------+ * Filter bar — global dashboard filters. Two rows:+ * .kql — a frameless text input for KQL-lite expressions+ * .pills — the current filter pills + CLEAR ALL+ * Corpus evidence: top Kibana pain is filters scoped to+ * visualizations, not the dashboard. OR filter support is+ * GH#3693, the 41-score multi-select (OR) ask.+ * ----------------------------------------------------------- */+.filter-bar {+ display: block;+ margin-bottom: var(--sp-6);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.filter-bar .key { color: var(--z-mute); margin-right: var(--sp-2); }+.filter-bar .hint { font-weight: 400; }++.filter-bar .kql {+ display: flex;+ align-items: baseline;+ gap: var(--sp-2);+ margin-bottom: var(--sp-3);+}+.filter-bar .kql input {+ flex: 1;+ background: none;+ border: 0;+ border-bottom: 1px solid var(--z-line);+ font-family: var(--font-mono);+ font-size: var(--fs-13);+ color: var(--z-ink);+ padding: 4px 0;+ text-transform: none;+ letter-spacing: 0;+ outline: none;+ min-width: 0;+}+.filter-bar .kql input:focus { border-bottom-color: var(--z-accent); }+.filter-bar .kql input::placeholder { color: var(--z-mute); opacity: 0.6; }++.filter-bar .pills {+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ flex-wrap: wrap;+}+.filter-bar .pill {+ display: inline-flex;+ align-items: baseline;+ gap: 2px;+ color: var(--z-accent);+}+.filter-bar .pill .field { opacity: 0.72; }+.filter-bar .pill .eq { opacity: 0.5; margin: 0 2px; }+.filter-bar .pill .or { opacity: 0.45; margin: 0 4px; font-size: 10px; }+.filter-bar .pill .chip {+ display: inline-flex;+ align-items: baseline;+ gap: 2px;+ padding: 0;+ color: inherit;+ background: none;+ border: 0;+ font: inherit;+ cursor: pointer;+}+.filter-bar .pill .chip .value { font-weight: 600; }+.filter-bar .pill .chip .x { margin-left: 4px; opacity: 0.55; }+.filter-bar .pill .chip:hover .x { opacity: 1; color: var(--z-ink); }+.filter-bar .clear {+ color: var(--z-mute);+ background: none;+ border: 0;+ font: inherit;+ cursor: pointer;+ padding: 0;+ margin-left: auto;+}+.filter-bar .clear:hover { color: var(--z-ink); }++/* Small arrow hint on a panel eyebrow that signals a drilldown target. */+.drill-hint {+ margin-left: var(--sp-3);+ color: var(--z-accent);+ font-size: var(--fs-11);+}++/* Typography-first empty state used when a panel's data is blank. */+.panel-empty {+ padding: var(--sp-6) 0;+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}++/* Retry button on dashboard-level error. */+.text-btn {+ background: none;+ border: 0;+ font: inherit;+ color: var(--z-accent);+ cursor: pointer;+ text-transform: uppercase;+ letter-spacing: var(--track-ui);+ font-size: var(--fs-13);+}+.text-btn:hover { color: var(--z-ink); }++/* Saved views row — pinnable named snapshots per dashboard. */+.saved-views {+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ margin-bottom: var(--sp-6);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+ flex-wrap: wrap;+}+.saved-views .key { color: var(--z-mute); margin-right: var(--sp-2); }+.saved-views .hint { font-weight: 400; }+.saved-views .view { color: var(--z-accent); background: none; border: 0; font: inherit; cursor: pointer; }+.saved-views .view:hover { color: var(--z-ink); }+.saved-views .sep { color: var(--z-mute); opacity: 0.4; }+.saved-views .x { background: none; border: 0; font: inherit; color: var(--z-mute); cursor: pointer; opacity: 0.5; }+.saved-views .x:hover { color: var(--z-accent); opacity: 1; }+.saved-views .save { margin-left: auto; color: var(--z-mute); background: none; border: 0; font: inherit; cursor: pointer; }+.saved-views .save:hover { color: var(--z-accent); }++/* Cluster selector. */+.cluster-ctrl {+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ font-weight: 500;+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.cluster-ctrl .key { color: var(--z-mute); margin-right: var(--sp-2); }+.cluster-ctrl button { color: var(--z-mute); background: none; border: 0; font: inherit; cursor: pointer; }+.cluster-ctrl button:hover { color: var(--z-ink); }+.cluster-ctrl button.active { color: var(--z-accent); }++.footer {+ margin-top: var(--sp-12);+ display: flex;+ justify-content: space-between;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ color: var(--z-mute);+ letter-spacing: 0.08em;+ text-transform: uppercase;+}++/* ---- Delta arrows ---------------------------------------- */++.delta {+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-weight: 700;+ font-variant-numeric: tabular-nums;+ letter-spacing: 0;+}+.delta.good { color: var(--z-accent); }+.delta.bad { color: var(--z-ink); }+.delta.meh { color: var(--z-mute); }++/* ---- Text utility ---------------------------------------- */++.u-right { text-align: right; }+.u-mute { color: var(--z-mute); }++/* ---- Recent / event list --------------------------------- */++.events {+ display: flex;+ flex-direction: column;+ gap: 2px;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+}+.events .ev {+ display: grid;+ grid-template-columns: 14ch 8ch 1fr;+ gap: var(--sp-2);+ padding: 3px 0;+ white-space: nowrap;+}+.events .ev .when { color: var(--z-mute); font-size: var(--fs-11); }+.events .ev .sev { font-weight: 700; }+.events .ev .sev.err { color: var(--z-accent); }+.events .ev .msg { overflow: hidden; text-overflow: ellipsis; }++/* ---- Stacked rows ---------------------------------------- */++.stacked { display: flex; flex-direction: column; }+.stk-row {+ display: grid;+ grid-template-columns: 14ch 1fr 10ch;+ gap: var(--sp-2);+ align-items: baseline;+ padding: 5px 0;+ font-family: var(--font-data);+ font-size: var(--fs-13);+}+.stk-bar { width: 100%; }++/* ---- Data table ------------------------------------------ */++.tbl {+ display: flex;+ flex-direction: column;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+}+.tbl-row {+ display: grid;+ grid-template-columns: repeat(var(--tbl-cols, 3), minmax(0, 1fr));+ gap: var(--sp-2);+ padding: 6px 0;+}+.tbl-row.tbl-head {+ color: var(--z-mute);+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ margin-bottom: 6px;+}++/* ---- SearchBox / Hits / Facets / QueryDSL / Plan --------- */++.sbox {+ display: flex;+ flex-direction: column;+ gap: var(--sp-3);+}+.sbox-row {+ display: flex;+ align-items: baseline;+ gap: 6px;+ flex-wrap: wrap;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.sbox-row .spacer { flex: 1; }+.sbox-row .sep { color: var(--z-faint); }+.sbox-row button { color: var(--z-mute); padding: 0 2px; }+.sbox-row button:hover { color: var(--z-ink); }+.sbox-row button.active { color: var(--z-accent); }+.sbox-input {+ font-family: var(--font-data);+ font-size: var(--fs-32);+ letter-spacing: 0;+ text-transform: none;+ gap: var(--sp-2);+ padding-top: var(--sp-2);+}+.sbox-input .prompt { font-weight: 700; }+.sbox-input input {+ flex: 1;+ background: none;+ border: none;+ outline: none;+ color: var(--z-ink);+ font: inherit;+ padding: 0;+ caret-color: var(--z-accent);+ font-variant-numeric: tabular-nums;+}+.sbox-input input::placeholder { color: var(--z-faint); }++/* Hits list */+.hits-meta {+ display: flex;+ align-items: baseline;+ margin-bottom: var(--sp-3);+ gap: var(--sp-2);+}+.hits-meta .hits-action {+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ color: var(--z-mute);+ margin-left: var(--sp-2);+}+.hits-meta .hits-action:hover { color: var(--z-accent); }+.hits-list { display: flex; flex-direction: column; gap: var(--sp-2); }+.hit {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 4px 0;+ font-family: var(--font-data);+ font-size: var(--fs-13);+}+.hit-head {+ display: grid;+ grid-template-columns: 14ch 16ch 8ch 14ch 1fr;+ gap: var(--sp-2);+ font-size: var(--fs-11);+ font-variant-numeric: tabular-nums;+}+.hit-head.no-time { grid-template-columns: 14ch 16ch 8ch 1fr; }+.hit-headrow {+ margin-bottom: 6px;+ padding-bottom: 4px;+ font-family: var(--font-prose);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ color: var(--z-mute);+}+.hit-headrow .col-sort {+ text-align: left;+ color: var(--z-mute);+ font: inherit;+ letter-spacing: inherit;+ text-transform: inherit;+}+.hit-headrow .col-sort:hover { color: var(--z-ink); }+.hit-headrow .col-sort.active { color: var(--z-accent); }+.hit-cell-clickable {+ text-align: left;+ font: inherit;+ color: var(--z-mute);+ padding: 0;+ cursor: pointer;+}+.hit-cell-clickable:hover { color: var(--z-accent); }+.hit-body {+ color: var(--z-ink);+ font-size: var(--fs-13);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* Filter pills inside SearchBox */+.sbox-pills {+ flex-wrap: wrap;+ gap: 6px;+ text-transform: none;+ letter-spacing: 0;+ font-size: var(--fs-13);+}+.sbox-pills .key {+ text-transform: uppercase;+ letter-spacing: var(--track-label);+ font-size: var(--fs-11);+}+.pill {+ font-family: var(--font-data);+ font-size: var(--fs-13);+ color: var(--z-mute);+ padding: 0 4px;+ display: inline-flex;+ align-items: baseline;+ gap: 4px;+}+.pill .pill-field { color: var(--z-mute); }+.pill .pill-eq { color: var(--z-faint); }+.pill .pill-val { color: var(--z-ink); font-weight: 700; }+.pill .pill-x { color: var(--z-mute); margin-left: 4px; font-size: var(--fs-11); }+.pill:hover { color: var(--z-accent); }+.pill:hover .pill-x { color: var(--z-accent); }+.pill-clear {+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ color: var(--z-mute);+ padding: 0 4px;+ margin-left: var(--sp-2);+}+.pill-clear:hover { color: var(--z-accent); }++/* Facet filter rows */+.facet { display: flex; flex-direction: column; gap: 2px; margin-bottom: var(--sp-4); }+.facet-row {+ display: grid;+ grid-template-columns: 1fr 70px 180px;+ gap: var(--sp-2);+ align-items: baseline;+ padding: 4px 0;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ color: var(--z-mute);+ text-align: left;+ font-variant-numeric: tabular-nums;+ text-transform: none;+ letter-spacing: 0;+}+.facet-row:hover { color: var(--z-ink); }+.facet-row.active { color: var(--z-accent); }+.facet-count { text-align: right; }+.facet-bar { width: 100%; }+.facet-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++/* Query DSL block */+.qdsl {+ font-family: var(--font-data);+ font-size: var(--fs-13);+ line-height: 1.55;+ color: var(--z-mute);+ white-space: pre-wrap;+ word-break: break-word;+ margin: 0;+}+.qdsl .tok-key { color: var(--z-mute); }+.qdsl .tok-str { color: var(--z-ink); }+.qdsl .tok-num { color: var(--z-accent); font-weight: 700; }+.qdsl .tok-kw { color: var(--z-accent); }++/* Query plan tree */+.plan-row {+ font-family: var(--font-data);+ font-size: var(--fs-13);+ line-height: 1.55;+ white-space: nowrap;+ font-variant-numeric: tabular-nums;+ padding: 1px 0;+}+.plan-op { font-weight: 700; letter-spacing: 0.04em; }++/* Citations — link panels back to real user feedback artifacts */+.cites { display: flex; flex-direction: column; }+.cite {+ display: grid;+ grid-template-columns: 8ch 6ch 1fr 2ch;+ gap: var(--sp-2);+ align-items: baseline;+ padding: 5px 0;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ color: var(--z-mute);+ text-decoration: none;+ border: none;+}+.cite:hover { color: var(--z-ink); text-decoration: none; }+.cite-src { font-size: var(--fs-11); letter-spacing: 0.08em; }+.cite-score { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }+.cite-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.cite-arrow { text-align: right; }++/* MetricTile dense grid */+.mtiles {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: var(--sp-3) var(--sp-4);+}+.mtile { display: flex; flex-direction: column; gap: 4px; }+.mtile-head { display: flex; justify-content: space-between; align-items: baseline; }+.mtile-val { font-size: var(--fs-20); font-weight: 700; color: var(--z-ink); font-variant-numeric: tabular-nums; }++/* Caption under scene header */+.caption {+ font-family: var(--font-prose);+ font-size: var(--fs-13);+ color: var(--z-mute);+ max-width: 92ch;+ margin-bottom: var(--sp-6);+}++/* Inline-editable scene title (h1.editable in edit mode) */+.h-scene.editable {+ outline: none;+ cursor: text;+ caret-color: var(--z-accent);+}+.h-scene.editable:hover {+ text-shadow: 0 1px 0 var(--z-accent);+}+.h-scene.editable:focus {+ color: var(--z-accent);+}++/* -------- MANAGE view ---------------------------------- */++/* Dashboard list table */+.mg-table {+ display: flex;+ flex-direction: column;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+}+.mg-row {+ display: grid;+ grid-template-columns: 3ch 1fr 10ch 16ch minmax(380px, auto);+ gap: var(--sp-2);+ align-items: baseline;+ padding: 6px 0;+}+.mg-row.mg-head {+ color: var(--z-mute);+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ padding-bottom: 8px;+}+.mg-row[draggable="true"] { cursor: grab; }+.mg-row[draggable="true"]:hover { color: var(--z-ink); }+.mg-row.mg-row-hidden .mg-name { color: var(--z-mute); text-decoration: line-through; text-decoration-thickness: 1px; }+.mg-row .mg-order { color: var(--z-mute); }+.mg-row .mg-name { color: var(--z-ink); font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.mg-row .mg-kind { font-size: var(--fs-11); }+.mg-row .mg-src { font-size: var(--fs-11); color: var(--z-mute); }+.mg-row .mg-actions {+ display: flex;+ gap: 6px;+ justify-content: flex-end;+}++/* Generic small text button used across the MANAGE view */+.mg-btn {+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ color: var(--z-mute);+ padding: 2px 6px;+}+.mg-btn:hover { color: var(--z-ink); }+.mg-btn.mg-btn-danger { color: var(--z-mute); }+.mg-btn.mg-btn-danger:hover { color: var(--z-accent); }+.mg-btn.mg-btn-disabled { color: var(--z-faint); cursor: default; }+.mg-btn.mg-btn-disabled:hover { color: var(--z-faint); }++/* + NEW DASHBOARD row */+.mg-new-row {+ display: flex;+ align-items: baseline;+ gap: 6px;+ flex-wrap: wrap;+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ letter-spacing: var(--track-label);+ text-transform: uppercase;+ padding-top: var(--sp-3);+}+.mg-new-row .sep { color: var(--z-faint); margin: 0 4px; }+.mg-new-row .mg-new-templates { display: inline-flex; gap: 6px; flex-wrap: wrap; }++/* Clusters (cards as text rows, no frames) */+.mg-clusters {+ display: flex;+ flex-direction: column;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+}+.mg-cluster {+ display: grid;+ grid-template-columns: 3ch 14ch minmax(26ch, 1fr) 10ch 14ch 10ch;+ gap: var(--sp-2);+ padding: 6px 0;+ align-items: baseline;+ font: inherit;+ text-align: left;+ color: var(--z-mute);+}+.mg-cluster:hover { color: var(--z-ink); }+.mg-cluster.mg-cluster-active { color: var(--z-ink); }+.mg-cluster.mg-cluster-active .mg-cluster-name { color: var(--z-accent); }++/* Indices + fields sub-tables */+.mg-idx-table, .mg-fld-table {+ display: flex;+ flex-direction: column;+ font-family: var(--font-data);+ font-size: var(--fs-13);+ font-variant-numeric: tabular-nums;+}+.mg-idx-row, .mg-fld-row {+ display: grid;+ gap: var(--sp-2);+ padding: 4px 0;+}+.mg-idx-row { grid-template-columns: minmax(20ch, 1fr) 8ch 10ch 8ch 10ch; }+.mg-idx-head, .mg-fld-head {+ color: var(--z-mute);+ font-family: var(--font-prose);+ font-size: var(--fs-11);+ font-weight: 600;+ letter-spacing: var(--track-label);+ text-transform: uppercase;+}+.mg-fld-row { grid-template-columns: minmax(18ch, 1fr) 8ch 12ch 14ch 6ch; }+.mg-idx-btn {+ text-align: left;+ font: inherit;+ color: var(--z-mute);+ padding: 0;+}+.mg-idx-btn:hover { color: var(--z-ink); }+.mg-idx-btn.active { color: var(--z-accent); }++/* Settings rows */+.mg-settings { display: flex; flex-direction: column; gap: var(--sp-2); font-family: var(--font-data); font-size: var(--fs-13); }+.mg-setting {+ display: grid;+ grid-template-columns: 22ch minmax(20ch, 1fr) 1fr;+ gap: var(--sp-3);+ align-items: baseline;+}+.mg-setting .key { margin: 0; }++/* ---- Edit mode ------------------------------------------- */+/*+ * Edit-mode affordances (dashed outlines, drop guides, handles)+ * are the ONE place in the UX system where we allow decorative+ * 1px lines that are not data. They are transient: visible only+ * while editing, gone the moment you exit edit mode.+ *+ * The "police strip" frame is a fixed-position overlay that lives+ * INSIDE the page's existing 56px y / 64px x margins, so entering+ * edit mode does NOT shift content. Pixel-perfect parity between+ * view and edit mode: the only thing that changes is the frame.+ */++.edit-ctrl {+ display: inline-flex;+ align-items: baseline;+ gap: 8px;+ margin-right: var(--sp-3);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+}+.edit-ctrl .dash { color: var(--z-faint); }+.edit-ctrl button { color: var(--z-mute); }+.edit-ctrl button:hover { color: var(--z-ink); }+.edit-ctrl button.active { color: var(--z-accent); }++/* The 1px dashed accent frame around the viewport edge. */+.edit-frame {+ position: fixed;+ /* Start below the nav + sub-nav so EDIT clearly belongs to the+ dashboard content, not the main menu. 150px covers the primary+ nav row (56..75) + sub-nav (117..137) + a small gap. */+ top: 150px;+ right: 14px;+ bottom: 14px;+ left: 14px;+ border: 1px dashed var(--z-accent);+ pointer-events: none;+ z-index: 50;+}++/* Top strip — EDIT MODE label + drag/resize/remove tips. Lives in the+ page's top padding, never overlaps content. */+.edit-strip-top {+ position: fixed;+ /* Sit just inside the top edge of the .edit-frame (top: 150px). */+ top: 158px;+ left: 28px;+ right: 28px;+ display: flex;+ gap: var(--sp-3);+ align-items: baseline;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+ pointer-events: none;+ z-index: 51;+ padding: 0 8px;+ background: var(--z-paper);+}+.edit-strip-top .marker {+ color: var(--z-accent);+ font-weight: 700;+ letter-spacing: 0.18em;+}+.edit-strip-top .tips {+ color: var(--z-mute);+ flex: 1;+}+.edit-strip-top .tips .key-bind {+ color: var(--z-ink);+}+.edit-strip-top .meta {+ color: var(--z-mute);+}++/* Bottom strip — numbered column header, aligned to the canvas grid so+ you can read which column a panel sits in. */+.edit-strip-bottom {+ position: fixed;+ bottom: 22px;+ left: var(--page-x);+ right: var(--page-x);+ max-width: calc(1680px - var(--page-x) * 2);+ margin: 0 auto;+ display: grid;+ grid-template-columns: repeat(12, 1fr);+ column-gap: var(--gap-x);+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: 0.08em;+ color: var(--z-mute);+ text-transform: uppercase;+ pointer-events: none;+ z-index: 51;+ padding: 4px 8px;+ background: var(--z-paper);+}+.edit-strip-bottom span {+ border-left: 1px solid var(--z-faint);+ padding-left: 6px;+}+.edit-strip-bottom span:last-child {+ border-right: 1px solid var(--z-faint);+ padding-right: 6px;+}++.panel.edit {+ outline: 1px dashed var(--z-mute);+ outline-offset: 10px;+ position: relative;+ z-index: 1;+ transition: outline-color 120ms;+}+.panel.edit:hover { outline-color: var(--z-ink); }+.panel.edit.dragging { opacity: 0.35; }+.panel.edit.drop-before { outline-color: var(--z-accent); }+.panel.edit.drop-after { outline-color: var(--z-accent); }++/* (legacy inline grid header removed; now lives in .edit-strip-bottom) */++/* Full-canvas 12-column overlay inside the grid */+.edit-grid {+ position: absolute;+ inset: 0;+ pointer-events: none;+ display: grid;+ grid-template-columns: repeat(12, 1fr);+ column-gap: var(--gap-x);+ z-index: 0;+}+.edit-grid span {+ border-left: 1px dashed var(--z-faint);+}+.edit-grid span:last-child {+ border-right: 1px dashed var(--z-faint);+}++.panel-edit {+ position: absolute;+ top: -30px;+ left: 0;+ right: 0;+ display: flex;+ gap: var(--sp-3);+ align-items: baseline;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+ z-index: 3;+ pointer-events: none;+}+.panel-edit > * { pointer-events: auto; }+.panel-edit .colsLabel {+ color: var(--z-accent);+ font-weight: 700;+ letter-spacing: 0.1em;+}+.panel-edit .colsLabel .slash { color: var(--z-mute); margin: 0 2px; font-weight: 400; }+.panel-edit .colsLabel .max { color: var(--z-mute); font-weight: 400; }+.panel-edit .meter {+ display: inline-block;+ width: 96px;+ height: 6px;+}+.panel-edit .meter line { vector-effect: non-scaling-stroke; }+.panel-edit .sizes { display: inline-flex; gap: 4px; }+.panel-edit .sizes .sep { color: var(--z-faint); }+.panel-edit .sizes button { color: var(--z-mute); padding: 0 2px; }+.panel-edit .sizes button:hover { color: var(--z-ink); }+.panel-edit .sizes button.active { color: var(--z-accent); font-weight: 700; }+.panel-edit .remove {+ margin-left: auto;+ color: var(--z-mute);+ font-family: var(--font-data);+ font-size: var(--fs-13);+}+.panel-edit .remove:hover { color: var(--z-accent); }++/* The +ADD picker at the bottom of the canvas */+.add-picker {+ margin-top: var(--sp-8);+ display: flex;+ align-items: baseline;+ gap: var(--sp-3);+ flex-wrap: wrap;+ font-family: var(--font-data);+ font-size: var(--fs-11);+ letter-spacing: var(--track-ui);+ text-transform: uppercase;+ padding-top: var(--sp-3);+ border-top: 1px dashed var(--z-faint);+}+.add-picker .types { display: inline-flex; gap: 6px; flex-wrap: wrap; }+.add-picker .types .sep { color: var(--z-faint); }+.add-picker .types button {+ color: var(--z-mute);+ padding: 2px 0;+}+.add-picker .types button:hover { color: var(--z-accent); }++/* ============================================================+ Mobile / tablet responsive rules+ Desktop-first product: the dashboards were designed for wide+ screens. On narrow screens we collapse the 12-col canvas to+ a single column, tighten gutters, and give every wide data+ block its own horizontal scroll so the page never side-scrolls.+ ============================================================ */++@media (max-width: 1100px) {+ :root { --page-x: 40px; --gap-x: 28px; }+ .h-scene { font-size: 64px; }+}++@media (max-width: 900px) {+ :root {+ --page-x: 20px;+ --page-y: 32px;+ --gap-x: 16px;+ --gap-y: 32px;+ }+ html, body { overflow-x: hidden; }++ .h-scene { font-size: 48px; line-height: 0.92; }+ .h-section { font-size: var(--fs-20); }+ .num-big { font-size: var(--fs-32); }+ .num-md { font-size: var(--fs-20); }++ /* Nav wraps to multiple rows. Status hides on tightest width. */+ .nav {+ flex-wrap: wrap;+ row-gap: 8px;+ column-gap: var(--sp-2);+ font-size: 10px;+ letter-spacing: 0.08em;+ }+ .nav .brand { flex: 1 0 100%; font-size: var(--fs-13); margin-right: 0; }+ .nav .spacer { display: none; }+ .nav .status { margin-left: auto; }+ .nav-sub { margin-top: 0; }++ /* Time / refresh / filter rows wrap. */+ .dash-ctrls { gap: var(--sp-3) var(--sp-4); }+ .time, .refresh, .theme { font-size: 10px; }++ /* Canvas collapses from 12 columns to 1. We also need to+ override any inline `grid-column: span N` that the dashboard+ renderer writes per-panel. */+ .canvas {+ grid-template-columns: 1fr;+ column-gap: 0;+ row-gap: var(--sp-6);+ }+ .canvas > * { grid-column: 1 / -1 !important; }+ .canvas.edit { grid-auto-rows: auto; }++ .panel { min-width: 0; max-width: 100%; }++ /* Wide data blocks: scroll inside their panel. */+ .heatmap,+ .multiples,+ .chart,+ .panel svg {+ max-width: 100%;+ }+ .heatmap { overflow-x: auto; -webkit-overflow-scrolling: touch; }+ .multiples { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); }++ /* Top-N row: shorten the bar column so labels + values fit. */+ .row {+ grid-template-columns: 1fr 64px 56px 40px;+ font-size: var(--fs-11);+ gap: 6px;+ }++ /* Add picker wraps neatly. */+ .add-picker { font-size: 10px; }+}++@media (max-width: 480px) {+ :root { --page-x: 14px; }+ .h-scene { font-size: 36px; }+ .nav .status { display: none; }+ .row { grid-template-columns: 1fr 56px 40px; }+ .row .row__bar { display: none; }+}++/* ============================================================+ Mobile preview — iPhone device frame with single-column layout.+ Toggled by the MOBILE button in the nav chrome. The `.mobile-preview`+ class on `<html>` activates everything below.+ ============================================================ */++.mobile-ctrl button {+ font: inherit;+ letter-spacing: inherit;+ text-transform: inherit;+ color: var(--z-mute);+ background: none;+ border: none;+ cursor: pointer;+ padding: 2px 0;+}+.mobile-ctrl button:hover { color: var(--z-ink); }+.mobile-ctrl button.active { color: var(--z-accent); }++/* iPhone 15 Pro frame — realistic proportions and details.+ 393×852 CSS px mapped to a centered fixed-width container.+ The frame is purely decorative (border-radius + shadows). */++.iphone-frame {+ display: none;+}++html.mobile-preview .iphone-frame {+ display: block;+ position: relative;+ width: 393px;+ margin: var(--sp-6) auto var(--sp-8);+ background: #1a1a1a;+ border-radius: 48px;+ padding: 14px;+ box-shadow:+ 0 0 0 2px #333,+ 0 0 0 4px #111,+ 0 20px 60px rgba(0,0,0,0.5);+}++/* Notch / Dynamic Island */+.iphone-notch {+ width: 120px;+ height: 28px;+ background: #1a1a1a;+ border-radius: 14px;+ margin: 0 auto 0;+ position: relative;+ z-index: 10;+}++/* Screen area */+.iphone-screen {+ background: var(--z-paper);+ border-radius: 36px;+ overflow-y: auto;+ overflow-x: hidden;+ height: 760px;+ padding: 8px 16px 16px;+ -webkit-overflow-scrolling: touch;+ scrollbar-width: none;+}+.iphone-screen::-webkit-scrollbar { display: none; }++/* Home bar indicator */+.iphone-home-bar {+ width: 140px;+ height: 5px;+ background: var(--z-mute);+ border-radius: 3px;+ margin: 10px auto 0;+ opacity: 0.5;+}++/* Inside the phone frame — force single-column, scale down type */+html.mobile-preview .iphone-screen .h-scene {+ font-size: 36px;+ line-height: 0.92;+}+html.mobile-preview .iphone-screen .h-section {+ font-size: var(--fs-16);+}+html.mobile-preview .iphone-screen .canvas {+ grid-template-columns: 1fr !important;+ column-gap: 0;+ row-gap: var(--sp-4);+}+html.mobile-preview .iphone-screen .canvas > * {+ grid-column: 1 / -1 !important;+}+html.mobile-preview .iphone-screen .panel {+ min-width: 0;+ max-width: 100%;+}+html.mobile-preview .iphone-screen .num-big {+ font-size: var(--fs-32);+}+html.mobile-preview .iphone-screen .num-md {+ font-size: var(--fs-20);+}+html.mobile-preview .iphone-screen .key {+ font-size: 10px;+}+html.mobile-preview .iphone-screen .hint {+ font-size: 10px;+}+html.mobile-preview .iphone-screen .heatmap {+ overflow-x: auto;+ font-size: 10px;+}+html.mobile-preview .iphone-screen .row {+ grid-template-columns: 1fr 48px 40px;+ font-size: var(--fs-11);+ gap: 4px;+}+html.mobile-preview .iphone-screen .row .row__bar { display: none; }+html.mobile-preview .iphone-screen .multiples {+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+}+html.mobile-preview .iphone-screen .chart {+ max-width: 100%;+}+html.mobile-preview .iphone-screen .series-legend {+ font-size: 9px;+}+html.mobile-preview .iphone-screen .scene {+ margin-bottom: var(--sp-3);+}+html.mobile-preview .iphone-screen .scene .kicker {+ font-size: 9px;+}+html.mobile-preview .iphone-screen .time,+html.mobile-preview .iphone-screen .refresh,+html.mobile-preview .iphone-screen .filter-bar {+ font-size: 9px;+}+html.mobile-preview .iphone-screen .dash-ctrls {+ gap: var(--sp-2);+ flex-wrap: wrap;+}+html.mobile-preview .iphone-screen .dist-legend {+ gap: var(--sp-2) var(--sp-3);+}+html.mobile-preview .iphone-screen .dist-legend > * {+ min-width: 80px;+}++/* Hide nav-sub inside the phone (too wide). Show a compact+ dashboard name instead via the scene header. */+html.mobile-preview .nav-sub {+ display: none;+}++/* Status bar simulation inside the screen */+.iphone-screen::before {+ content: '9:41';+ display: block;+ text-align: center;+ font-family: var(--font-prose);+ font-size: 12px;+ font-weight: 600;+ color: var(--z-ink);+ padding: 4px 0 8px;+ letter-spacing: 0.02em;+}diff --git a/xerj-ux/assets/tokens.css b/xerj-ux/assets/tokens.cssnew file mode 100644index 000000000..a314c3aa5--- /dev/null+++ b/xerj-ux/assets/tokens.css@@ -0,0 +1,67 @@+/* ============================================================+ XERJ.ai — Design tokens+ The complete token list. Do not add new tokens without+ deleting an old one. See UX_BOOK.md §2.+ ============================================================ */++:root {+ /* Color — five values, no more */+ --z-paper: #0D0D0D;+ --z-ink: #E0E0E0;+ --z-mute: #555555;+ --z-faint: #2A2A2A;+ --z-accent: #EEBB00;++ /* Type families */+ --font-display: 'Big Shoulders Display', 'Impact', 'Helvetica Neue Condensed', sans-serif;+ --font-data: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace;+ --font-prose: 'Inter', -apple-system, system-ui, sans-serif;++ /* Type scale — seven sizes, no others */+ --fs-11: 11px;+ --fs-13: 13px;+ --fs-16: 16px;+ --fs-20: 20px;+ --fs-32: 32px;+ --fs-56: 56px;+ --fs-96: 96px;++ /* Spacing (multiples of 8) */+ --sp-1: 8px;+ --sp-2: 16px;+ --sp-3: 24px;+ --sp-4: 32px;+ --sp-6: 48px;+ --sp-8: 64px;+ --sp-12: 96px;++ /* Grid */+ --page-x: 64px;+ --page-y: 56px;+ --gap-y: 56px;+ --gap-x: 40px;++ /* Tracking */+ --track-tight: -0.01em;+ --track-label: 0.18em;+ --track-ui: 0.1em;+}++/* Explicit theme — set via [data-theme] on <html>. Bootstrapped+ synchronously in index.html to avoid FOUC. */+:root[data-theme='night'] {+ --z-paper: #0D0D0D;+ --z-ink: #E0E0E0;+ --z-mute: #555555;+ --z-faint: #2A2A2A;+}+:root[data-theme='day'] {+ --z-paper: #FBFAF6;+ --z-ink: #141414;+ --z-mute: #7A7671;+ --z-faint: #E6E4DC;+ /* Day accent — darker ochre in the same yellow family.+ The night accent (#EEBB00) is 1.7:1 on paper — unreadable.+ #A06800 is 5.7:1, passes AA body text. Same hue family. */+ --z-accent: #A06800;+}diff --git a/xerj-ux/index.html b/xerj-ux/index.htmlnew file mode 100644index 000000000..04e547ab2--- /dev/null+++ b/xerj-ux/index.html@@ -0,0 +1,83 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Xerj Console · typography-first observability for Xerj</title>+<meta name="color-scheme" content="dark light">+<script>+ // Theme bootstrap — runs before CSS to prevent a flash of wrong theme.+ (function () {+ var t = localStorage.getItem('xerj.theme');+ if (t !== 'day' && t !== 'night') t = 'night';+ document.documentElement.setAttribute('data-theme', t);+ })();+</script>+<link rel="preconnect" href="https://fonts.googleapis.com">+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@400;700;800;900&family=JetBrains+Mono:wght@400;500;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">+<link rel="stylesheet" href="assets/tokens.css">+<link rel="stylesheet" href="assets/base.css">+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ctext y='13' font-family='monospace' font-size='14' font-weight='900' fill='%23EEBB00'%3Ez%3C/text%3E%3C/svg%3E">+</head>+<body>+<div id="app" aria-busy="true"></div>+<!--+ Auth guard. Hits /_xerj-console/api/v1/me before app.js runs. On 401 we+ redirect to /_xerj-console/login (or /_xerj-console/setup when this is a fresh+ install — the bootstrap banner already pointed the user at /setup,+ but if they bookmarked / it's nicer to land on /setup than /login).+ On 200 we cache the user record on `window.__xerjConsoleMe` so app.js can+ pick it up synchronously without re-fetching, and import app.js.+-->+<script type="module">+ (async () => {+ try {+ const r = await fetch('/_xerj-console/api/v1/me', {+ credentials: 'same-origin',+ headers: { 'accept': 'application/json' },+ });+ if (r.status === 401) {+ // Decide: setup vs login. We probe /cluster/info — its+ // `started_at_ms` tells us whether the server has been up+ // long enough that someone almost certainly set it up; on a+ // fresh boot we send the user to /setup.+ try {+ const info = await (await fetch('/_xerj-console/api/v1/cluster/info', {+ credentials: 'same-origin',+ })).json();+ // No reliable "is bootstrapped?" probe yet; default to /login+ // since /setup requires a magic-link token in the fragment.+ // Operators on first boot reach /setup via the stderr banner.+ void info;+ } catch {}+ window.location.href = '/_xerj-console/login';+ return;+ }+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const body = await r.json();+ window.__xerjConsoleMe = body && body.data ? body.data.user : null;++ // Pull /prefs + /views from the engine and seed localStorage+ // BEFORE app.js boots — app.js reads localStorage at module-load+ // time, so the pull has to complete first or the SPA renders+ // with stale (or empty) state for one frame.+ try {+ const sync = await import('./src/xerj-console-sync.js');+ await sync.pullAll();+ // Start the periodic push tick once app.js has had a beat.+ Promise.resolve().then(() => sync.startPush());+ } catch (e) {+ console.warn('[xerj-console sync]', e);+ }+ } catch (e) {+ // Engine unreachable (offline dev, hot-reload mid-flight) —+ // load the SPA anyway so the user sees an error state instead+ // of a redirect loop.+ console.error('[xerj-console auth guard]', e);+ }+ await import('./src/app.js');+ })();+</script>+</body>+</html>diff --git a/xerj-ux/login.html b/xerj-ux/login.htmlnew file mode 100644index 000000000..7eefd318c--- /dev/null+++ b/xerj-ux/login.html@@ -0,0 +1,139 @@+<!doctype html>+<html lang="en" data-theme="night">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Xerj Console · sign in</title>+<meta name="color-scheme" content="dark light">+<link rel="preconnect" href="https://fonts.googleapis.com">+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@800;900&family=JetBrains+Mono:wght@400;500&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">+<link rel="stylesheet" href="assets/tokens.css">+<link rel="stylesheet" href="assets/base.css">+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ctext y='13' font-family='monospace' font-size='14' font-weight='900' fill='%23EEBB00'%3Ez%3C/text%3E%3C/svg%3E">+<style>+ body {+ min-height: 100vh; display: flex; align-items: center; justify-content: center;+ padding: 2rem;+ }+ .auth-card {+ background: var(--bg-surface, #15171a);+ border: 1px solid var(--border, #2a2d33);+ border-radius: 8px; padding: 2rem;+ max-width: 420px; width: 100%;+ color: var(--fg, #e6e8eb);+ }+ .auth-card h1 {+ font-family: 'Big Shoulders Display', sans-serif;+ font-weight: 900; font-size: 2.25rem; letter-spacing: -0.02em;+ margin: 0 0 .25rem; color: #EEBB00;+ }+ .auth-card p.lead { color: var(--fg-mute, #8a8e95); margin: 0 0 1.5rem; }+ label { display: block; font-weight: 500; margin: 1rem 0 .25rem; font-size: 0.875rem; }+ input[type="email"] {+ width: 100%; padding: 0.625rem 0.75rem;+ background: var(--bg, #0c0d10);+ border: 1px solid var(--border, #2a2d33);+ border-radius: 4px; color: var(--fg, #e6e8eb);+ font-family: inherit; font-size: 0.9rem;+ }+ input:focus { outline: 2px solid #EEBB00; outline-offset: 1px; }+ button {+ background: #EEBB00; color: #0c0d10;+ border: none; padding: 0.75rem 1.5rem;+ font-weight: 600; border-radius: 4px;+ cursor: pointer; margin-top: 1.5rem;+ font-family: inherit; font-size: 0.9rem;+ width: 100%;+ }+ button:disabled { opacity: 0.5; cursor: not-allowed; }+ .err {+ background: #3a1a1a; color: #ff8a8a;+ padding: 0.75rem 1rem; border-radius: 4px;+ margin: 1rem 0; font-size: 0.875rem;+ font-family: 'JetBrains Mono', monospace;+ }+ .footnote {+ color: var(--fg-mute, #8a8e95);+ font-size: 0.8rem; margin-top: 1.5rem;+ text-align: center;+ }+ .footnote a { color: #EEBB00; text-decoration: none; }+</style>+</head>+<body>+ <div class="auth-card">+ <h1>XERJ CONSOLE</h1>+ <p class="lead">Sign in with your passkey.</p>++ <div id="err" class="err" hidden></div>++ <form id="form" autocomplete="on">+ <label for="email">Email</label>+ <input id="email" type="email" placeholder="[email protected]" required autocomplete="email username webauthn">++ <button type="submit" id="btn">Sign in</button>+ </form>++ <p class="footnote">+ Don't have a passkey yet? <a href="/_xerj-console/setup">Set up</a>.+ </p>+ </div>++<script type="module">+import { beginLogin, finishLogin, b64uToBuf, bufToB64u } from './src/xerj-console-auth.js';++const $err = document.getElementById('err');+const $form = document.getElementById('form');+const $btn = document.getElementById('btn');+const $email = document.getElementById('email');++function showError(msg) {+ $err.textContent = msg; $err.hidden = false;+}++$form.addEventListener('submit', async (ev) => {+ ev.preventDefault();+ $err.hidden = true;+ $btn.disabled = true;+ $btn.textContent = 'Authenticating…';++ try {+ const email = $email.value.trim();+ if (!email) throw new Error('Email is required.');++ const begin = await beginLogin(email);+ const opts = JSON.parse(JSON.stringify(begin.request_options.publicKey));+ opts.challenge = b64uToBuf(opts.challenge);+ if (opts.allowCredentials) {+ for (const c of opts.allowCredentials) c.id = b64uToBuf(c.id);+ }++ const cred = await navigator.credentials.get({ publicKey: opts });+ if (!cred) throw new Error('Browser returned no credential.');++ const ass = cred.response;+ const credPayload = {+ id: cred.id,+ rawId: bufToB64u(cred.rawId),+ type: cred.type,+ response: {+ clientDataJSON: bufToB64u(ass.clientDataJSON),+ authenticatorData: bufToB64u(ass.authenticatorData),+ signature: bufToB64u(ass.signature),+ userHandle: ass.userHandle ? bufToB64u(ass.userHandle) : null,+ },+ extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {},+ };++ await finishLogin(begin.challenge_id, credPayload);+ window.location.href = '/_xerj-console/';+ } catch (e) {+ showError(e.message || String(e));+ $btn.disabled = false;+ $btn.textContent = 'Sign in';+ }+});+</script>+</body>+</html>diff --git a/xerj-ux/setup.html b/xerj-ux/setup.htmlnew file mode 100644index 000000000..ccbb1a158--- /dev/null+++ b/xerj-ux/setup.html@@ -0,0 +1,228 @@+<!doctype html>+<html lang="en" data-theme="night">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Xerj Console · setup</title>+<meta name="color-scheme" content="dark light">+<link rel="preconnect" href="https://fonts.googleapis.com">+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@800;900&family=JetBrains+Mono:wght@400;500&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">+<link rel="stylesheet" href="assets/tokens.css">+<link rel="stylesheet" href="assets/base.css">+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ctext y='13' font-family='monospace' font-size='14' font-weight='900' fill='%23EEBB00'%3Ez%3C/text%3E%3C/svg%3E">+<style>+ body {+ min-height: 100vh; display: flex; align-items: center; justify-content: center;+ padding: 2rem;+ }+ .auth-card {+ background: var(--bg-surface, #15171a);+ border: 1px solid var(--border, #2a2d33);+ border-radius: 8px; padding: 2rem;+ max-width: 480px; width: 100%;+ color: var(--fg, #e6e8eb);+ }+ .auth-card h1 {+ font-family: 'Big Shoulders Display', sans-serif;+ font-weight: 900; font-size: 2.25rem; letter-spacing: -0.02em;+ margin: 0 0 .5rem; color: #EEBB00;+ }+ .auth-card p.lead { color: var(--fg-mute, #8a8e95); margin: 0 0 1.5rem; }+ .step { display: none; }+ .step.active { display: block; }+ label { display: block; font-weight: 500; margin: 1rem 0 .25rem; font-size: 0.875rem; }+ input[type="email"], input[type="text"] {+ width: 100%; padding: 0.625rem 0.75rem;+ background: var(--bg, #0c0d10);+ border: 1px solid var(--border, #2a2d33);+ border-radius: 4px; color: var(--fg, #e6e8eb);+ font-family: inherit; font-size: 0.9rem;+ }+ input:focus { outline: 2px solid #EEBB00; outline-offset: 1px; }+ button {+ background: #EEBB00; color: #0c0d10;+ border: none; padding: 0.75rem 1.5rem;+ font-weight: 600; border-radius: 4px;+ cursor: pointer; margin-top: 1.5rem;+ font-family: inherit; font-size: 0.9rem;+ }+ button:disabled { opacity: 0.5; cursor: not-allowed; }+ button.secondary { background: transparent; color: var(--fg-mute); border: 1px solid var(--border); }+ .err {+ background: #3a1a1a; color: #ff8a8a;+ padding: 0.75rem 1rem; border-radius: 4px;+ margin: 1rem 0; font-size: 0.875rem;+ font-family: 'JetBrains Mono', monospace;+ }+ .ok {+ background: #1a3a1f; color: #8aff9c;+ padding: 0.75rem 1rem; border-radius: 4px;+ margin: 1rem 0; font-size: 0.875rem;+ }+ .role {+ display: inline-block;+ background: #EEBB00; color: #0c0d10;+ padding: 0.125rem 0.5rem;+ border-radius: 3px; font-size: 0.75rem;+ font-weight: 700; letter-spacing: 0.05em;+ text-transform: uppercase;+ }+</style>+</head>+<body>+ <div class="auth-card">+ <h1>XERJ CONSOLE</h1>+ <p class="lead">First-launch setup — claim this server by enrolling a passkey.</p>++ <div id="err" class="err" hidden></div>+ <div id="ok" class="ok" hidden></div>++ <!-- Step 1: collect email + display name (token already in URL fragment) -->+ <div id="step-info" class="step active">+ <p>You're claiming the role <span class="role" id="role-pill">owner</span> on this server.</p>+ <label for="email">Email</label>+ <input id="email" type="email" placeholder="[email protected]" required autocomplete="email">++ <label for="display">Display name</label>+ <input id="display" type="text" placeholder="Your name" autocomplete="name">++ <label for="pkname">Passkey name (visible to you only)</label>+ <input id="pkname" type="text" value="My main key" autocomplete="off">++ <button id="btn-enrol">Enrol passkey</button>+ </div>++ <!-- Step 2: in-flight WebAuthn ceremony -->+ <div id="step-touch" class="step">+ <p style="font-size: 1.05rem;">Touch your security key, biometric sensor, or platform passkey now…</p>+ <p class="lead" style="margin-top: 1rem;">If your browser didn't prompt automatically, click <em>Try again</em>.</p>+ <button id="btn-retry" class="secondary">Try again</button>+ </div>++ <!-- Step 3: done -->+ <div id="step-done" class="step">+ <p style="font-size: 1.05rem; color: #8aff9c;">✓ Passkey enrolled. Logging you in…</p>+ </div>+ </div>++<script type="module">+import { redeemMagic, beginEnrol, finishEnrol, b64uToBuf, bufToB64u } from './src/xerj-console-auth.js';++const $err = document.getElementById('err');+const $ok = document.getElementById('ok');+const $rolePill = document.getElementById('role-pill');+const $email = document.getElementById('email');+const $display = document.getElementById('display');+const $pkname = document.getElementById('pkname');+const $btnEnrol = document.getElementById('btn-enrol');+const $btnRetry = document.getElementById('btn-retry');++function showStep(id) {+ for (const el of document.querySelectorAll('.step')) el.classList.remove('active');+ document.getElementById(id).classList.add('active');+}+function showError(msg) {+ $err.textContent = msg; $err.hidden = false;+ $ok.hidden = true;+}+function showOk(msg) {+ $ok.textContent = msg; $ok.hidden = false;+ $err.hidden = true;+}++// Pull token from URL fragment (#token=...). Hide it from history immediately.+function tokenFromHash() {+ const frag = window.location.hash.replace(/^#/, '');+ const params = new URLSearchParams(frag);+ return params.get('token');+}+function clearHash() {+ history.replaceState(null, '', window.location.pathname + window.location.search);+}++const token = tokenFromHash();+if (!token) {+ showError('No magic-link token in URL. The link must include #token=…');+ $btnEnrol.disabled = true;+}++// Eagerly redeem the token on page load — it's single-use; we want+// to consume it before the user does anything else.+let enrollmentSession = null;+(async () => {+ if (!token) return;+ try {+ enrollmentSession = await redeemMagic(token);+ clearHash();+ if (enrollmentSession.role) $rolePill.textContent = enrollmentSession.role;+ if (enrollmentSession.email) $email.value = enrollmentSession.email;+ } catch (e) {+ showError('Could not redeem link: ' + e.message);+ $btnEnrol.disabled = true;+ }+})();++async function enrol() {+ $err.hidden = true;+ if (!enrollmentSession) {+ showError('Enrollment session missing — reload from the magic link.');+ return;+ }+ const email = $email.value.trim();+ const display = $display.value.trim() || email;+ const pkname = $pkname.value.trim() || 'default';+ if (!email) {+ showError('Email is required.');+ return;+ }++ showStep('step-touch');++ try {+ const begin = await beginEnrol(enrollmentSession.enrollment_session_id, email, display);+ // Decode WebAuthn binary fields from base64url to ArrayBuffer.+ const opts = JSON.parse(JSON.stringify(begin.creation_options.publicKey));+ opts.challenge = b64uToBuf(opts.challenge);+ opts.user.id = b64uToBuf(opts.user.id);+ if (opts.excludeCredentials) {+ for (const c of opts.excludeCredentials) c.id = b64uToBuf(c.id);+ }++ const cred = await navigator.credentials.create({ publicKey: opts });+ if (!cred) throw new Error('Browser returned no credential.');++ // Re-encode the credential response for transport.+ const att = cred.response;+ const credPayload = {+ id: cred.id,+ rawId: bufToB64u(cred.rawId),+ type: cred.type,+ response: {+ clientDataJSON: bufToB64u(att.clientDataJSON),+ attestationObject: bufToB64u(att.attestationObject),+ },+ extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {},+ };++ await finishEnrol(+ enrollmentSession.enrollment_session_id,+ begin.challenge_id,+ credPayload,+ pkname, email, display+ );++ showStep('step-done');+ showOk('Enrolled. Redirecting…');+ setTimeout(() => { window.location.href = '/_xerj-console/'; }, 800);+ } catch (e) {+ showStep('step-info');+ showError(e.message || String(e));+ }+}++$btnEnrol.addEventListener('click', enrol);+$btnRetry.addEventListener('click', () => { showStep('step-info'); });+</script>+</body>+</html>diff --git a/xerj-ux/src/app.js b/xerj-ux/src/app.jsnew file mode 100644index 000000000..73c533064--- /dev/null+++ b/xerj-ux/src/app.js@@ -0,0 +1,1363 @@+// ============================================================+// XERJ.ai — Bootstrap + router + layout engine+//+// One render loop. Edit mode layers drag/resize/remove/add on+// top of the same render — no separate editor routes.+// ============================================================++import { registry, defaults, SECTIONS, DASHBOARD_GROUPS, dashboardsInSection } from './dashboards/registry.js';+import { Nav, SceneHeader, TimeCtrl, RefreshCtrl, FilterBar, ClusterCtrl, SavedViews, Footer, MobileCtrl } from './ux/chrome.js';+import { query, dataSourceStatus } from './data/query.js';+import { chartTypes, chartTypeList } from './ux/chart-types.js';+import { esc } from './ux/text.js';+import { mockSearch } from './data/mock.js';+import { hitsToCsv, downloadText, svgToPng } from './data/export.js';+import {+ mergedDashboards, renameDashboard, reorderDashboards, setHidden,+ createUserDashboard, deleteUserDashboard, isUserDash, resetAll as resetDashboards,+} from './data/dashboard-store.js';+import {+ listClusters, listIndices, listFields, listClustersSync,+ defaultClusterId, setDefaultCluster,+} from './data/data-sources.js';++// ---------- state -----------------------------------------+const LS = {+ theme: 'xerj.theme',+ time: 'xerj.time',+ edit: 'xerj.edit',+ search: 'xerj.search',+ refresh: 'xerj.refresh',+ cluster: 'xerj.cluster',+ views: 'xerj.views',+ filters: (dashId) => 'xerj.filters.' + dashId,+ layout: (dashId) => 'xerj.layout.' + dashId,+};++function loadJSON(key, fallback) {+ try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : fallback; }+ catch { return fallback; }+}+function loadSearch() { return loadJSON(LS.search, null); }+function loadAllFilters() {+ const out = {};+ for (const k of Object.keys(localStorage)) {+ if (k.startsWith('xerj.filters.')) {+ const id = k.slice('xerj.filters.'.length);+ try { out[id] = JSON.parse(localStorage.getItem(k)) || {}; } catch {}+ }+ }+ return out;+}++const _initial = parseRoute();+const _urlState = parseUrlState();+const state = {+ section: _initial.section,+ route: _initial.route,+ time: _urlState.time || localStorage.getItem(LS.time) || '24H',+ timeCustom: {+ from: _urlState.tfrom || localStorage.getItem('xerj.timeFrom') || '',+ to: _urlState.tto || localStorage.getItem('xerj.timeTo') || '',+ },+ cluster: _urlState.cluster || defaultClusterId(),+ refresh: parseInt(localStorage.getItem(LS.refresh) || '0', 10), // ms; 0 = off+ refreshTimer: null,+ fetchedAt: null, // ISO string of last successful query+ fetchMs: null, // last fetch duration in ms+ fetchErr: null, // last fetch error message+ loading: false,+ filters: loadAllFilters(), // { [dashId]: { field: value } }+ theme: document.documentElement.getAttribute('data-theme') || 'night',+ edit: localStorage.getItem(LS.edit) === '1',+ mobile: localStorage.getItem('xerj.mobile') === '1',+ layouts: loadAllLayouts(),+ search: (() => {+ const loaded = loadSearch() || {};+ return {+ q: loaded.q || '',+ type: loaded.type || 'match',+ index: loaded.index || '*',+ filters: loaded.filters || {},+ sort: loaded.sort || { field: '_score', dir: 'desc' },+ showTime: loaded.showTime !== false,+ result: null,+ };+ })(),+ _focusSelector: null, // set by handlers that need focus restored+};+// Merge any URL-seeded filters into the current dashboard's filter set.+if (_urlState.filters) {+ state.filters[_initial.route] = { ...(state.filters[_initial.route] || {}), ..._urlState.filters };+ saveFilters(_initial.route);+}++// ---------- filters, URL state, refresh -------------------+function currentFilters() {+ return state.filters[state.route] || {};+}+function saveFilters(dashId) {+ const v = state.filters[dashId];+ if (v && Object.keys(v).length) localStorage.setItem(LS.filters(dashId), JSON.stringify(v));+ else localStorage.removeItem(LS.filters(dashId));+}+// Toggle a filter value. Multi-value semantics: clicking the same+// value twice removes it; clicking a new value on an existing field+// appends to the OR list.+function setFilter(field, value) {+ const dashId = state.route;+ const cur = { ...(state.filters[dashId] || {}) };+ const existing = cur[field];+ if (existing == null) {+ cur[field] = value;+ } else if (Array.isArray(existing)) {+ const idx = existing.indexOf(value);+ if (idx >= 0) {+ const next = existing.filter((v) => v !== value);+ if (next.length === 0) delete cur[field];+ else if (next.length === 1) cur[field] = next[0];+ else cur[field] = next;+ } else {+ cur[field] = [...existing, value];+ }+ } else {+ if (existing === value) delete cur[field];+ else cur[field] = [existing, value];+ }+ state.filters[dashId] = cur;+ saveFilters(dashId);+ writeUrlState();+}++// Remove one value from a field (used by pill ✕ click on a specific+// chip inside a multi-value filter).+function removeFilterValue(field, value) {+ const dashId = state.route;+ const cur = { ...(state.filters[dashId] || {}) };+ const existing = cur[field];+ if (existing == null) return;+ if (Array.isArray(existing)) {+ const next = existing.filter((v) => v !== value);+ if (next.length === 0) delete cur[field];+ else if (next.length === 1) cur[field] = next[0];+ else cur[field] = next;+ } else if (existing === value) {+ delete cur[field];+ }+ state.filters[dashId] = cur;+ saveFilters(dashId);+ writeUrlState();+}++// KQL-lite parser: tokenize `field:value field:"multi word" foo`.+// Free-text tokens become a synthetic `q` filter; repeat fields+// turn into OR arrays.+function parseKql(text) {+ const out = {};+ const add = (k, v) => {+ if (!v) return;+ if (out[k] == null) out[k] = v;+ else if (Array.isArray(out[k])) out[k].push(v);+ else out[k] = [out[k], v];+ };+ // Match field:"quoted value" OR field:value OR loose token+ const re = /([a-zA-Z_][\w.]*):"([^"]*)"|([a-zA-Z_][\w.]*):(\S+)|"([^"]+)"|(\S+)/g;+ let m;+ while ((m = re.exec(text)) !== null) {+ if (m[1] != null) add(m[1], m[2]);+ else if (m[3] != null) add(m[3], m[4]);+ else if (m[5] != null) add('q', m[5]);+ else if (m[6] != null) add('q', m[6]);+ }+ return out;+}++// Inverse of parseKql — render a filter object as a KQL string that+// re-parses to the same shape. Used to keep the input box in sync.+function serializeKql(filters) {+ const parts = [];+ for (const [k, v] of Object.entries(filters || {})) {+ const values = Array.isArray(v) ? v : [v];+ for (const x of values) {+ const needsQuote = /\s/.test(String(x));+ if (k === 'q') {+ parts.push(needsQuote ? `"${x}"` : String(x));+ } else {+ parts.push(needsQuote ? `${k}:"${x}"` : `${k}:${x}`);+ }+ }+ }+ return parts.join(' ');+}++function applyKqlInput(text) {+ const dashId = state.route;+ state.filters[dashId] = parseKql(text);+ saveFilters(dashId);+ writeUrlState();+}+function clearFilters() {+ const dashId = state.route;+ state.filters[dashId] = {};+ saveFilters(dashId);+ writeUrlState();+}++// URL state: ?t=24H&f=service:auth,level:error&c=prod-us+// Filters are encoded as repeated `f` params so URLSearchParams can+// handle escaping cleanly: ?f=service:nginx&f=level:error. Multi-value+// (OR) filters repeat the same key: ?f=service:auth&f=service:web.+function parseUrlState() {+ const qs = location.search.slice(1);+ if (!qs) return {};+ const out = {};+ const params = new URLSearchParams(qs);+ if (params.get('t')) out.time = params.get('t').toUpperCase();+ if (params.get('tfrom')) out.tfrom = params.get('tfrom');+ if (params.get('tto')) out.tto = params.get('tto');+ if (params.get('c')) out.cluster = params.get('c');+ const all = params.getAll('f');+ if (all.length) {+ out.filters = {};+ for (const pair of all) {+ const idx = pair.indexOf(':');+ if (idx > 0) {+ const k = pair.slice(0, idx);+ const v = pair.slice(idx + 1);+ const existing = out.filters[k];+ if (existing == null) out.filters[k] = v;+ else if (Array.isArray(existing)) existing.push(v);+ else out.filters[k] = [existing, v];+ }+ }+ }+ return out;+}+function writeUrlState() {+ const params = new URLSearchParams();+ if (state.time && state.time !== '24H') params.set('t', state.time);+ if (state.time === 'CUSTOM' && state.timeCustom) {+ if (state.timeCustom.from) params.set('tfrom', state.timeCustom.from);+ if (state.timeCustom.to) params.set('tto', state.timeCustom.to);+ }+ if (state.cluster) params.set('c', state.cluster);+ for (const [k, v] of Object.entries(currentFilters())) {+ if (Array.isArray(v)) for (const x of v) params.append('f', `${k}:${x}`);+ else params.append('f', `${k}:${v}`);+ }+ const qs = params.toString();+ const url = location.pathname + (qs ? '?' + qs : '') + location.hash;+ history.replaceState(null, '', url);+}++function setRefreshInterval(ms) {+ state.refresh = ms;+ localStorage.setItem(LS.refresh, String(ms));+ if (state.refreshTimer) { clearInterval(state.refreshTimer); state.refreshTimer = null; }+ if (ms > 0) {+ state.refreshTimer = setInterval(() => {+ if (state.section === 'dashboards' || state.section === 'discover') render();+ }, ms);+ }+}++// ---------- saved views -----------------------------------+// A saved view is a snapshot of (dashId, time, cluster, filters).+// Click it to land on that dashboard with the same context.+function loadViews() { return loadJSON(LS.views, []); }+function saveViews(views) { localStorage.setItem(LS.views, JSON.stringify(views)); }+function saveCurrentView() {+ const dashId = state.route;+ const all = loadViews();+ const name = prompt('Save view as:', 'View ' + (all.length + 1));+ if (!name) return;+ const id = 'v-' + Date.now().toString(36);+ all.push({+ id,+ name,+ dashId,+ time: state.time,+ cluster: state.cluster,+ filters: currentFilters(),+ savedAt: new Date().toISOString(),+ });+ saveViews(all);+}+function deleteView(id) {+ saveViews(loadViews().filter((v) => v.id !== id));+}+function applyView(id) {+ const v = loadViews().find((x) => x.id === id);+ if (!v) return;+ state.time = v.time;+ state.cluster = v.cluster || state.cluster;+ state.filters[v.dashId] = { ...(v.filters || {}) };+ saveFilters(v.dashId);+ localStorage.setItem(LS.time, state.time);+ location.hash = '#/dashboards/' + v.dashId;+}++function relTime(iso) {+ if (!iso) return '';+ const delta = Date.now() - new Date(iso).getTime();+ if (delta < 2000) return 'just now';+ if (delta < 60_000) return Math.round(delta / 1000) + 's ago';+ if (delta < 3600_000) return Math.round(delta / 60_000) + 'm ago';+ return Math.round(delta / 3600_000) + 'h ago';+}++function navStatus() {+ if (state.loading) return 'LOADING…';+ if (state.fetchErr) return 'ERROR · ' + state.fetchErr.slice(0, 40);+ const bits = [];+ // dataSourceStatus is a function in v0.7+ (was a const string) so+ // the nav reflects the live backend state instead of a fixed label.+ bits.push(typeof dataSourceStatus === 'function' ? dataSourceStatus() : String(dataSourceStatus));+ if (state.fetchedAt) bits.push('UPDATED ' + relTime(state.fetchedAt).toUpperCase());+ if (state.fetchMs != null) bits.push(state.fetchMs + 'MS');+ return bits.join(' · ');+}++function runSearchNow() {+ // Optimistic placeholder so the table doesn't blank out while+ // the live query is in flight. Replaced as soon as the engine+ // responds with real hits.+ state.search.result = mockSearch({+ q: state.search.q,+ type: state.search.type,+ index: state.search.index,+ filters: state.search.filters,+ sort: state.search.sort,+ });+ // Live xerj search: turn the SearchBox state into a real+ // `query()` ctx and overlay the live hits + facets when they+ // arrive. Falls back to the mock above on backend error so the+ // demo never serves a blank console.+ query({+ dashId: 'search-discover',+ range: state.time,+ customRange: state.time === 'CUSTOM' ? state.timeCustom : null,+ cluster: state.cluster,+ filters: state.search.filters,+ search: {+ q: state.search.q,+ type: state.search.type,+ index: state.search.index,+ },+ })+ .then((res) => {+ const live = res?.data;+ if (!live || live.error) return;+ const mock = state.search.result || {};+ state.search.result = {+ ...mock,+ hits: live.hits || mock.hits || [],+ total: live.total ?? (live.hits?.length ?? 0),+ took: live.took,+ max_score: live.max_score,+ facets: live.facets || mock.facets,+ _live: true,+ };+ state.fetchedAt = res.meta?.fetchedAt || Date.now();+ state.fetchMs = res.meta?.durationMs ?? state.fetchMs;+ // Re-render the page so the table swaps mock → live without+ // requiring user interaction.+ if (state.section === 'discover') render();+ })+ .catch(() => { /* leave the optimistic mock in place */ });+ // Persist the inputs (not the result — it rebuilds on demand)+ localStorage.setItem(LS.search, JSON.stringify({+ q: state.search.q,+ type: state.search.type,+ index: state.search.index,+ filters: state.search.filters,+ sort: state.search.sort,+ showTime: state.search.showTime,+ }));+}++/**+ * Parse the hash into { section, route }. Routes come in three shapes:+ *+ * #/ → section=dashboards, route=<first dashboard>+ * #/dashboards → section=dashboards, route=<first dashboard>+ * #/dashboards/:id → section=dashboards, route=:id+ * #/<section> → section=<section>, route=<view id for that section>+ *+ * Backward compat: legacy `#/ai-overview` (bare dashboard id) gets+ * auto-routed into `#/dashboards/ai-overview`, and legacy `#/manage`+ * redirects to `#/settings`.+ */+function parseRoute() {+ const raw = (location.hash || '').replace(/^#\/?/, '');+ const parts = raw.split('/').filter(Boolean);+ const merged = mergedDashboards(defaults, { includeHidden: true });++ // Helper: find the default view id for a section.+ const firstOfSection = (sectionId) => {+ const list = dashboardsInSection(sectionId, merged);+ return list[0]?.id;+ };++ // Empty hash → dashboards section, first dashboard+ if (!parts.length) {+ const first = firstOfSection('dashboards') || 'ai-overview';+ return { section: 'dashboards', route: first };+ }++ // Legacy: #/manage → settings+ if (parts[0] === 'manage') return { section: 'settings', route: 'settings' };++ // Section-level route: #/section or #/section/:id+ const sectionIds = new Set(SECTIONS.map((s) => s.id));+ if (sectionIds.has(parts[0])) {+ if (parts[0] === 'dashboards') {+ const id = parts[1] || firstOfSection('dashboards') || 'ai-overview';+ // Only accept real dashboards in this section+ const known = merged.find((d) => d.id === id && (d.section || 'dashboards') === 'dashboards');+ if (known) return { section: 'dashboards', route: id };+ return { section: 'dashboards', route: firstOfSection('dashboards') || 'ai-overview' };+ }+ // Non-dashboards sections have exactly one view: firstOfSection+ const first = firstOfSection(parts[0]);+ if (first) return { section: parts[0], route: first };+ }++ // Legacy bare route: #/ai-overview → #/dashboards/ai-overview+ if (merged.some((d) => d.id === parts[0])) {+ const d = merged.find((x) => x.id === parts[0]);+ const section = d.section || 'dashboards';+ return { section, route: parts[0] };+ }++ // Fallback+ return { section: 'dashboards', route: firstOfSection('dashboards') || 'ai-overview' };+}++// Build the data context that the section views (DATA / SETTINGS)+// need. Async because real API calls will replace these mocks in one+// step once the engine ships /v1/clusters etc.+async function buildSectionData(sectionId) {+ if (sectionId === 'data') {+ const clusters = await listClusters();+ const indicesByCluster = {};+ const fieldsByIndex = {};+ for (const c of clusters) {+ indicesByCluster[c.id] = await listIndices(c.id);+ }+ const active = defaultClusterId();+ for (const i of indicesByCluster[active] || []) {+ fieldsByIndex[i.name] = await listFields(i.name);+ }+ return {+ clusters,+ indicesByCluster,+ fieldsByIndex,+ activeCluster: active,+ focusIndex: state._focusIndex || (indicesByCluster[active] || [])[0]?.name,+ };+ }+ if (sectionId === 'settings') {+ return {+ dashboards: mergedDashboards(defaults, { includeHidden: true }),+ views: loadViews(),+ };+ }+ return {};+}++function loadAllLayouts() {+ const out = {};+ for (const id of Object.keys(registry)) {+ try {+ const raw = localStorage.getItem(LS.layout(id));+ if (raw) out[id] = JSON.parse(raw);+ } catch { /* ignore corrupt */ }+ }+ return out;+}+function saveLayout(dashId) {+ const v = state.layouts[dashId];+ if (!v) localStorage.removeItem(LS.layout(dashId));+ else localStorage.setItem(LS.layout(dashId), JSON.stringify(v));+}+function applyTheme(t) {+ state.theme = t;+ document.documentElement.setAttribute('data-theme', t);+ localStorage.setItem(LS.theme, t);+}++// ---------- layout engine ---------------------------------+/**+ * Merge a dashboard's default panels with the user's stored override.+ * Returns a flat ordered array of panel objects ready to render.+ */+function mergeLayout(defaultPanels, override) {+ if (!override) return defaultPanels.map((p) => ({ ...p, source: 'default' }));+ const byId = Object.fromEntries(defaultPanels.map((p) => [p.id, p]));+ const hidden = new Set(override.hidden || []);+ const out = [];+ const seen = new Set();++ const order = override.order || defaultPanels.map((p) => p.id);+ for (const id of order) {+ if (hidden.has(id)) { seen.add(id); continue; }+ const base = byId[id];+ if (base) {+ const cols = override.cols?.[id] ?? base.cols;+ out.push({ ...base, cols, source: 'default' });+ seen.add(id);+ } else {+ // Maybe a user-added panel.+ const added = (override.added || []).find((a) => a.id === id);+ if (added) {+ const cols = override.cols?.[id] ?? added.cols;+ out.push({ ...added, cols, source: 'added' });+ seen.add(id);+ }+ }+ }+ // Append defaults missing from order (new panels added since override was saved).+ for (const p of defaultPanels) {+ if (!seen.has(p.id) && !hidden.has(p.id)) {+ const cols = override.cols?.[p.id] ?? p.cols;+ out.push({ ...p, cols, source: 'default' });+ }+ }+ // Append user-added panels missing from order (freshly added).+ for (const added of (override.added || [])) {+ if (!seen.has(added.id)) {+ const cols = override.cols?.[added.id] ?? added.cols;+ out.push({ ...added, cols, source: 'added' });+ }+ }+ return out;+}++function ensureOverride(dashId, defaultPanels) {+ if (state.layouts[dashId]) return state.layouts[dashId];+ const fresh = {+ order: defaultPanels.map((p) => p.id),+ cols: {},+ hidden: [],+ added: [],+ };+ state.layouts[dashId] = fresh;+ return fresh;+}++function mutate(dashId, defaultPanels, fn) {+ const ov = ensureOverride(dashId, defaultPanels);+ fn(ov);+ saveLayout(dashId);+}++// ---------- render ----------------------------------------+const SIZES = [2, 3, 4, 6, 8, 12];++function renderEditChrome(p) {+ const sizes = SIZES.map((s) =>+ `<button type="button" data-panel="${esc(p.id)}" data-size="${s}" class="${p.cols === s ? 'active' : ''}" aria-pressed="${p.cols === s}">${s}</button>`+ ).join('<span class="sep">·</span>');+ const frac = Math.max(0, Math.min(12, p.cols)) / 12;+ const meterFill = (frac * 96).toFixed(1);+ const meter = `+ <svg class="meter" viewBox="0 0 96 6" preserveAspectRatio="none" aria-hidden="true">+ <line x1="0" y1="5" x2="96" y2="5" stroke="currentColor" stroke-width="1" stroke-opacity="0.25"/>+ <line x1="0" y1="5" x2="${meterFill}" y2="5" stroke="var(--z-accent)" stroke-width="1"/>+ </svg>`;+ return `+ <div class="panel-edit" aria-label="Edit panel">+ <span class="colsLabel"><span class="max">COL</span> ${p.cols}<span class="slash">/</span><span class="max">12</span></span>+ ${meter}+ <span class="sizes">${sizes}</span>+ <button type="button" class="remove" data-panel="${esc(p.id)}" data-remove aria-label="Remove">✕</button>+ </div>`;+}++function renderPanel(p, data, editMode) {+ let inner = '';+ try {+ if (p.source === 'added') {+ const t = chartTypes[p.type] || chartTypes.markdown;+ inner = t.render(data);+ } else if (typeof p.render === 'function') {+ inner = p.render({ data });+ } else {+ inner = '';+ }+ // Empty-state fallback: if the render produced nothing meaningful,+ // show a typography-first placeholder so users see WHY the slot is+ // blank (e.g. filtered everything out) rather than a broken panel.+ const stripped = String(inner || '').replace(/<[^>]+>/g, '').trim();+ if (!stripped) {+ inner = `<div class="panel-empty mono faint">NO DATA · ADJUST FILTERS OR TIME RANGE</div>`;+ }+ } catch (err) {+ inner = `<div class="panel-empty mono faint">PANEL ERROR · ${esc((err.message || err) + '').slice(0, 80)}</div>`;+ }+ const editAttrs = editMode ? ' draggable="true"' : '';+ const editChrome = editMode ? renderEditChrome(p) : '';+ // A panel that declares `drilldown: { to: <dashId> }` adds a+ // data attribute the global click handler uses to route clicks+ // to the target dashboard with the clicked filter preserved.+ const drillAttr = p.drilldown?.to ? ` data-drilldown-to="${esc(p.drilldown.to)}"` : '';+ const drillHint = p.drilldown?.to ? `<span class="drill-hint mono faint">→ ${esc(p.drilldown.to.toUpperCase())}</span>` : '';+ return `+ <section class="panel${editMode ? ' edit' : ''}" data-panel="${esc(p.id)}" style="grid-column: span ${p.cols};"${editAttrs}${drillAttr}>+ ${editChrome}+ ${p.eyebrow ? `<div class="key">${esc(p.eyebrow)}${drillHint}</div>` : ''}+ ${inner}+ </section>`;+}++function renderAddPicker() {+ const items = chartTypeList.map((t) =>+ `<button type="button" data-add="${esc(t.id)}" title="${esc(t.describe || '')}">${esc(t.name)}</button>`+ ).join('<span class="sep">·</span>');+ return `+ <div class="add-picker">+ <span class="key" style="color:var(--z-accent);">+ ADD PANEL</span>+ <span class="types">${items}</span>+ </div>`;+}++async function render() {+ const app = document.getElementById('app');+ // Resolve the active dashboard from either the default registry or+ // the user metadata store. User-cloned dashboards inherit their+ // render from their clonedFrom template.+ const allDash = mergedDashboards(defaults, { includeHidden: true });+ const dash = allDash.find((d) => d.id === state.route)+ || dashboardsInSection(state.section, allDash)[0]+ || registry['ai-overview'];+ const navDash = mergedDashboards(defaults);+ const dashboardsForSection = dashboardsInSection('dashboards', navDash);++ // For the SEARCH dashboard, eagerly run the search so panels see hits.+ if (dash.id === 'search-discover' && !state.search.result) {+ runSearchNow();+ }++ const activeFilters = currentFilters();+ let data;+ let fetchErr = null;+ // Section-level views (data/settings/users/alerts) get their own+ // context builder. Everything else goes through the regular query.+ if (state.section === 'data' || state.section === 'settings') {+ try {+ data = await buildSectionData(state.section);+ } catch (err) {+ data = {};+ fetchErr = err;+ }+ } else {+ state.loading = true;+ try {+ const result = await query({+ dashId: dash.id,+ range: state.time,+ customRange: state.time === 'CUSTOM' ? state.timeCustom : null,+ cluster: state.cluster,+ filters: activeFilters,+ });+ data = result.data;+ state.fetchedAt = result.meta.fetchedAt;+ state.fetchMs = result.meta.durationMs;+ state.fetchErr = null;+ } catch (err) {+ state.fetchErr = err.message || String(err);+ fetchErr = err;+ } finally {+ state.loading = false;+ }+ if (fetchErr) {+ app.innerHTML = `+ ${Nav({ sections: SECTIONS, activeSection: state.section, dashboards: dashboardsForSection, groups: DASHBOARD_GROUPS, activeDash: dash.id, theme: state.theme, edit: state.edit, status: navStatus() })}+ <div class="scene"><div class="key" style="margin-bottom:12px;">ERROR</div><h1 class="h-scene">CANNOT LOAD</h1></div>+ <pre class="mono faint" style="white-space:pre-wrap; font-size:var(--fs-13);">${esc((fetchErr && fetchErr.stack) || fetchErr)}</pre>+ <div style="margin-top:var(--sp-6);"><button type="button" data-retry class="text-btn">RETRY</button></div>`;+ return;+ }+ }++ const view = dash.render({ data, time: state.time, search: state.search });+ // Let a user rename override the scene title. User-cloned dashboards+ // always use the user-chosen name; defaults only override if the user+ // has explicitly set an xerj.dashboards.names entry.+ try {+ const store = JSON.parse(localStorage.getItem('xerj.dashboards') || '{}');+ if (dash.isUser || (store.names && store.names[dash.id])) {+ view.title = (dash.name || view.title || '').toUpperCase();+ }+ } catch {}+ const merged = mergeLayout(view.panels, state.layouts[dash.id]);+ const panelsHtml = merged.length+ ? merged.map((p) => renderPanel(p, data, state.edit)).join('')+ : `<div class="mono faint" style="grid-column: span 12; padding:var(--sp-6) 0;">All panels hidden. Click RESET to restore defaults.</div>`;++ // Police-strip frame: a fixed-position overlay that lives in the page's+ // existing margins, so entering edit mode never shifts content. The frame+ // itself is a 1px dashed border around the viewport; the top strip carries+ // the EDIT MODE label and tips; the bottom strip carries the column index.+ const editFrame = state.edit ? `+ <div class="edit-frame" aria-hidden="true"></div>+ <div class="edit-strip-top" role="status">+ <span class="marker">EDIT MODE</span>+ <span class="tips">+ DRAG PANEL TO REORDER ·+ CLICK A <span class="key-bind">NUMBER</span> TO RESIZE ·+ <span class="key-bind">✕</span> TO REMOVE ·+ SCROLL FOR <span class="key-bind">+ ADD</span>+ </span>+ <span class="meta">${esc(dash.name.toUpperCase())} · ${merged.length} PANELS</span>+ </div>+ <div class="edit-strip-bottom" aria-hidden="true">${+ Array.from({ length: 12 }, (_, i) => `<span>${String(i + 1).padStart(2, '0')}</span>`).join('')+ }</div>+ ` : '';+ const gridOverlay = state.edit+ ? `<div class="edit-grid" aria-hidden="true">${'<span></span>'.repeat(12)}</div>`+ : '';+ const addHtml = state.edit ? renderAddPicker() : '';++ // Section-level views (alerts, data, users, settings) don't show the+ // inline time control — the time range is a dashboards-section concept.+ const hideTimeCtrl = state.section !== 'dashboards' && state.section !== 'discover';+ const showFilterBar = state.section === 'dashboards';+ const filterBarHtml = showFilterBar+ ? FilterBar({ filters: activeFilters, kql: serializeKql(activeFilters) })+ : '';+ const refreshHtml = hideTimeCtrl+ ? ''+ : RefreshCtrl({ active: state.refresh });+ const clusterHtml = hideTimeCtrl+ ? ''+ : ClusterCtrl({ clusters: listClustersSync(), active: state.cluster });+ const savedViewsHtml = showFilterBar+ ? SavedViews({ views: loadViews(), dashId: dash.id })+ : '';++ app.innerHTML = `+ ${Nav({+ sections: SECTIONS,+ activeSection: state.section,+ dashboards: dashboardsForSection,+ groups: DASHBOARD_GROUPS,+ activeDash: dash.id,+ theme: state.theme,+ edit: state.edit,+ mobile: state.mobile,+ status: navStatus(),+ })}+ ${state.mobile ? '<div class="iphone-frame"><div class="iphone-notch"></div><div class="iphone-screen">' : ''}+ ${SceneHeader({+ title: view.title, kicker: view.kicker || 'OBSERVE', meta: view.meta || [state.time],+ editable: state.edit, dashId: dash.id,+ })}+ ${view.caption ? `<p class="caption">${esc(view.caption)}</p>` : ''}+ ${hideTimeCtrl ? '' : `<div class="dash-ctrls">${TimeCtrl({ active: state.time, custom: state.timeCustom })}${refreshHtml}${clusterHtml}</div>`}+ ${filterBarHtml}+ ${savedViewsHtml}+ <main class="canvas${state.edit ? ' edit' : ''}" aria-label="${esc(dash.name)}">${gridOverlay}${panelsHtml}</main>+ ${addHtml}+ ${state.mobile ? '</div><div class="iphone-home-bar"></div></div>' : ''}+ ${Footer()}+ ${editFrame}+ `;+ app.setAttribute('aria-busy', 'false');++ // Restore focus on the search input (if we're on the search dashboard).+ if (state._focusSelector) {+ const el = document.querySelector(state._focusSelector);+ if (el) {+ el.focus();+ if (el.tagName === 'INPUT') {+ const v = el.value;+ el.setSelectionRange(v.length, v.length);+ }+ }+ state._focusSelector = null;+ }+}++// ---------- event delegation ------------------------------+let dragSrcId = null;++document.addEventListener('click', (e) => {+ // Primary nav: top-level product section+ const secA = e.target.closest('[data-section]');+ if (secA) {+ e.preventDefault();+ const sid = secA.getAttribute('data-section');+ if (sid === 'dashboards') {+ location.hash = '#/dashboards';+ } else {+ location.hash = '#/' + sid;+ }+ return;+ }+ // Secondary nav: a specific dashboard inside the dashboards section+ const dashA = e.target.closest('[data-dash]');+ if (dashA) {+ e.preventDefault();+ const id = dashA.getAttribute('data-dash');+ location.hash = '#/dashboards/' + id;+ return;+ }+ // Secondary nav: a collapsed group tab — switch groups by landing+ // on the group's first dashboard.+ const groupBtn = e.target.closest('[data-dash-group]');+ if (groupBtn) {+ e.preventDefault();+ const firstId = groupBtn.getAttribute('data-dash-group-first');+ if (firstId) location.hash = '#/dashboards/' + firstId;+ return;+ }+ // Time range+ const tb = e.target.closest('[data-time]');+ if (tb) {+ state.time = tb.getAttribute('data-time');+ localStorage.setItem(LS.time, state.time);+ // When switching INTO custom and we have no stored endpoints,+ // seed a sensible default (now − 24h → now).+ if (state.time === 'CUSTOM' && !state.timeCustom.from) {+ const now = new Date();+ const prev = new Date(now.getTime() - 24 * 3600 * 1000);+ const fmt = (d) => d.toISOString().slice(0, 16);+ state.timeCustom = { from: fmt(prev), to: fmt(now) };+ localStorage.setItem('xerj.timeFrom', state.timeCustom.from);+ localStorage.setItem('xerj.timeTo', state.timeCustom.to);+ }+ writeUrlState();+ render();+ return;+ }+ // Refresh interval+ const rf = e.target.closest('[data-refresh]');+ if (rf) {+ setRefreshInterval(parseInt(rf.getAttribute('data-refresh'), 10));+ render();+ return;+ }+ // Manual retry on error+ if (e.target.closest('[data-retry]')) {+ render();+ return;+ }+ // Global filter bar: click-to-filter (used by FilterBar pills and+ // any click-to-filter affordance inside a panel — TopN rows, Dist+ // segments, heatmap cells).+ const fAdd = e.target.closest('[data-filter-add]');+ if (fAdd) {+ const raw = fAdd.getAttribute('data-filter-add');+ const idx = raw.indexOf(':');+ if (idx > 0) {+ const field = raw.slice(0, idx);+ const value = raw.slice(idx + 1);+ // Drilldown takes precedence when the panel declares one.+ const drillHost = fAdd.closest('[data-drilldown-to]');+ if (drillHost) {+ const toId = drillHost.getAttribute('data-drilldown-to');+ // Seed the target dashboard's filters with this value before+ // navigating so the destination renders pre-filtered. The+ // search-discover dashboard has its own filter store+ // (state.search.filters) — seed that one instead.+ if (toId === 'search-discover') {+ state.search.filters = { ...(state.search.filters || {}), [field]: value };+ state.search.result = null; // force re-run on render+ } else {+ state.filters[toId] = { ...(state.filters[toId] || {}), [field]: value };+ try { localStorage.setItem(LS.filters(toId), JSON.stringify(state.filters[toId])); } catch {}+ }+ // Resolve the target's actual section — some targets (like+ // search-discover) live outside the 'dashboards' section and+ // need a different hash shape (#/discover rather than+ // #/dashboards/search-discover).+ const all = mergedDashboards(defaults, { includeHidden: true });+ const target = all.find((d) => d.id === toId);+ const sectionId = target?.section || 'dashboards';+ location.hash = sectionId === 'dashboards' ? `#/dashboards/${toId}` : `#/${sectionId}`;+ return;+ }+ setFilter(field, value);+ render();+ }+ return;+ }+ // Remove one chip from a filter pill (multi-value OR filters).+ const fRem = e.target.closest('[data-filter-remove]');+ if (fRem) {+ const raw = fRem.getAttribute('data-filter-remove');+ const idx = raw.indexOf(':');+ if (idx > 0) {+ removeFilterValue(raw.slice(0, idx), raw.slice(idx + 1));+ render();+ }+ return;+ }+ if (e.target.closest('[data-filter-clear]')) {+ clearFilters();+ render();+ return;+ }+ // Cluster selector+ const cset = e.target.closest('[data-cluster-set]');+ if (cset) {+ state.cluster = cset.getAttribute('data-cluster-set');+ setDefaultCluster(state.cluster);+ writeUrlState();+ render();+ return;+ }+ // Save current view+ if (e.target.closest('[data-view-save]')) {+ saveCurrentView();+ render();+ return;+ }+ // Apply a saved view+ const vApply = e.target.closest('[data-view-apply]');+ if (vApply) {+ applyView(vApply.getAttribute('data-view-apply'));+ return;+ }+ // Delete a saved view+ const vDel = e.target.closest('[data-view-delete]');+ if (vDel) {+ const id = vDel.getAttribute('data-view-delete');+ if (confirm('Delete this view?')) {+ deleteView(id);+ render();+ }+ return;+ }+ // Theme+ const th = e.target.closest('[data-theme-set]');+ if (th) {+ applyTheme(th.getAttribute('data-theme-set'));+ render();+ return;+ }+ // Mobile preview toggle+ if (e.target.closest('[data-mobile-toggle]')) {+ state.mobile = !state.mobile;+ localStorage.setItem('xerj.mobile', state.mobile ? '1' : '0');+ document.documentElement.classList.toggle('mobile-preview', state.mobile);+ render();+ return;+ }+ // Edit toggle+ if (e.target.closest('[data-edit-toggle]')) {+ state.edit = !state.edit;+ localStorage.setItem(LS.edit, state.edit ? '1' : '0');+ render();+ return;+ }+ // Reset layout+ if (e.target.closest('[data-reset-layout]')) {+ const id = state.route;+ delete state.layouts[id];+ saveLayout(id);+ render();+ return;+ }+ // Resize (click a size number)+ const sz = e.target.closest('[data-size]');+ if (sz) {+ const pid = sz.getAttribute('data-panel');+ const cols = parseInt(sz.getAttribute('data-size'), 10);+ const dash = registry[state.route];+ const view = dash.render({ data: {}, time: state.time });+ mutate(state.route, view.panels, (ov) => { ov.cols[pid] = cols; });+ render();+ return;+ }+ // Remove panel+ const rm = e.target.closest('[data-remove]');+ if (rm) {+ const pid = rm.getAttribute('data-panel');+ const dash = registry[state.route];+ const view = dash.render({ data: {}, time: state.time });+ mutate(state.route, view.panels, (ov) => {+ if (!ov.hidden.includes(pid)) ov.hidden.push(pid);+ const idx = (ov.added || []).findIndex((a) => a.id === pid);+ if (idx >= 0) ov.added.splice(idx, 1);+ });+ render();+ return;+ }+ // Search: query type+ const qt = e.target.closest('[data-query-type]');+ if (qt) {+ state.search.type = qt.getAttribute('data-query-type');+ runSearchNow();+ state._focusSelector = '[data-search-input]';+ render();+ return;+ }+ // Search: index+ const si = e.target.closest('[data-search-index]');+ if (si) {+ state.search.index = si.getAttribute('data-search-index');+ runSearchNow();+ state._focusSelector = '[data-search-input]';+ render();+ return;+ }+ // Facet apply (click-to-filter) — also drives the click-to-filter on Hit+ // row values and the ✕ on filter pills (clicking an active value removes).+ const fa = e.target.closest('[data-facet-apply]');+ if (fa) {+ const raw = fa.getAttribute('data-facet-apply');+ const colonIdx = raw.indexOf(':');+ const field = raw.slice(0, colonIdx);+ const value = raw.slice(colonIdx + 1);+ const cur = state.search.filters[field];+ if (cur === value) delete state.search.filters[field];+ else state.search.filters[field] = value;+ runSearchNow();+ render();+ return;+ }+ // Clear all filters+ if (e.target.closest('[data-facet-clear]')) {+ state.search.filters = {};+ runSearchNow();+ render();+ return;+ }+ // Sort a Hits column (GH#696 / GH#737)+ const sortBtn = e.target.closest('[data-sort-field]');+ if (sortBtn) {+ state.search.sort = {+ field: sortBtn.getAttribute('data-sort-field'),+ dir: sortBtn.getAttribute('data-sort-dir'),+ };+ runSearchNow();+ render();+ return;+ }+ // Toggle time-column visibility (GH#3319)+ if (e.target.closest('[data-toggle-time]')) {+ state.search.showTime = !state.search.showTime;+ runSearchNow();+ render();+ return;+ }+ // Export Hits as CSV (GH#1992 — the #1 ask of all time)+ if (e.target.closest('[data-export-csv]')) {+ const hits = state.search.result?.hits || [];+ const cols = state.search.showTime+ ? ['_index', '_id', '_score', '_ts', '_source']+ : ['_index', '_id', '_score', '_source'];+ downloadText('xerj-search-' + new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-') + '.csv',+ 'text/csv', hitsToCsv(hits, cols));+ return;+ }+ // Export a panel chart as PNG (GH#1366 — 178 reactions)+ const pngBtn = e.target.closest('[data-export-png]');+ if (pngBtn) {+ const sec = pngBtn.closest('.panel');+ const svg = sec?.querySelector('svg.chart, svg.series');+ if (svg) {+ const id = sec.getAttribute('data-panel') || 'panel';+ svgToPng(svg, { filename: 'xerj-' + id + '.png' }).catch((err) =>+ console.error('PNG export failed', err));+ }+ return;+ }+ // --- MANAGE view click handlers -------------------------+ const mgUp = e.target.closest('[data-mg-up]');+ if (mgUp) {+ const id = mgUp.getAttribute('data-mg-up');+ const list = mergedDashboards(defaults, { includeHidden: true });+ const i = list.findIndex((d) => d.id === id);+ if (i > 0) {+ const order = list.map((d) => d.id);+ [order[i - 1], order[i]] = [order[i], order[i - 1]];+ reorderDashboards(order);+ render();+ }+ return;+ }+ const mgDown = e.target.closest('[data-mg-down]');+ if (mgDown) {+ const id = mgDown.getAttribute('data-mg-down');+ const list = mergedDashboards(defaults, { includeHidden: true });+ const i = list.findIndex((d) => d.id === id);+ if (i >= 0 && i < list.length - 1) {+ const order = list.map((d) => d.id);+ [order[i + 1], order[i]] = [order[i], order[i + 1]];+ reorderDashboards(order);+ render();+ }+ return;+ }+ const mgRename = e.target.closest('[data-mg-rename]');+ if (mgRename) {+ const id = mgRename.getAttribute('data-mg-rename');+ const current = mergedDashboards(defaults, { includeHidden: true }).find((d) => d.id === id);+ const name = prompt('Rename "' + (current?.name || id) + '":', current?.name || '');+ if (name != null) {+ renameDashboard(id, name);+ render();+ }+ return;+ }+ const mgHide = e.target.closest('[data-mg-hide]');+ if (mgHide) {+ const id = mgHide.getAttribute('data-mg-hide');+ const list = mergedDashboards(defaults, { includeHidden: true });+ const cur = list.find((d) => d.id === id);+ setHidden(id, !cur?.hidden);+ render();+ return;+ }+ const mgClone = e.target.closest('[data-mg-clone]');+ if (mgClone) {+ const id = mgClone.getAttribute('data-mg-clone');+ const current = mergedDashboards(defaults, { includeHidden: true }).find((d) => d.id === id);+ const name = prompt('Clone "' + (current?.name || id) + '" as:', (current?.name || 'Untitled') + ' (copy)');+ if (name) {+ const newId = createUserDashboard({ name, fromId: id });+ location.hash = '#/dashboards/' + newId;+ }+ return;+ }+ const mgDelete = e.target.closest('[data-mg-delete]');+ if (mgDelete) {+ const id = mgDelete.getAttribute('data-mg-delete');+ if (isUserDash(id) && confirm('Delete user dashboard "' + id + '"? This cannot be undone.')) {+ deleteUserDashboard(id);+ if (state.route === id) {+ location.hash = '#/settings';+ } else {+ render();+ }+ }+ return;+ }+ const mgNew = e.target.closest('[data-mg-new]');+ if (mgNew) {+ const fromId = mgNew.getAttribute('data-mg-new');+ const name = prompt(fromId ? 'New dashboard from "' + fromId + '" · Name:' : 'New blank dashboard · Name:', 'Untitled');+ if (name) {+ const newId = createUserDashboard({ name, fromId: fromId || null });+ location.hash = '#/dashboards/' + newId;+ }+ return;+ }+ const mgCluster = e.target.closest('[data-mg-cluster]');+ if (mgCluster) {+ setDefaultCluster(mgCluster.getAttribute('data-mg-cluster'));+ state._focusIndex = null;+ render();+ return;+ }+ const mgIndex = e.target.closest('[data-mg-index]');+ if (mgIndex) {+ state._focusIndex = mgIndex.getAttribute('data-mg-index');+ render();+ return;+ }+ if (e.target.closest('[data-mg-reset-all]')) {+ if (confirm('Reset ALL saved state? This wipes dashboards, layouts, theme, filters.')) {+ for (const k of Object.keys(localStorage)) {+ if (k.startsWith('xerj.')) localStorage.removeItem(k);+ }+ resetDashboards();+ location.reload();+ }+ return;+ }++ // Add panel (from ADD picker)+ const add = e.target.closest('[data-add]');+ if (add) {+ const typeId = add.getAttribute('data-add');+ const t = chartTypes[typeId];+ if (!t) return;+ const dash = registry[state.route];+ const view = dash.render({ data: {}, time: state.time });+ mutate(state.route, view.panels, (ov) => {+ ov.added = ov.added || [];+ const newId = typeId + '-' + Date.now().toString(36);+ ov.added.push({+ id: newId,+ type: typeId,+ eyebrow: t.name + ' · NEW',+ cols: t.cols || 6,+ });+ ov.order = ov.order || view.panels.map((p) => p.id);+ ov.order.push(newId);+ });+ render();+ // scroll to bottom so the new panel is visible+ requestAnimationFrame(() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }));+ return;+ }+});++// ---------- search input (Enter to run) -------------------+document.addEventListener('keydown', (e) => {+ // KQL-lite input on dashboards+ const kq = e.target.closest && e.target.closest('[data-kql-input]');+ if (kq) {+ if (e.key === 'Enter') {+ e.preventDefault();+ applyKqlInput(kq.value);+ state._focusSelector = '[data-kql-input]';+ render();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ kq.value = '';+ applyKqlInput('');+ state._focusSelector = '[data-kql-input]';+ render();+ }+ return;+ }+ const si = e.target.closest && e.target.closest('[data-search-input]');+ if (si) {+ if (e.key === 'Enter') {+ e.preventDefault();+ state.search.q = si.value;+ runSearchNow();+ state._focusSelector = '[data-search-input]';+ render();+ } else if (e.key === 'Escape') {+ si.value = '';+ state.search.q = '';+ state.search.filters = {};+ runSearchNow();+ state._focusSelector = '[data-search-input]';+ render();+ }+ return;+ }+ // Inline rename of the scene title in edit mode (contenteditable h1)+ const rn = e.target.closest && e.target.closest('[data-rename-dash]');+ if (rn) {+ if (e.key === 'Enter') {+ e.preventDefault();+ const id = rn.getAttribute('data-rename-dash');+ const name = rn.textContent.trim();+ renameDashboard(id, name);+ rn.blur();+ render();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ rn.blur();+ render();+ }+ }+});+// Custom time range — FROM/TO datetime-local inputs+document.addEventListener('change', (e) => {+ const tf = e.target.closest && e.target.closest('[data-time-from]');+ const tt = e.target.closest && e.target.closest('[data-time-to]');+ if (tf || tt) {+ state.timeCustom = {+ from: document.querySelector('[data-time-from]')?.value || '',+ to: document.querySelector('[data-time-to]')?.value || '',+ };+ localStorage.setItem('xerj.timeFrom', state.timeCustom.from);+ localStorage.setItem('xerj.timeTo', state.timeCustom.to);+ writeUrlState();+ render();+ }+});++// blur-save for inline rename (clicking outside the title also commits)+document.addEventListener('blur', (e) => {+ const rn = e.target.closest && e.target.closest('[data-rename-dash]');+ if (!rn) return;+ const id = rn.getAttribute('data-rename-dash');+ const newName = rn.textContent.trim();+ renameDashboard(id, newName);+}, true);++// ---------- drag and drop ---------------------------------+document.addEventListener('dragstart', (e) => {+ if (!state.edit) return;+ const sec = e.target.closest('.panel.edit');+ if (!sec) return;+ dragSrcId = sec.getAttribute('data-panel');+ sec.classList.add('dragging');+ try {+ e.dataTransfer.effectAllowed = 'move';+ e.dataTransfer.setData('text/plain', dragSrcId);+ } catch {}+});+document.addEventListener('dragover', (e) => {+ if (!state.edit || !dragSrcId) return;+ const sec = e.target.closest('.panel.edit');+ if (!sec) return;+ e.preventDefault();+ document.querySelectorAll('.drop-before, .drop-after').forEach((el) => el.classList.remove('drop-before', 'drop-after'));+ const rect = sec.getBoundingClientRect();+ const after = e.clientX > rect.left + rect.width / 2;+ sec.classList.add(after ? 'drop-after' : 'drop-before');+});+document.addEventListener('dragleave', (e) => {+ const sec = e.target.closest('.panel.edit');+ if (sec && !sec.contains(e.relatedTarget)) sec.classList.remove('drop-before', 'drop-after');+});+document.addEventListener('drop', (e) => {+ if (!state.edit || !dragSrcId) return;+ const sec = e.target.closest('.panel.edit');+ if (!sec) return;+ e.preventDefault();+ const targetId = sec.getAttribute('data-panel');+ const insertAfter = sec.classList.contains('drop-after');+ document.querySelectorAll('.drop-before, .drop-after').forEach((el) => el.classList.remove('drop-before', 'drop-after'));+ if (!targetId || targetId === dragSrcId) return;++ const dash = registry[state.route];+ const view = dash.render({ data: {}, time: state.time });+ mutate(state.route, view.panels, (ov) => {+ const fullOrder = ov.order && ov.order.length ? ov.order.slice() : view.panels.map((p) => p.id);+ // Make sure both src and target are in the order list (they should be).+ const have = new Set(fullOrder);+ if (!have.has(dragSrcId)) fullOrder.push(dragSrcId);+ if (!have.has(targetId)) fullOrder.push(targetId);+ const from = fullOrder.indexOf(dragSrcId);+ fullOrder.splice(from, 1);+ let to = fullOrder.indexOf(targetId);+ if (insertAfter) to += 1;+ fullOrder.splice(to, 0, dragSrcId);+ ov.order = fullOrder;+ });+ render();+});+document.addEventListener('dragend', () => {+ document.querySelectorAll('.dragging').forEach((el) => el.classList.remove('dragging'));+ document.querySelectorAll('.drop-before, .drop-after').forEach((el) => el.classList.remove('drop-before', 'drop-after'));+ dragSrcId = null;+});++// ---------- route changes ---------------------------------+window.addEventListener('hashchange', () => {+ const parsed = parseRoute();+ state.section = parsed.section;+ state.route = parsed.route;+ // A URL with query string (e.g. from a share link) should reapply.+ const urlState = parseUrlState();+ if (urlState.time) state.time = urlState.time;+ if (urlState.cluster) state.cluster = urlState.cluster;+ if (urlState.filters) {+ state.filters[state.route] = { ...(state.filters[state.route] || {}), ...urlState.filters };+ saveFilters(state.route);+ }+ writeUrlState();+ render();+});++// Boot the refresh interval if the user had one saved.+if (state.refresh > 0) setRefreshInterval(state.refresh);++// Restore mobile preview class if it was active.+if (state.mobile) document.documentElement.classList.add('mobile-preview');++render();diff --git a/xerj-ux/src/dashboards/agent-memory.js b/xerj-ux/src/dashboards/agent-memory.jsnew file mode 100644index 000000000..2479fcbf9--- /dev/null+++ b/xerj-ux/src/dashboards/agent-memory.js@@ -0,0 +1,111 @@+// ============================================================+// Dashboard — AGENT · MEMORY+//+// XERJ.ai's unique primitive: append-only index with semantic+// dedup and recency-weighted recall for long-running agents.+// This is the only dashboard in the category — nobody else+// ships this at the data-layer level.+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist } from '../ux/charts.js';+import { EmbedSpace } from '../ux/charts-ai.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { Table } from '../ux/tables.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const agentMemory = {+ id: 'agent-memory',+ name: 'Agent · Memory',+ render: ({ data, time }) => ({+ title: 'AGENT · MEMORY',+ kicker: 'APPEND-ONLY · DEDUP · RECENCY',+ meta: [time, 'AGENTIC LOOPS'],+ panels: [++ { id: 'entries', eyebrow: 'MEMORY ENTRIES', cols: 4, type: 'metric',+ render: () => Num({+ value: data.metrics.entries.formatted, unit: 'stored',+ spark: Spark(data.series.size, { w: 220, h: 44 }),+ delta: data.metrics.entries.delta, emphasis: true,+ }),+ },+ { id: 'dedup', eyebrow: 'DEDUP RATE', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.dedup.formatted, unit: '%',+ delta: data.metrics.dedup.delta, deltaGood: 'up', emphasis: false,+ }),+ },+ { id: 'recall', eyebrow: 'RECALL P95', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.recall.formatted, unit: 'ms',+ delta: data.metrics.recall.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'growth', eyebrow: 'GROWTH', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.growth.formatted, unit: 'new',+ hint: data.metrics.growth.hint, emphasis: false,+ }),+ },+ { id: 'agents', eyebrow: 'AGENTS', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.agents.formatted, unit: 'online',+ hint: data.metrics.agents.hint, emphasis: false,+ }),+ },++ { id: 'sizeSeries', eyebrow: 'MEMORY SIZE OVER TIME', cols: 12, type: 'line',+ render: () => Series(data.series.size, {+ h: 140, labels: [data.series.startLabel, data.series.endLabel], unit: 'entries',+ }),+ },++ { id: 'embedSpace', eyebrow: 'SEMANTIC MEMORY · ONCALL-TRIAGE · UMAP', cols: 12, type: 'embedspace',+ render: () => EmbedSpace({ clusters: data.clusters, h: 360 }),+ },++ { id: 'byAgent', eyebrow: 'BY AGENT', cols: 6, type: 'topn',+ render: () => TopN({+ items: data.agents,+ total: data.agents.reduce((a, b) => a + b.value, 0),+ n: 10,+ }),+ },++ { id: 'topMemories', eyebrow: 'MOST-REFERENCED MEMORIES', cols: 6, type: 'topn',+ render: () => TopN({+ items: data.topMemories,+ n: 10,+ valueFmt: (v) => v + '× ',+ }),+ },++ { id: 'dedupSeries', eyebrow: 'DEDUP RATE OVER TIME', cols: 6, type: 'line',+ render: () => Series(data.series.dedup, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: '%',+ }),+ },++ { id: 'recallSeries', eyebrow: 'RECALL P95 OVER TIME', cols: 6, type: 'line',+ render: () => Series(data.series.recallP95, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'ms',+ }),+ },++ { id: 'recentOps', eyebrow: 'RECENT OPERATIONS', cols: 12, type: 'table',+ render: () => Table({+ columns: ['TIME', 'OP', 'AGENT', 'DETAIL'],+ rows: data.recentOps,+ align: ['left', 'left', 'left', 'left'],+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['agent-memory'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/ai-overview.js b/xerj-ux/src/dashboards/ai-overview.jsnew file mode 100644index 000000000..a456de066--- /dev/null+++ b/xerj-ux/src/dashboards/ai-overview.js@@ -0,0 +1,100 @@+// ============================================================+// Dashboard — AI · OVERVIEW (flagship)+//+// Answers: am I serving AI at scale, what does it cost me,+// what would it cost on ES + Pinecone + Splunk, where is my+// money going?+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist, Heatmap } from '../ux/charts.js';+import { Ribbon3D, FlowBand } from '../ux/charts-ai.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const aiOverview = {+ id: 'ai-overview',+ name: 'AI · Overview',+ render: ({ data, time }) => ({+ title: 'AI · OVERVIEW',+ kicker: 'XERJ INTELLIGENCE',+ meta: [time, 'AI DATA PLANE'],+ panels: [++ { id: 'queries', eyebrow: 'LLM QUERIES', cols: 4, type: 'metric',+ render: () => Num({+ value: data.metrics.queries.formatted, unit: 'queries',+ spark: Spark(data.series.queries, { w: 220, h: 44 }),+ delta: data.metrics.queries.delta, emphasis: true,+ }),+ },+ { id: 'tokens', eyebrow: 'TOKENS · IN + OUT', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.tokens.formatted, unit: 'T',+ delta: data.metrics.tokens.delta, emphasis: false,+ }),+ },+ { id: 'cost', eyebrow: 'SPEND · USD', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.cost.formatted, unit: 'usd',+ delta: data.metrics.cost.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'savings', eyebrow: 'vs. ES + PINECONE + SPLUNK', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.savings.formatted, unit: 'saved',+ hint: data.metrics.savings.note,+ emphasis: false,+ }),+ },+ { id: 'cacheHit', eyebrow: 'CACHE HIT', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.cacheHit.formatted, unit: '%',+ delta: data.metrics.cacheHit.delta, emphasis: false,+ }),+ },++ { id: 'queriesSeries', eyebrow: 'QUERIES OVER TIME', cols: 12, type: 'line',+ render: () => Series(data.series.queries, {+ h: 160, labels: [data.series.startLabel, data.series.endLabel], unit: 'q/s',+ }),+ },++ { id: 'latencyRibbons', eyebrow: 'LATENCY · PER MODEL · AXONOMETRIC', cols: 12, type: 'ribbon3d',+ render: () => Ribbon3D({ series: data.latencyRibbons, h: 280, depth: 14 }),+ },++ { id: 'tokenFlow', eyebrow: 'TOKEN BUDGET', cols: 12, type: 'flowband',+ render: () => FlowBand({ segments: data.flowSegments, unit: 'T' }),+ },++ { id: 'models', eyebrow: 'BY MODEL', cols: 12, type: 'dist',+ render: () => Dist({ segments: data.models, width: 1200 }),+ },++ { id: 'topIntents', eyebrow: 'TOP INTENTS · CLICK TO DRILL', cols: 6, type: 'topn',+ drilldown: { to: 'search-discover' },+ render: () => TopN({ items: data.intents, total: data.metrics.queries.value, n: 10, filterField: 'intent' }),+ },++ { id: 'topDocs', eyebrow: 'TOP DOCUMENTS · CLICK TO FILTER', cols: 6, type: 'topn',+ render: () => TopN({ items: data.topDocs, total: data.metrics.queries.value, n: 10, filterField: 'doc' }),+ },++ { id: 'costHeatmap', eyebrow: 'SPEND · WEEKDAY × 2H', cols: 12, type: 'heatmap',+ render: () => Heatmap({+ rows: ['MON','TUE','WED','THU','FRI','SAT','SUN'],+ cols: data.costHeatmap.cols,+ matrix: data.costHeatmap.matrix,+ cellFmt: (v) => '$' + v.toFixed(0),+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['ai-overview'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/alerts.js b/xerj-ux/src/dashboards/alerts.jsnew file mode 100644index 000000000..e5aced459--- /dev/null+++ b/xerj-ux/src/dashboards/alerts.js@@ -0,0 +1,157 @@+// ============================================================+// Section — ALERTS+//+// Live alert rules + recent fires + noisy rules + rule authoring.+//+// Corpus evidence: 349 items in categories/07-alerting-and-watcher,+// 49% negative. Recurring complaints:+// • "Watcher → Alerting → Rules" migration confusion (GH issues)+// • noisy alerts, silent alerts, rules fire with no trail+// • separate Watcher app you have to remember exists+// • authoring YAML for simple threshold rules+//+// XERJ response: rules as code (stored as JSON in xerj.rules.*),+// NL→rule authoring via the embed-proxy (Phase 3), connector+// status visible inline, no separate "app".+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist } from '../ux/charts.js';+import { TopN, Events } from '../ux/layout.js';+import { Table, Markdown } from '../ux/tables.js';+import { FlowBand } from '../ux/charts-ai.js';+import { Citations } from '../ux/charts-ops.js';++export const alerts = {+ id: 'alerts',+ name: 'Alerts',+ section: 'alerts',+ render: ({ data, time }) => ({+ title: 'ALERTS',+ kicker: 'RULES · FIRES · CONNECTORS',+ meta: [time, 'AS CODE · NO WATCHER APP'],+ caption: 'Alert rules as code, not YAML in a hidden app. Every rule is a JSON file under `xerj.rules.*` you can diff, review, and version. This view is the operator surface — active fires, rule health, connector status, and the corpus evidence that says Kibana got this wrong.',+ panels: [++ { id: 'active', eyebrow: 'ACTIVE FIRES', cols: 3, type: 'metric',+ render: () => Num({+ value: '7', unit: 'open',+ delta: -12.5, deltaGood: 'down',+ spark: Spark([3,5,8,12,14,11,9,7,6,7,5,7], { w: 160, h: 32 }),+ emphasis: true,+ }),+ },+ { id: 'silenced', eyebrow: 'SILENCED', cols: 2, type: 'metric',+ render: () => Num({ value: '3', unit: 'rules', hint: '2h avg ttl', emphasis: false }),+ },+ { id: 'rules', eyebrow: 'RULES DEFINED', cols: 2, type: 'metric',+ render: () => Num({ value: '48', unit: 'total', hint: '12 recently modified', emphasis: false }),+ },+ { id: 'fires', eyebrow: 'FIRES · 24H', cols: 2, type: 'metric',+ render: () => Num({ value: '132', unit: 'events', delta: 4.2, deltaGood: 'down', emphasis: false }),+ },+ { id: 'connectors', eyebrow: 'CONNECTORS', cols: 3, type: 'metric',+ render: () => Num({ value: '4', unit: 'healthy', hint: 'slack · pagerduty · webhook · email', emphasis: false }),+ },++ { id: 'firesOverTime', eyebrow: 'FIRES OVER TIME', cols: 12, type: 'line',+ render: () => Series(+ Array.from({ length: 48 }, (_, i) => 4 + Math.sin(i / 6) * 3 + Math.cos(i / 3) * 2 + Math.random() * 2),+ { h: 140, labels: ['00:00', '24:00'], unit: '/bucket' }+ ),+ },++ { id: 'bySev', eyebrow: 'BY SEVERITY', cols: 12, type: 'dist',+ render: () => Dist({+ segments: [+ { label: 'CRITICAL', value: 8 },+ { label: 'ERROR', value: 24 },+ { label: 'WARN', value: 62 },+ { label: 'INFO', value: 38 },+ ],+ width: 1200,+ }),+ },++ { id: 'topNoisy', eyebrow: 'TOP NOISY RULES · FIRES / 24H', cols: 6, type: 'topn',+ render: () => TopN({+ items: [+ { label: 'checkout-svc p95 latency > 2s', value: 28 },+ { label: 'auth failures > 10/min', value: 24 },+ { label: 'disk utilization > 90%', value: 18 },+ { label: 'memtable ratio > 0.8', value: 14 },+ { label: 'upstream 5xx > 1%', value: 12 },+ { label: 'wal lag > 50ms', value: 11 },+ { label: 'cache hit rate < 50%', value: 9 },+ { label: 'hnsw recall < 95%', value: 7 },+ ],+ total: 132,+ n: 8,+ }),+ },++ { id: 'recent', eyebrow: 'RECENT · LAST 30 EVENTS', cols: 6, type: 'events',+ render: () => Events({ items: [+ { at: '23:14:02', sev: 'err', msg: 'checkout-svc p95 latency > 2s · 2842ms · critical' },+ { at: '23:13:51', sev: 'warn', msg: 'auth failures > 10/min · 14 failed logins · src=45.137.21.4' },+ { at: '23:13:22', sev: 'warn', msg: 'upstream 5xx > 1% · 1.8% on /api/v2/checkout' },+ { at: '23:12:48', sev: 'info', msg: 'disk utilization > 90% · ip-10-0-4-73 · 92%' },+ { at: '23:12:09', sev: 'err', msg: 'hnsw recall < 95% · embeddings index · 93.7%' },+ { at: '23:11:44', sev: 'warn', msg: 'memtable ratio > 0.8 · logs-prod · 0.84' },+ { at: '23:11:03', sev: 'info', msg: 'wal lag > 50ms · ingest-worker · 62ms' },+ { at: '23:10:41', sev: 'warn', msg: 'cache hit rate < 50% · /api/v2/search · 42%' },+ ]}),+ },++ { id: 'ruleAsCode', eyebrow: 'RULES AS CODE · EXAMPLE', cols: 12, type: 'markdown',+ render: () => Markdown(+`## This is what a rule looks like++A XERJ.ai alert rule is a JSON object. It lives in git, not in a database.+You diff it, review it, roll it back. No separate app, no YAML, no "Watcher"+vs "Alerting" vs "Rules" migration confusion.++\`\`\`+{+ "id": "checkout-p95-latency",+ "name": "Checkout p95 latency > 2s",+ "severity": "critical",+ "query": {+ "index": "metrics",+ "metric": "query_latency_s{quantile=\\"0.95\\",service=\\"checkout-svc\\"}",+ "window": "5m",+ "op": ">",+ "value": 2.0+ },+ "dedupe": "30m",+ "notify": ["pagerduty/oncall", "slack/#oncall"],+ "runbook": "https://runbook.internal/checkout-latency"+}+\`\`\`++That's all of it. Put it in \`rules/checkout-p95-latency.json\`. Commit.+The engine watches the directory and starts evaluating. If you delete the+file, the rule stops — no orphaned state.`+ ),+ },++ { id: 'citations', eyebrow: 'WHY THIS SECTION EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({+ items: [+ { id: 'kibana-alerting', source: 'github', score: 143,+ title: 'Allow Authors to Limit Interactivity',+ url: 'https://github.com/elastic/kibana/issues/9575' },+ { id: 'watcher-1', source: 'discourse', score: 47,+ title: 'Watcher that counts the documents that arrive to an index in kibana',+ url: 'https://discuss.elastic.co/t/watcher-that-counts-the-documents-that-arrive-to-an-index-in-kibana/270609/23' },+ { id: 'alerting-noise', source: 'reddit', score: 22,+ title: 'Kibana alerting: noisy, silent, or broken — pick one',+ url: 'https://www.reddit.com/r/elasticsearch/' },+ ],+ total: 349,+ }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/anomaly-detect.js b/xerj-ux/src/dashboards/anomaly-detect.jsnew file mode 100644index 000000000..9861384f4--- /dev/null+++ b/xerj-ux/src/dashboards/anomaly-detect.js@@ -0,0 +1,134 @@+// ============================================================+// Dashboard — ANOMALY · DETECTION (z-score + attribution)+//+// Note: the engine's native anomaly pipeline is aspirational+// today. This dashboard runs a rolling 2.5σ detector on the+// client so the panels are real — it'll flip to server-side+// scoring once that module lands. The story is the same either+// way: *what fired, when, and why*.+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Dist } from '../ux/charts.js';+import { AnomalyBand, Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { Treemap } from '../ux/charts-ext.js';+import { ParallelCoords, AttentionMap } from '../ux/charts-ai.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const anomalyDetect = {+ id: 'anomaly-detect',+ name: 'Anomaly',+ render: ({ data, time }) => ({+ title: 'ANOMALY · DETECTION',+ kicker: 'WHAT FIRED · WHEN · WHY',+ meta: [time, 'Z-SCORE · 2.5σ BAND · BETA'],+ caption: 'Rolling-window z-score over 14 engine-emitted signals. The normal band is mean ± 2.5σ across a sliding window. Crosses mark values outside the band; the top-anomaly attribution row explains which features moved.',+ panels: [++ { id: 'detected', eyebrow: 'ANOMALIES · LAST PERIOD', cols: 4, type: 'metric',+ render: () => Num({+ value: data.metrics.detected.formatted, unit: 'fired',+ delta: data.metrics.detected.delta, deltaGood: 'down', emphasis: true,+ }),+ },+ { id: 'covered', eyebrow: 'SIGNALS SCORED', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.covered.formatted, unit: 'streams',+ hint: data.metrics.covered.hint, emphasis: false,+ }),+ },+ { id: 'falsePos', eyebrow: 'FALSE-POSITIVE RATE', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.falsePos.formatted, unit: '%',+ delta: data.metrics.falsePos.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'recall', eyebrow: 'RECALL vs HAND LABELS', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.recall.formatted, unit: '%',+ hint: data.metrics.recall.hint, emphasis: false,+ }),+ },++ { id: 'band', eyebrow: 'QUERY LATENCY · NORMAL BAND · μ ± 2.5σ', cols: 12, type: 'anomalyband',+ render: () => AnomalyBand({+ values: data.series.values,+ upper: data.series.upper,+ lower: data.series.lower,+ anomalies: data.series.anomalies,+ h: 240,+ labels: [data.series.startLabel, data.series.endLabel],+ unit: 'ms',+ }),+ },++ { id: 'topSignals', eyebrow: 'MOST-ANOMALOUS SIGNALS · BY z-SCORE', cols: 6, type: 'topn',+ render: () => TopN({+ items: data.topSignals,+ n: 10,+ valueFmt: (v) => 'z ' + v.toFixed(1),+ }),+ },++ { id: 'features', eyebrow: 'FEATURE ATTRIBUTION · TOP ANOMALY', cols: 6, type: 'topn',+ render: () => TopN({+ items: data.topFeatures,+ n: 8,+ valueFmt: (v) => 'Δ ' + v.toFixed(1) + 'σ',+ }),+ },++ { id: 'pcoords', eyebrow: 'SIGNAL PROFILE · PARALLEL COORDINATES', cols: 12, type: 'pcoords',+ render: () => ParallelCoords({+ dims: [+ { name: 'LAT p95' }, { name: 'QPS' }, { name: 'WAL LAG' },+ { name: 'FLUSH' }, { name: 'MEM' }, { name: 'CPU' },+ ],+ rows: Array.from({ length: 80 }, () => [+ 200 + Math.random() * 1400,+ 800 + Math.random() * 1800,+ 2 + Math.random() * 20,+ 180 + Math.random() * 220,+ 60 + Math.random() * 30,+ 30 + Math.random() * 55,+ ]),+ highlight: [1680, 2600, 28, 420, 84, 82],+ h: 260,+ }),+ },++ { id: 'cause', eyebrow: 'ROOT-CAUSE CANDIDATES · RANKED', cols: 6, type: 'treemap',+ render: () => Treemap({ items: [+ { label: 'upstream checkout-svc:8080', value: 38, children: [+ { label: 'connect timeout (5xx burst)', value: 22 },+ { label: 'slow upstream (p95 +420ms)', value: 12 },+ { label: 'connection reset', value: 4 },+ ]},+ { label: 'gc pause · auth-svc', value: 14, children: [+ { label: 'old-gen exhausted', value: 8 },+ { label: 'young-gen pause', value: 6 },+ ]},+ { label: 'wal lag · ingest-worker', value: 9 },+ { label: 'embed-proxy 429 rate', value: 6 },+ ]}),+ },++ { id: 'trace', eyebrow: 'CORRELATED LOG · ATTENTION EXPLAIN', cols: 6, type: 'attention',+ render: () => AttentionMap({+ tokens: ('upstream timed out ( connect ) while connecting to upstream client: 10.0.3.42 upstream: "http://checkout-svc:8080/api/v2/checkout/quote" request: "POST /api/v2/checkout HTTP/1.1" retry_after: 30s fallback: cached-rate-bucket').split(' ').map((t) => ({+ text: t,+ weight: /(upstream|timed|out|connect|checkout-svc|retry_after|fallback)/i.test(t)+ ? 0.7 + Math.random() * 0.3+ : 0.1 + Math.random() * 0.25,+ })),+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['anomaly-detect'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/data.js b/xerj-ux/src/dashboards/data.jsnew file mode 100644index 000000000..b50d48923--- /dev/null+++ b/xerj-ux/src/dashboards/data.js@@ -0,0 +1,167 @@+// ============================================================+// Section — DATA+//+// Cluster / index / field browser. This is the product surface+// for "what data does the engine have, where does it live,+// what fields are indexed, and how are they encoded".+//+// The three functions in data/data-sources.js are the ONLY+// place that swaps from mock to live fetch when the engine is+// ready. When the backend ships /v1/clusters + /v1/indices,+// this page becomes live automatically.+// ============================================================++import { esc } from '../ux/text.js';+import { Citations } from '../ux/charts-ops.js';+import { Markdown } from '../ux/tables.js';+import { defaultClusterId } from '../data/data-sources.js';++const humanCount = (n) => {+ if (n == null) return '—';+ if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';+ if (n >= 1e3) return (n / 1e3).toFixed(0) + 'K';+ return String(n);+};+const humanBytes = (b) => {+ if (b == null) return '—';+ const u = ['B','KB','MB','GB','TB','PB'];+ let v = b, i = 0;+ while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }+ return v.toFixed(v < 10 ? 1 : 0) + ' ' + u[i];+};++export const dataSection = {+ id: 'data',+ name: 'Data',+ section: 'data',+ render: ({ data, time }) => {+ const clusters = data.clusters || [];+ const indicesByCluster = data.indicesByCluster || {};+ const fieldsByIndex = data.fieldsByIndex || {};+ const active = data.activeCluster || 'local';+ const activeIndices = indicesByCluster[active] || [];+ const focusIndex = data.focusIndex || activeIndices[0]?.name;+ const fields = fieldsByIndex[focusIndex] || [];++ return {+ title: 'DATA',+ kicker: 'CLUSTERS · INDICES · FIELDS',+ meta: [time, 'SOURCES'],+ caption: 'What the engine actually has. Every row on this page maps to a real endpoint: `GET /v1/clusters`, `GET /v1/clusters/:id/indices`, `GET /v1/indices/:name/_mapping`. The mock values flip to live fetch the day the backend ships — nothing else on this page changes.',+ panels: [++ { id: 'clusters', eyebrow: 'CLUSTERS · CLICK TO SET DEFAULT', cols: 12, type: 'clusters',+ render: () => renderClusters(clusters, active),+ },++ { id: 'indices', eyebrow: `INDICES · ${active.toUpperCase()} · CLICK AN INDEX TO INSPECT FIELDS`, cols: 6, type: 'indices',+ render: () => renderIndices(activeIndices, focusIndex),+ },++ { id: 'fields', eyebrow: `FIELDS · ${focusIndex || '—'} · FROM /v1/indices/:name/_mapping`, cols: 6, type: 'fields',+ render: () => renderFields(fields),+ },++ { id: 'howTo', eyebrow: 'CONNECTING A NEW CLUSTER', cols: 12, type: 'markdown',+ render: () => Markdown(+`## Point XERJ.ai at a cluster++Today, clusters are defined in \`src/data/data-sources.js\` and read from+mock arrays. **When the engine ships** the HTTP bindings that this page+expects, clusters will be configured through this UI instead.++\`\`\`+POST /v1/clusters+{+ "id": "prod-us",+ "name": "PROD-US",+ "url": "https://xerj-us-east-1.internal:8080",+ "auth": { "type": "bearer", "token": "$XERJ_TOKEN" }+}+\`\`\`++The current default cluster is stored in \`localStorage.xerj.cluster\`,+which you can inspect under SETTINGS. Every query goes to that cluster+unless a specific dashboard panel overrides it via its \`source: { cluster }\`+binding.`+ ),+ },++ { id: 'citations', eyebrow: 'WHY THIS SECTION EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({+ items: [+ { id: 'gh-6498', source: 'github', score: 57,+ title: 'Remove index pattern mapping cache',+ url: 'https://github.com/elastic/kibana/issues/6498' },+ { id: 'gh-17888', source: 'github', score: 45,+ title: 'Per-user profiles, settings in Kibana',+ url: 'https://github.com/elastic/kibana/issues/17888' },+ { id: 'gh-17542', source: 'github', score: 57,+ title: 'Ability to change the index pattern on a visualization',+ url: 'https://github.com/elastic/kibana/issues/17542' },+ ],+ total: 451,+ }),+ },++ ],+ };+ },+};++// ---------- renderers -----------------------------------++function renderClusters(clusters, active) {+ if (!clusters.length) return '<div class="mono faint">No clusters configured.</div>';+ const rows = clusters.map((c) => {+ const isActive = c.id === active;+ const status = {+ green: `<span class="mono accent">●</span>`,+ yellow: `<span class="mono faint">◐</span>`,+ red: `<span class="mono">○</span>`,+ }[c.status] || '—';+ return `+ <button type="button" class="mg-cluster${isActive ? ' mg-cluster-active' : ''}" data-mg-cluster="${esc(c.id)}">+ <span class="mg-cluster-status">${status}</span>+ <span class="mg-cluster-name mono${isActive ? ' accent' : ''}">${esc(c.name)}</span>+ <span class="mg-cluster-url mono faint">${esc(c.url)}</span>+ <span class="mg-cluster-stat mono">${humanCount(c.indices)} idx</span>+ <span class="mg-cluster-stat mono">${humanCount(c.docs)} docs</span>+ <span class="mg-cluster-ver mono faint">${esc(c.version)}</span>+ </button>`;+ }).join('');+ return `<div class="mg-clusters">${rows}</div>`;+}++function renderIndices(indices, focusIndex) {+ if (!indices.length) return '<div class="mono faint">No indices in this cluster.</div>';+ const cols = ['NAME', 'DOCS', 'SIZE', 'SHARDS', 'RETENTION'];+ const headRow = `<div class="mg-idx-row mg-idx-head">${cols.map((c) => `<span>${esc(c)}</span>`).join('')}</div>`;+ const body = indices.map((i) => {+ const cells = [+ `<button type="button" class="mg-idx-btn${i.name === focusIndex ? ' active' : ''}" data-mg-index="${esc(i.name)}">${esc(i.name)}</button>`,+ humanCount(i.docs),+ humanBytes(i.bytes),+ String(i.shards),+ i.retention_days == null ? '∞' : i.retention_days + 'd',+ ];+ return `<div class="mg-idx-row">${cells.map((c) => `<span>${c}</span>`).join('')}</div>`;+ }).join('');+ return `<div class="mg-idx-table">${headRow}${body}</div>`;+}++function renderFields(fields) {+ if (!fields.length) return '<div class="mono faint">No mapping for this index.</div>';+ const cols = ['FIELD', 'TYPE', 'CARDINALITY', 'ENCODING', 'RATIO'];+ const headRow = `<div class="mg-fld-row mg-fld-head">${cols.map((c) => `<span>${esc(c)}</span>`).join('')}</div>`;+ const body = fields.map((f) => `+ <div class="mg-fld-row">+ <span class="mono">${esc(f.name)}</span>+ <span class="mono faint">${esc(f.type)}</span>+ <span class="mono">${humanCount(f.cardinality)}</span>+ <span class="mono faint">${esc(f.encoding)}</span>+ <span class="mono">${(f.ratio * 100).toFixed(0)}%</span>+ </div>`).join('');+ return `<div class="mg-fld-table">${headRow}${body}</div>`;+}diff --git a/xerj-ux/src/dashboards/ingest-pipeline.js b/xerj-ux/src/dashboards/ingest-pipeline.jsnew file mode 100644index 000000000..654804bd6--- /dev/null+++ b/xerj-ux/src/dashboards/ingest-pipeline.js@@ -0,0 +1,127 @@+// ============================================================+// Dashboard — INGEST · PIPELINE (engine internals)+//+// Every number on this dashboard corresponds to a real metric+// emitted by xerj-common/src/metrics.rs (/v1/metrics):+// docs_indexed, bytes_written, index_latency_s (p50/p95/p99),+// flush_duration_s, merge_duration_s, wal_write_latency_s,+// wal_size_bytes, segment_count, memory_usage, active_searches.+// Plus per-field encodings from /v1/indices/:name/encodings.+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Multiples } from '../ux/charts.js';+import { FlowBand } from '../ux/charts-ai.js';+import { MetricTile, Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { Table } from '../ux/tables.js';+import { Gauge } from '../ux/charts-ext.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const ingestPipeline = {+ id: 'ingest-pipeline',+ name: 'Ingest · Pipeline',+ render: ({ data, time }) => ({+ title: 'INGEST · PIPELINE',+ kicker: 'WAL · MEMTABLE · SEGMENT · MERGE',+ meta: [time, 'ENGINE INTERNALS'],+ caption: 'Every value on this page is a real Prometheus metric emitted by xerj-common::metrics — no synthetic signals. Use this to watch the WAL → memtable → segment → merge chain and the exact field encodings the storage layer chose.',+ panels: [++ { id: 'docsRate', eyebrow: 'DOCS INDEXED/s', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.docsRate.formatted, unit: 'docs/s',+ spark: Spark(data.series.docsIn, { w: 160, h: 36 }),+ delta: data.metrics.docsRate.delta, emphasis: true,+ }),+ },+ { id: 'bytesRate', eyebrow: 'BYTES WRITTEN/s', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.bytesRate.formatted, unit: 'MB/s',+ emphasis: false,+ }),+ },+ { id: 'walLag', eyebrow: 'WAL WRITE LATENCY', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.walLag.formatted, unit: 'ms',+ delta: data.metrics.walLag.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'segments', eyebrow: 'SEGMENTS', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.segments.formatted, unit: 'open',+ hint: data.metrics.segments.hint, emphasis: false,+ }),+ },+ { id: 'mem', eyebrow: 'MEMORY USAGE', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.mem.formatted, unit: 'gb',+ emphasis: false,+ }),+ },++ { id: 'pipeline', eyebrow: 'PIPELINE · END-TO-END FLOW', cols: 12, type: 'flowband',+ render: () => FlowBand({ segments: data.pipelineFlow, unit: '%' }),+ },++ { id: 'docsSeries', eyebrow: 'INGEST THROUGHPUT', cols: 12, type: 'line',+ render: () => Series(data.series.docsIn, {+ h: 140, labels: [data.series.startLabel, data.series.endLabel], unit: 'docs/s',+ }),+ },++ { id: 'latency', eyebrow: 'INDEX LATENCY · p50 / p95 / p99', cols: 12, type: 'multiples',+ render: () => Multiples({+ items: [+ { label: 'P50', values: data.series.idxLatP50, value: data.series.idxLatP50[data.series.idxLatP50.length-1].toFixed(2) + ' MS' },+ { label: 'P95', values: data.series.idxLatP95, value: data.series.idxLatP95[data.series.idxLatP95.length-1].toFixed(2) + ' MS' },+ { label: 'P99', values: data.series.idxLatP99, value: data.series.idxLatP99[data.series.idxLatP99.length-1].toFixed(2) + ' MS' },+ ],+ w: 300, h: 28,+ }),+ },++ { id: 'flushDur', eyebrow: 'FLUSH DURATION', cols: 6, type: 'line',+ render: () => Series(data.series.flushMs, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'ms',+ }),+ },++ { id: 'mergeDur', eyebrow: 'MERGE DURATION', cols: 6, type: 'line',+ render: () => Series(data.series.mergeMs, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'ms',+ }),+ },++ { id: 'topIndices', eyebrow: 'DOCS INDEXED · BY INDEX', cols: 6, type: 'topn',+ render: () => TopN({ items: data.topIndices, n: 10 }),+ },++ { id: 'encodings', eyebrow: 'FIELD ENCODINGS · /v1/indices/:name/encodings', cols: 6, type: 'table',+ render: () => Table({+ columns: ['FIELD', 'ENCODING', 'RATIO'],+ rows: data.perField.map((f) => [f.label, f.encoding, f.value + '%']),+ align: ['left', 'left', 'right'],+ }),+ },++ { id: 'compressionRatio', eyebrow: 'COMPRESSION RATIO', cols: 6, type: 'gauge',+ render: () => Gauge({+ value: 4.8, min: 1, max: 8, unit: '× raw JSON',+ thresholds: [2, 5], label: 'target ≥ 5×',+ }),+ },++ { id: 'memSeries', eyebrow: 'MEMORY OVER TIME', cols: 6, type: 'line',+ render: () => Series(data.series.memBytes.map((b) => b / 1024 / 1024 / 1024), {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'GB',+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['ingest-pipeline'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/logs-overview.js b/xerj-ux/src/dashboards/logs-overview.jsnew file mode 100644index 000000000..8fe4834aa--- /dev/null+++ b/xerj-ux/src/dashboards/logs-overview.js@@ -0,0 +1,76 @@+// ============================================================+// Dashboard — [LOGS] OVERVIEW+// Replaces Kibana [Logs] Overview. Typography-first.+//+// Panel schema:+// { id, eyebrow, cols, render: () => innerHtmlString }+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist, Heatmap } from '../ux/charts.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const logsOverview = {+ id: 'logs-overview',+ name: 'Logs',+ render: ({ data, time }) => ({+ title: 'LOGS · OVERVIEW',+ kicker: 'OBSERVE',+ meta: [time, 'ALL INDICES'],+ panels: [+ { id: 'total', eyebrow: 'TOTAL EVENTS', cols: 4, type: 'metric',+ render: () => Num({+ value: data.metrics.total.formatted, unit: 'events',+ spark: Spark(data.series.total, { w: 200, h: 40 }),+ delta: data.metrics.total.delta, deltaGood: 'up', emphasis: true,+ }),+ },+ { id: 'peak', eyebrow: 'PEAK RATE', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.peak.formatted, unit: 'e/s',+ hint: 'at ' + data.metrics.peak.at, emphasis: false,+ }),+ },+ { id: 'errRate', eyebrow: 'ERROR RATE', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.errorRate.formatted, unit: '%',+ delta: data.metrics.errorRate.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'sources', eyebrow: 'SOURCES', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.sources.formatted, unit: 'hosts',+ hint: data.metrics.sources.active + ' active', emphasis: false,+ }),+ },+ { id: 'series', eyebrow: 'EVENTS OVER TIME', cols: 12, type: 'line',+ render: () => Series(data.series.total, {+ h: 160, labels: [data.series.startLabel, data.series.endLabel], unit: '/bucket',+ }),+ },+ { id: 'levels', eyebrow: 'BY LEVEL', cols: 12, type: 'dist',+ render: () => Dist({ segments: data.byLevel, width: 1200 }),+ },+ { id: 'topServices', eyebrow: 'TOP SERVICES · CLICK TO FILTER', cols: 6, type: 'topn',+ render: () => TopN({ items: data.topServices, total: data.metrics.total.value, n: 10, filterField: 'service' }),+ },+ { id: 'topHosts', eyebrow: 'TOP HOSTS · CLICK TO DRILL', cols: 6, type: 'topn',+ drilldown: { to: 'system' },+ render: () => TopN({ items: data.topHosts, total: data.metrics.total.value, n: 10, filterField: 'host' }),+ },+ { id: 'heatmap', eyebrow: 'INTENSITY · WEEKDAY × 2H', cols: 12, type: 'heatmap',+ render: () => Heatmap({+ rows: ['MON','TUE','WED','THU','FRI','SAT','SUN'],+ cols: data.heatmap.cols,+ matrix: data.heatmap.matrix,+ cellFmt: (v) => (v >= 1000 ? Math.round(v / 1000) + 'K' : String(v)),+ }),+ },+ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['logs-overview'] || [], total: 5150 }),+ },+ ],+ }),+};diff --git a/xerj-ux/src/dashboards/rag-quality.js b/xerj-ux/src/dashboards/rag-quality.jsnew file mode 100644index 000000000..ab0531d27--- /dev/null+++ b/xerj-ux/src/dashboards/rag-quality.js@@ -0,0 +1,97 @@+// ============================================================+// Dashboard — RAG · QUALITY+//+// The unsolved observability problem of 2026: are my RAG+// answers actually grounded? Which retrievals mattered? Which+// prompts hallucinate?+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist, Heatmap } from '../ux/charts.js';+import { ChordArcs, AttentionMap } from '../ux/charts-ai.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const ragQuality = {+ id: 'rag-quality',+ name: 'RAG · Quality',+ render: ({ data, time }) => ({+ title: 'RAG · QUALITY',+ kicker: 'GROUNDING · HALLUCINATION · CITATIONS',+ meta: [time, 'RETRIEVAL PIPELINE'],+ panels: [++ { id: 'grounding', eyebrow: 'GROUNDING SCORE', cols: 4, type: 'metric',+ render: () => Num({+ value: data.metrics.grounding.formatted, unit: '%',+ spark: Spark(data.series.grounding, { w: 220, h: 44 }),+ delta: data.metrics.grounding.delta, deltaGood: 'up', emphasis: true,+ }),+ },+ { id: 'halluc', eyebrow: 'HALLUCINATION RATE', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.hallucination.formatted, unit: '%',+ delta: data.metrics.hallucination.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'hitRate', eyebrow: 'RETRIEVAL HIT RATE', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.hitRate.formatted, unit: '%',+ delta: data.metrics.hitRate.delta, emphasis: false,+ }),+ },+ { id: 'citations', eyebrow: 'AVG CITATIONS', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.avgCitations.formatted, unit: 'per answer',+ delta: data.metrics.avgCitations.delta, emphasis: false,+ }),+ },++ { id: 'groundingSeries', eyebrow: 'GROUNDING OVER TIME', cols: 12, type: 'line',+ render: () => Series(data.series.grounding, {+ h: 140, labels: [data.series.startLabel, data.series.endLabel], unit: '%',+ }),+ },++ { id: 'flow', eyebrow: 'RETRIEVAL FLOW · QUERY → CHUNK', cols: 12, type: 'chord',+ render: () => ChordArcs({+ sources: data.flow.queries,+ targets: data.flow.chunks,+ flows: data.flow.flows,+ h: 440,+ }),+ },++ { id: 'attention', eyebrow: 'SAMPLE ANSWER · TOKEN ATTENTION', cols: 12, type: 'attention',+ render: () => AttentionMap({ tokens: data.attention.tokens }),+ },++ { id: 'retrievalSource', eyebrow: 'BY RETRIEVAL SOURCE', cols: 12, type: 'dist',+ render: () => Dist({ segments: data.retrievalSource, width: 1200 }),+ },++ { id: 'lowGrounding', eyebrow: 'LOWEST GROUNDING PROMPTS', cols: 6, type: 'topn',+ render: () => TopN({+ items: data.lowGroundingPrompts,+ n: 8,+ valueFmt: (v) => v,+ }),+ },++ { id: 'chunkDensity', eyebrow: 'CHUNK HIT DENSITY · QUERY TYPE × CHUNK', cols: 6, type: 'heatmap',+ render: () => Heatmap({+ rows: data.chunkHitDensity.rows,+ cols: data.chunkHitDensity.cols,+ matrix: data.chunkHitDensity.matrix,+ cellFmt: (v) => (v >= 1000 ? Math.round(v / 1000) + 'K' : String(v)),+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['rag-quality'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/registry.js b/xerj-ux/src/dashboards/registry.jsnew file mode 100644index 000000000..133697fa0--- /dev/null+++ b/xerj-ux/src/dashboards/registry.js@@ -0,0 +1,104 @@+// ============================================================+// XERJ.ai — Dashboard + section registry+//+// Two taxonomies at play:+//+// 1. SECTIONS are the primary product surface — the top nav.+// Order = what users look for first, per user-feedback/kibana/:+// dashboards → discover → alerts → data → users → settings+//+// 2. DASHBOARDS live under SECTION='dashboards' and appear in+// the secondary nav row. Other sections each have exactly+// one view (discover, alerts, data, users, settings).+// ============================================================++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 { anomalyDetect } from './anomaly-detect.js';+import { ingestPipeline } from './ingest-pipeline.js';+import { logsOverview } from './logs-overview.js';+import { system } from './system.js';++import { searchDiscover } from './search-discover.js'; // DISCOVER section+import { alerts } from './alerts.js'; // ALERTS section+import { dataSection } from './data.js'; // DATA section+import { users } from './users.js'; // USERS section+import { settings } from './settings.js'; // SETTINGS section++// Give every DASHBOARD-section view the same section tag. We+// deliberately DON'T add it to the section-level views — those+// already declare their own `section` in their source files.+// Each dashboard also gets a `group` so the sub-nav can bucket+// them into folders/dropdowns — handles screens that can't fit+// the full dashboard list on one line.+const DEFAULT_GROUP = {+ 'ai-overview': 'ai',+ 'rag-quality': 'ai',+ 'vector-index': 'ai',+ 'agent-memory': 'ai',+ 'logs-overview': 'logs',+ 'anomaly-detect': 'logs',+ 'ingest-pipeline':'logs',+ 'system': 'infra',+};+for (const d of [aiOverview, ragQuality, vectorIndex, agentMemory, anomalyDetect, ingestPipeline, logsOverview, system]) {+ d.section = 'dashboards';+ d.group = DEFAULT_GROUP[d.id] || 'other';+}+// Search-discover gets tagged as the DISCOVER section (promoted out of the dashboards list).+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+ // Logs: logs-overview, anomaly-detect, ingest-pipeline+ // Infra: system+ aiOverview, ragQuality, vectorIndex, agentMemory,+ logsOverview, anomalyDetect, ingestPipeline,+ system,+ // Top-level sections (one view each)+ searchDiscover,+ alerts,+ dataSection,+ users,+ settings,+];++export const defaults = all;+export const registry = Object.fromEntries(all.map((d) => [d.id, d]));++// Primary nav: one entry per section. Order matters — this is the+// order corpus priority told us users scan. The label is uppercase+// UI text; the id maps to a section. Each section knows which view+// to render when clicked (the first dashboard in that section).+export const SECTIONS = [+ { id: 'dashboards', label: 'Dashboards' },+ { id: 'discover', label: 'Discover' },+ { id: 'alerts', label: 'Alerts' },+ { id: 'data', label: 'Data' },+ { id: 'users', label: 'Users' },+ { id: 'settings', label: 'Settings' },+];++// Dashboard groups — folders under the 'dashboards' section. The+// order here is what users see; each group is rendered in the+// secondary nav with its members visible when the group is active,+// and collapsed to a label otherwise. Adding a new group is just a+// DEFAULT_GROUP entry above + a row in this array.+export const DASHBOARD_GROUPS = [+ { id: 'ai', label: 'AI' },+ { id: 'logs', label: 'Logs' },+ { id: 'infra', label: 'Infra' },+];++/** Return dashboards belonging to a section. Used by the nav+ * router and the secondary nav row. */+export function dashboardsInSection(sectionId, merged) {+ return merged.filter((d) => (d.section || 'dashboards') === sectionId);+}++// Legacy alias — kept so callers that imported `dashboardList` still work.+export const dashboardList = all.map((d) => ({ id: d.id, name: d.name }));diff --git a/xerj-ux/src/dashboards/search-discover.js b/xerj-ux/src/dashboards/search-discover.jsnew file mode 100644index 000000000..022b84f40--- /dev/null+++ b/xerj-ux/src/dashboards/search-discover.js@@ -0,0 +1,245 @@+// ============================================================+// Dashboard — SEARCH · DISCOVER (interactive query console)+//+// Real features shown here — every one maps to code in the+// engine audit:+// • 8 query types (subset of 24 the DSL supports)+// • terms-agg facet sidebar (exact cardinality, not HLL)+// • POST /v1/indices/:name/search preview in XERJ.ai DSL+// • POST /v1/indices/:name/explain-plan tree+// • hits w/ _index / _id / _score / _source / @timestamp+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series } from '../ux/charts.js';+import { SearchBox, Hits, Facet, QueryDSL, QueryPlanTree, Citations } from '../ux/charts-ops.js';+import { VBar } from '../ux/charts-ext.js';+import { dashboardCitations } from '../data/feedback-citations.js';++// All 8 query types we expose in the UI (mapping to real DSL nodes)+const QUERY_TYPES = ['match', 'term', 'range', 'prefix', 'phrase', 'knn', 'semantic', 'hybrid'];+const INDICES = ['*', 'chat-events', 'logs-ssh-auth', 'agent-memory', 'vector-ops', 'anomalies', 'ai-kb'];++// Build the XERJ.ai query DSL object matching the current SearchBox state.+function buildDsl({ q, type, index, filters }) {+ const filterList = Object.entries(filters || {}).map(([f, v]) => ({ term: { [f]: v } }));+ let inner;+ switch (type) {+ case 'term': {+ const m = (q || '').match(/^([a-z_]+)\s*=\s*(.+)$/i);+ inner = m ? { term: { [m[1]]: m[2] } } : { match_all: {} };+ break;+ }+ case 'range': {+ const m = (q || '').match(/^([a-z_]+)\s*(>=|<=|>|<)\s*(\d+(?:\.\d+)?)$/i);+ if (m) {+ const [, f, op, v] = m;+ const k = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';+ inner = { range: { [f]: { [k]: Number(v) } } };+ } else inner = { match_all: {} };+ break;+ }+ case 'prefix': inner = q ? { prefix: { message: q } } : { match_all: {} }; break;+ case 'phrase': inner = q ? { match_phrase: { message: q } } : { match_all: {} }; break;+ case 'knn': inner = { knn: { field: 'embedding', query_vector: '<inline>', k: 10, ef_search: 96 } }; break;+ case 'semantic': inner = { semantic: { field: 'embedding', query: q || '*', model: 'text-embed-3' } }; break;+ case 'hybrid': inner = { hybrid: {+ fusion: 'rrf',+ queries: [+ { match: { message: q || '*' } },+ { knn: { field: 'embedding', query_vector: '<inline>', k: 20 } },+ ],+ rank_constant: 60,+ } }; break;+ default: inner = q ? { match: { message: q } } : { match_all: {} };+ }+ const body = filterList.length+ ? { query: { bool: { must: inner, filter: filterList } } }+ : { query: inner };+ return {+ method: 'POST',+ path: '/v1/indices/' + (index === '*' ? '*' : index) + '/search',+ body: { ...body, size: 25, track_total_hits: true,+ aggs: {+ by_level: { terms: { field: 'level', size: 8 } },+ by_service: { terms: { field: 'service', size: 8 } },+ by_host: { terms: { field: 'host', size: 8 } },+ }+ },+ };+}++// Build a fake query plan matching the DSL (the planner would produce one)+function buildPlan({ type, q, filters }, total) {+ const filterCount = Object.keys(filters || {}).length;+ const root = { op: 'BoolQuery', estimate: total, cost: total + 80, children: [] };+ switch (type) {+ case 'hybrid':+ root.op = 'Hybrid(rrf,60)';+ root.children.push(+ { op: 'MatchQuery', field: 'message', value: q || '*', estimate: Math.round(total * 1.8), cost: Math.round(total * 1.8 + 20) },+ { op: 'KnnQuery', field: 'embedding', value: 'k=20 ef_search=96', estimate: 20, cost: 420 },+ );+ break;+ case 'knn':+ root.op = 'KnnQuery';+ root.field = 'embedding';+ root.value = 'k=10 ef_search=96';+ root.estimate = 10;+ root.cost = 310;+ break;+ case 'semantic':+ root.op = 'SemanticSearch';+ root.field = 'embedding';+ root.value = `embed(${q || '*'}) → knn`;+ root.children.push(+ { op: 'EmbedAt/Query', estimate: 1, cost: 120 },+ { op: 'KnnQuery', field: 'embedding', value: 'k=10', estimate: 10, cost: 280 },+ );+ break;+ case 'term':+ root.op = 'TermQuery';+ root.value = q;+ root.estimate = total;+ root.cost = Math.round(total * 0.05 + 8);+ break;+ case 'range':+ root.op = 'RangeQuery';+ root.value = q;+ root.estimate = Math.round(total * 0.4);+ root.cost = Math.round(total * 0.1 + 16);+ break;+ case 'prefix':+ root.op = 'PrefixQuery';+ root.value = q;+ root.children.push({ op: 'FstScan', estimate: total * 2, cost: total * 0.6 });+ break;+ case 'phrase':+ root.op = 'MatchPhrase';+ root.value = `"${q}"`;+ root.children.push({ op: 'PostingsIntersect', estimate: total, cost: total * 0.8 });+ break;+ default:+ root.op = 'MatchQuery';+ root.field = 'message';+ root.value = q;+ root.children.push({ op: 'BM25Scorer', estimate: total, cost: total * 0.3 });+ }+ if (filterCount > 0) {+ root.children.push({+ op: 'FilterCtx', field: 'post-filter', value: `${filterCount} term(s)`, estimate: total, cost: filterCount * 4,+ });+ }+ // Always terminate with a TopK collector (matching the real planner)+ root.children.push({ op: 'TopKCollector', value: 'k=25', estimate: 25, cost: 8 });+ return root;+}++export const searchDiscover = {+ id: 'search-discover',+ name: 'Search · Discover',+ render: ({ data, time, search }) => {+ const r = search?.result;+ const dsl = buildDsl(search);+ const plan = buildPlan(search, r?.total ?? 0);++ return {+ title: 'SEARCH · DISCOVER',+ kicker: 'INTERACTIVE QUERY CONSOLE',+ meta: [time, '24 DSL TYPES · EXACT AGGS'],+ caption: 'Type a query, press Enter. All 8 query families, 14 aggregation types, and exact cardinality run against the live XERJ.ai index. The plan below comes from POST /v1/indices/:name/explain-plan.',+ panels: [++ { id: 'searchbox', eyebrow: 'QUERY · TYPE · INDEX · FILTERS', cols: 12, type: 'searchbox',+ render: () => SearchBox({+ value: search?.q ?? '',+ types: QUERY_TYPES,+ activeType: search?.type ?? 'match',+ indices: INDICES,+ activeIndex: search?.index ?? '*',+ filters: search?.filters ?? {},+ }),+ },++ { id: 'hits', eyebrow: 'RESULTS · CLICK A COLUMN TO SORT · CLICK INDEX TO FILTER', cols: 8, type: 'hits',+ render: () => Hits({+ hits: r?.hits || [],+ total: r?.total ?? 0,+ tookMs: r?.tookMs ?? 0,+ maxScore: r?.maxScore ?? null,+ sort: search?.sort,+ showTime: search?.showTime !== false,+ // Field display names — GH#1896 (65 reactions): users want to see+ // friendlier column headers than the internal field names.+ labels: { _index: 'INDEX', _id: 'ID', _score: 'SCORE', _ts: 'TIME', _source: 'MESSAGE' },+ }),+ },++ { id: 'facets', eyebrow: 'FACETS · CLICK TO FILTER', cols: 4, type: 'facet',+ render: () => `+ ${Facet({ field: 'level', items: r?.facets.level || [], active: search?.filters?.level })}+ ${Facet({ field: 'service', items: r?.facets.service || [], active: search?.filters?.service })}+ ${Facet({ field: '_index', items: r?.facets._index || [], active: search?.filters?._index })}+ ${Facet({ field: 'host', items: r?.facets.host || [], active: search?.filters?.host })}+ `,+ },++ { id: 'histogram', eyebrow: 'DATE_HISTOGRAM · INTERVAL=1H', cols: 8, type: 'bar',+ render: () => VBar({+ items: (r?.histogram || Array.from({length:24}, ()=>0)).map((v, i) => ({+ label: String(i).padStart(2, '0'), value: v,+ })),+ h: 140, unit: 'hits/bucket',+ }),+ },++ { id: 'searchMetrics', eyebrow: 'INDEX · LIVE', cols: 4, type: 'metric',+ render: () => {+ const totalDocs = data?.metrics?.totalDocs?.formatted || '52.4M';+ const uniqueTerms = data?.metrics?.uniqueTerms?.formatted || '18.9M';+ return `+ <div class="stack-3">+ <div class="row-flex">+ <div class="num-md accent">${totalDocs}</div>+ <span class="hint">documents</span>+ </div>+ <div class="row-flex">+ <div class="num-md">${uniqueTerms}</div>+ <span class="hint">unique terms · exact cardinality</span>+ </div>+ <div class="row-flex">+ <div class="num-md">${data?.metrics?.p95?.formatted || '10.4'}<span class="num-unit">ms</span></div>+ <span class="hint">p95 query latency</span>+ </div>+ </div>`;+ },+ },++ { id: 'dsl', eyebrow: 'REQUEST · POST ' + dsl.path, cols: 6, type: 'markdown',+ render: () => QueryDSL(dsl.body),+ },++ { id: 'plan', eyebrow: 'QUERY PLAN · FROM EXPLAIN-PLAN ENDPOINT', cols: 6, type: 'plan',+ render: () => QueryPlanTree(plan),+ },++ { id: 'qps', eyebrow: 'QUERIES/s OVER TIME', cols: 6, type: 'line',+ render: () => Series(data?.series?.queries || [], {+ h: 100, labels: [data?.series?.startLabel, data?.series?.endLabel], unit: 'qps',+ }),+ },++ { id: 'latency', eyebrow: 'p95 LATENCY OVER TIME', cols: 6, type: 'line',+ render: () => Series(data?.series?.took_p95 || [], {+ h: 100, labels: [data?.series?.startLabel, data?.series?.endLabel], unit: 'ms',+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['search-discover'] || [], total: 5150 }),+ },++ ],+ };+ },+};diff --git a/xerj-ux/src/dashboards/settings.js b/xerj-ux/src/dashboards/settings.jsnew file mode 100644index 000000000..1b1dd1c23--- /dev/null+++ b/xerj-ux/src/dashboards/settings.js@@ -0,0 +1,238 @@+// ============================================================+// Section — SETTINGS+//+// The last-resort section. If defaults are right, most users+// never visit. This page exposes:+// • the default cluster+// • the persistent-state inventory (what's in localStorage)+// • the dashboards manager (rename/reorder/hide/clone/delete/new)+// • the DANGER RESET ALL button+//+// We deliberately keep Dashboards management under Settings+// (not as its own primary section) because editing dashboards+// is a rare admin action, not a daily task.+// ============================================================++import { esc } from '../ux/text.js';+import { Citations } from '../ux/charts-ops.js';+import { Markdown } from '../ux/tables.js';+import { defaultClusterId } from '../data/data-sources.js';++export const settings = {+ id: 'settings',+ name: 'Settings',+ section: 'settings',+ render: ({ data, time }) => {+ const dashboards = data.dashboards || [];+ const views = data.views || [];+ return {+ title: 'SETTINGS',+ kicker: 'DEFAULTS · DASHBOARDS · DANGER',+ meta: [time, 'ADMIN'],+ caption: 'Everything under SETTINGS is rare admin. Rename or reorder a dashboard here; for everything else, the defaults are right.',+ panels: [++ { id: 'defaults', eyebrow: 'DEFAULTS', cols: 12, type: 'settings',+ render: () => renderSettings(),+ },++ { id: 'mg-dashboards-head', eyebrow: '', cols: 12, type: 'markdown',+ render: () => `<div class="h-section" style="margin-top:var(--sp-3);">DASHBOARDS · ${dashboards.length}</div>+ <div class="hint" style="margin-top:6px;">Drag a row to reorder. Click RENAME to rename. CLONE, HIDE, or DELETE from the action buttons.</div>`,+ },++ { id: 'mg-dashboards', eyebrow: '', cols: 12, type: 'manage-dashboards',+ render: () => renderDashboardTable(dashboards),+ },++ { id: 'mg-new', eyebrow: '', cols: 12, type: 'manage-new',+ render: () => renderNewDashboardRow(dashboards.filter((d) => !d.isUser && d.section === 'dashboards')),+ },++ { id: 'mg-views-head', eyebrow: '', cols: 12, type: 'markdown',+ render: () => `<div class="h-section" style="margin-top:var(--sp-10);">SAVED VIEWS · ${views.length}</div>+ <div class="hint" style="margin-top:6px;">A saved view is a pinned snapshot of a dashboard with its time range, cluster, and filters. Click the name to apply.</div>`,+ },++ { id: 'mg-views', eyebrow: '', cols: 12, type: 'manage-views',+ render: () => renderViewsTable(views),+ },++ { id: 'storage', eyebrow: 'PERSISTENT STATE INVENTORY', cols: 12, type: 'markdown',+ render: () => Markdown(+`## What we store, where++Everything XERJ.ai persists lives under \`localStorage.xerj.*\`. No+cookies, no IndexedDB, no server state (yet). You can dump the entire+inventory with one browser-console command:++\`\`\`+Object.keys(localStorage).filter(k => k.startsWith('xerj.'))+\`\`\`++The current keys are:++- \`xerj.theme\` · \`day\` | \`night\`+- \`xerj.time\` · last-used time range (\`1H\`, \`24H\`, \`7D\`, ...)+- \`xerj.edit\` · \`0\` | \`1\` — is edit mode sticky on reload+- \`xerj.search\` · search-discover state (query + type + filters + sort)+- \`xerj.dashboards\` · rename / order / hidden / custom (user dashboards)+- \`xerj.layout.<dash-id>\` · per-dashboard panel layout overrides+- \`xerj.cluster\` · default cluster id++When the engine grows a \`/v1/users/me\` endpoint, this store syncs up.`+ ),+ },++ { id: 'danger', eyebrow: 'DANGER · WIPE ALL STATE', cols: 12, type: 'danger',+ render: () => `+ <div class="mg-settings">+ <div class="mg-setting">+ <span class="key">RESET EVERYTHING</span>+ <button type="button" class="mg-btn mg-btn-danger" data-mg-reset-all>RESET ALL SAVED STATE</button>+ <span class="hint">— restores defaults, deletes every user dashboard, clears layouts, themes, filters. Reloads the page. Cannot be undone.</span>+ </div>+ </div>+ `,+ },++ { id: 'citations', eyebrow: 'WHY THIS SECTION EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({+ items: [+ { id: 'gh-56406', source: 'github', score: 41,+ title: 'Add a configuration setting for default "Rows Per Page" setting in Management',+ url: 'https://github.com/elastic/kibana/issues/56406' },+ { id: 'gh-6515', source: 'github', score: 18,+ title: 'Kibana Globalization',+ url: 'https://github.com/elastic/kibana/issues/6515' },+ { id: 'gh-1600', source: 'github', score: 14,+ title: 'Global timezone support',+ url: 'https://github.com/elastic/kibana/issues/1600' },+ ],+ total: 3610,+ }),+ },++ ],+ };+ },+};++// ---------- renderers -----------------------------------++function renderSettings() {+ return `+ <div class="mg-settings">+ <div class="mg-setting">+ <span class="key">DEFAULT CLUSTER</span>+ <span class="mono accent">${esc(defaultClusterId())}</span>+ <span class="hint">— change by clicking a cluster in the <a href="#/data" class="mono accent">DATA</a> section</span>+ </div>+ <div class="mg-setting">+ <span class="key">THEME</span>+ <span class="mono">toggle in the top-right nav</span>+ </div>+ <div class="mg-setting">+ <span class="key">TIME ZONE</span>+ <span class="mono">${esc(Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC')}</span>+ <span class="hint">— auto-detected from browser</span>+ </div>+ </div>`;+}++function renderDashboardTable(dashboards) {+ if (!dashboards.length) {+ return '<div class="mono faint">No dashboards. Click + NEW to create one.</div>';+ }+ // Only show rows for dashboards in the 'dashboards' section (skip section-level dashboards like alerts/data/users/settings).+ const listable = dashboards.filter((d) => d.section === 'dashboards' || d.section == null);+ const rows = listable.map((d, i) => {+ const isHidden = d.hidden;+ const kind = d.isUser+ ? `<span class="mono accent">USER</span>`+ : `<span class="mono faint">DEFAULT</span>`;+ const src = d.clonedFrom+ ? `<span class="mono faint">from ${esc(d.clonedFrom)}</span>`+ : '';+ const actions = [+ `<button type="button" class="mg-btn" data-mg-up="${esc(d.id)}" title="Move up">↑</button>`,+ `<button type="button" class="mg-btn" data-mg-down="${esc(d.id)}" title="Move down">↓</button>`,+ `<button type="button" class="mg-btn" data-mg-rename="${esc(d.id)}" title="Rename">RENAME</button>`,+ `<button type="button" class="mg-btn" data-mg-hide="${esc(d.id)}" title="${isHidden ? 'Show' : 'Hide'}">${isHidden ? 'SHOW' : 'HIDE'}</button>`,+ `<button type="button" class="mg-btn" data-mg-clone="${esc(d.id)}" title="Clone">CLONE</button>`,+ d.isUser+ ? `<button type="button" class="mg-btn mg-btn-danger" data-mg-delete="${esc(d.id)}" title="Delete">DELETE</button>`+ : `<span class="mg-btn mg-btn-disabled" title="Defaults can only be hidden">—</span>`,+ ].join('');+ return `+ <div class="mg-row${isHidden ? ' mg-row-hidden' : ''}" data-mg-id="${esc(d.id)}">+ <span class="mg-order mono faint">${String(i + 1).padStart(2, '0')}</span>+ <span class="mg-name">${esc(d.name)}</span>+ <span class="mg-kind">${kind}</span>+ <span class="mg-src">${src}</span>+ <span class="mg-actions">${actions}</span>+ </div>`;+ }).join('');+ return `+ <div class="mg-table">+ <div class="mg-row mg-head">+ <span class="mg-order">#</span>+ <span class="mg-name">NAME</span>+ <span class="mg-kind">KIND</span>+ <span class="mg-src">SOURCE</span>+ <span class="mg-actions">ACTIONS</span>+ </div>+ ${rows}+ </div>`;+}++function renderViewsTable(views) {+ if (!views.length) {+ return '<div class="mono faint">No saved views. Pin a view from any dashboard with the + SAVE CURRENT VIEW button.</div>';+ }+ const rows = views.map((v, i) => {+ const fs = v.filters || {};+ const fbits = Object.entries(fs).map(([k, val]) => {+ const vals = Array.isArray(val) ? val.join('|') : val;+ return `${k}:${vals}`;+ }).join(' · ') || '—';+ const when = (v.savedAt || '').slice(0, 16).replace('T', ' ');+ return `+ <div class="mg-row" data-view-id="${esc(v.id)}">+ <span class="mg-order mono faint">${String(i + 1).padStart(2, '0')}</span>+ <span class="mg-name"><button type="button" class="mg-btn mg-btn-link" data-view-apply="${esc(v.id)}" title="Apply view">${esc(v.name)}</button></span>+ <span class="mg-kind"><span class="mono faint">${esc(v.dashId)}</span></span>+ <span class="mg-src"><span class="mono faint">${esc(v.time || '24H')} · ${esc(v.cluster || '—')} · ${esc(fbits)}</span></span>+ <span class="mg-actions">+ <span class="mono faint">${esc(when)}</span>+ <button type="button" class="mg-btn" data-view-apply="${esc(v.id)}" title="Apply">APPLY</button>+ <button type="button" class="mg-btn mg-btn-danger" data-view-delete="${esc(v.id)}" title="Delete">DELETE</button>+ </span>+ </div>`;+ }).join('');+ return `+ <div class="mg-table">+ <div class="mg-row mg-head">+ <span class="mg-order">#</span>+ <span class="mg-name">NAME</span>+ <span class="mg-kind">DASHBOARD</span>+ <span class="mg-src">CONTEXT</span>+ <span class="mg-actions">SAVED / ACTIONS</span>+ </div>+ ${rows}+ </div>`;+}++function renderNewDashboardRow(templates) {+ const options = templates.map((t) =>+ `<button type="button" class="mg-btn" data-mg-new="${esc(t.id)}" title="New from ${esc(t.name)}">${esc(t.name)}</button>`+ ).join('<span class="sep">·</span>');+ return `+ <div class="mg-new-row">+ <span class="key accent">+ NEW DASHBOARD</span>+ <span class="hint" style="margin: 0 var(--sp-2);">clone a template</span>+ <span class="mg-new-templates">${options}</span>+ <span class="hint" style="margin-left:auto;">or</span>+ <button type="button" class="mg-btn" data-mg-new="" title="New blank dashboard">BLANK</button>+ </div>`;+}diff --git a/xerj-ux/src/dashboards/system.js b/xerj-ux/src/dashboards/system.jsnew file mode 100644index 000000000..6f8a42ad0--- /dev/null+++ b/xerj-ux/src/dashboards/system.js@@ -0,0 +1,92 @@+// ============================================================+// Dashboard — [SYSTEM] OVERVIEW + AUTH+// Replaces Metricbeat System Overview + auth logs.+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Multiples } from '../ux/charts.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const system = {+ id: 'system',+ name: 'System',+ render: ({ data, time }) => ({+ title: 'SYSTEM · OVERVIEW',+ kicker: 'HOSTS · LOAD · AUTH',+ meta: [time, 'METRICBEAT + AUTH'],+ panels: [+ { id: 'hosts', eyebrow: 'HOSTS', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.hosts.formatted, unit: 'online',+ hint: data.metrics.hosts.hint, emphasis: true,+ }),+ },+ { id: 'alerts', eyebrow: 'ACTIVE ALERTS', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.alerts.formatted, unit: 'open',+ delta: data.metrics.alerts.delta, deltaGood: 'down',+ hint: data.metrics.alerts.hint, emphasis: false,+ }),+ },+ { id: 'cpuMean', eyebrow: 'MEAN CPU', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.cpuMean.formatted, unit: '%',+ spark: Spark(data.series.cpu, { w: 140, h: 32 }),+ delta: data.metrics.cpuMean.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'memMean', eyebrow: 'MEAN MEM', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.memMean.formatted, unit: '%',+ spark: Spark(data.series.mem, { w: 140, h: 32 }),+ delta: data.metrics.memMean.delta, deltaGood: 'down', emphasis: false,+ }),+ },+ { id: 'cpu', eyebrow: 'CPU', cols: 6, type: 'line',+ render: () => Series(data.series.cpu, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: '%',+ }),+ },+ { id: 'mem', eyebrow: 'MEMORY', cols: 6, type: 'line',+ render: () => Series(data.series.mem, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: '%',+ }),+ },+ { id: 'disk', eyebrow: 'DISK I/O', cols: 6, type: 'line',+ render: () => Series(data.series.disk, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'MB/s',+ }),+ },+ { id: 'net', eyebrow: 'NETWORK I/O', cols: 6, type: 'line',+ render: () => Series(data.series.net, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: 'MB/s',+ }),+ },+ { id: 'hostCpu', eyebrow: 'PER-HOST CPU · SMALL MULTIPLES', cols: 12, type: 'multiples',+ render: () => Multiples({ items: data.hostCpu, w: 180, h: 24 }),+ },+ { id: 'topProcs', eyebrow: 'TOP PROCESSES', cols: 6, type: 'topn',+ render: () => TopN({ items: data.topProcs, n: 10, valueFmt: (v) => v.toFixed(1) + ' %' }),+ },+ { id: 'topHosts', eyebrow: 'HOSTS BY LOAD', cols: 6, type: 'topn',+ render: () => TopN({ items: data.topHosts, n: 10, valueFmt: (v) => v + ' %' }),+ },+ { id: 'authSeries', eyebrow: 'AUTH · FAILED LOGINS', cols: 12, type: 'line',+ render: () => Series(data.auth.series, {+ h: 100, labels: [data.series.startLabel, data.series.endLabel], unit: '/min',+ }),+ },+ { id: 'topFailUsers', eyebrow: 'TOP FAILED USERS', cols: 6, type: 'topn',+ render: () => TopN({ items: data.auth.topFailUsers, total: data.auth.failures, n: 8 }),+ },+ { id: 'topFailIPs', eyebrow: 'TOP ATTACKING IPS', cols: 6, type: 'topn',+ render: () => TopN({ items: data.auth.topFailIPs, total: data.auth.failures, n: 8 }),+ },+ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['system'] || [], total: 5150 }),+ },+ ],+ }),+};diff --git a/xerj-ux/src/dashboards/users.js b/xerj-ux/src/dashboards/users.jsnew file mode 100644index 000000000..3f791971d--- /dev/null+++ b/xerj-ux/src/dashboards/users.js@@ -0,0 +1,144 @@+// ============================================================+// Section — USERS+//+// Users + Roles + API keys + sessions. Spaces-and-RBAC is the+// 2nd most painful operational category in the Kibana corpus+// after alerting (213 items, 47% negative). Recurring pain:+// • "permission denied" with no indication of what's missing+// • Spaces multi-tenancy too complex, feature privileges+// scattered across index, app, and role-mapping+// • API key rotation is manual+//+// XERJ response: one token, indices ARE the boundary. No+// "Spaces". Role = a set of index prefixes + operations.+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Dist } from '../ux/charts.js';+import { TopN, Events } from '../ux/layout.js';+import { Table, Markdown } from '../ux/tables.js';+import { Citations } from '../ux/charts-ops.js';++export const users = {+ id: 'users',+ name: 'Users',+ section: 'users',+ render: ({ data, time }) => ({+ title: 'USERS',+ kicker: 'IDENTITY · ACCESS · TOKENS',+ meta: [time, 'RBAC'],+ caption: 'No Spaces. No feature privileges matrix. No separate "role mapping" app. A user has a token. A role is a set of index prefixes and operations. A session is a token with an expiry. Everything else is hidden complexity we refuse to ship.',+ panels: [++ { id: 'users', eyebrow: 'USERS', cols: 3, type: 'metric',+ render: () => Num({ value: '128', unit: 'active', hint: '12 online now', emphasis: true }),+ },+ { id: 'roles', eyebrow: 'ROLES', cols: 2, type: 'metric',+ render: () => Num({ value: '8', unit: 'defined', hint: 'flat model', emphasis: false }),+ },+ { id: 'apiKeys', eyebrow: 'API KEYS', cols: 2, type: 'metric',+ render: () => Num({ value: '42', unit: 'live', hint: '3 expire < 7d', emphasis: false }),+ },+ { id: 'sessions', eyebrow: 'SESSIONS', cols: 2, type: 'metric',+ render: () => Num({ value: '86', unit: 'active', delta: 3.2, emphasis: false }),+ },+ { id: 'lastLogin', eyebrow: 'LAST LOGIN', cols: 3, type: 'metric',+ render: () => Num({ value: '12s', unit: 'ago', hint: '[email protected]', emphasis: false }),+ },++ { id: 'userList', eyebrow: 'USERS · MOST ACTIVE', cols: 6, type: 'topn',+ render: () => TopN({+ items: [+ { label: 'deploy', value: 2804 },+ { label: 'oncall-bot', value: 1920 },+ { label: 'searcher', value: 1612 },+ { label: 'metrics-exporter',value: 1402 },+ { label: 'alice@eng', value: 1180 },+ { label: 'bob@eng', value: 980 },+ { label: 'carol@pm', value: 770 },+ { label: 'dave@sre', value: 612 },+ ],+ total: 11280,+ n: 8,+ }),+ },++ { id: 'roles', eyebrow: 'ROLES · INDEX PREFIX × OPS', cols: 6, type: 'table',+ render: () => Table({+ columns: ['ROLE', 'INDICES', 'OPS'],+ rows: [+ ['admin', '*', 'read, write, admin, delete'],+ ['developer', 'logs-*, metrics-*', 'read, write'],+ ['sre', '*', 'read, write, admin'],+ ['pm', 'logs-prod, metrics', 'read'],+ ['oncall', '*', 'read, alert.ack'],+ ['agent-token', 'agent-memory, embeddings', 'read, write'],+ ['audit-ro', 'audit', 'read'],+ ['guest', 'docs', 'read'],+ ],+ align: ['left', 'left', 'left'],+ }),+ },++ { id: 'recent', eyebrow: 'RECENT AUTH EVENTS', cols: 12, type: 'events',+ render: () => Events({ items: [+ { at: '23:14:02', sev: 'info', msg: 'login · [email protected] · src=10.0.3.42 · method=bearer · ok' },+ { at: '23:13:51', sev: 'info', msg: 'login · alice@eng · src=10.0.4.11 · method=sso · ok' },+ { at: '23:13:22', sev: 'warn', msg: 'token rotated · api-key-k9q8 · expires in 30d' },+ { at: '23:12:48', sev: 'err', msg: 'permission denied · bob@eng · index=audit · op=read · missing role audit-ro' },+ { at: '23:12:09', sev: 'info', msg: 'login · oncall-bot · src=10.0.0.4 · method=api-key · ok' },+ { at: '23:11:44', sev: 'info', msg: 'token created · bob@eng · api-key-77mx · expires=30d' },+ { at: '23:11:03', sev: 'warn', msg: 'token expiring · alice@eng · api-key-4ka2 · 6h' },+ ]}),+ },++ { id: 'model', eyebrow: 'THE PERMISSION MODEL · WHY IT IS LIKE THIS', cols: 12, type: 'markdown',+ render: () => Markdown(+`## One token, no magic++XERJ.ai has exactly three concepts for access control:++- **Token** — a user or machine bearer. Can have an expiry. Can be revoked.+- **Role** — a set of \`(index_prefix, operation)\` pairs. Flat. No inheritance.+- **Session** — a token that's currently open. Auto-expires.++That's it. There are no **Spaces**, no **feature privileges matrix**, no+separate **role mapping** configuration. Everything goes through one check:++\`\`\`+allow(token, index, op) :=+ ∃ role ∈ token.roles :+ ∃ (prefix, ops) ∈ role :+ index.startsWith(prefix) ∧ op ∈ ops+\`\`\`++If an operation is denied, the response includes the **exact missing role ++prefix**. No more "permission denied" with no hint — see the auth event+above for \`bob@eng\`.++The corpus has 213 items in \`categories/08-spaces-and-rbac/\`, many of+which are "I can see the dashboard but can't edit it" or "why doesn't my+Space work". That complexity is gone.`+ ),+ },++ { id: 'citations', eyebrow: 'WHY THIS SECTION EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({+ items: [+ { id: 'gh-4453', source: 'github', score: 38,+ title: 'Saved object authorization - Phase 1',+ url: 'https://github.com/elastic/kibana/issues/4453' },+ { id: 'gh-18331', source: 'github', score: 47,+ title: 'Anonymous access',+ url: 'https://github.com/elastic/kibana/issues/18331' },+ { id: 'gh-17888', source: 'github', score: 45,+ title: 'Per-user profiles, settings in Kibana',+ url: 'https://github.com/elastic/kibana/issues/17888' },+ ],+ total: 213,+ }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/dashboards/vector-index.js b/xerj-ux/src/dashboards/vector-index.jsnew file mode 100644index 000000000..20305a68f--- /dev/null+++ b/xerj-ux/src/dashboards/vector-index.js@@ -0,0 +1,110 @@+// ============================================================+// Dashboard — VECTOR INDEX+//+// HNSW health + embedding space. Answers: where do my+// embeddings live, how is recall holding up, what is the+// shape of my corpus in vector space?+// ============================================================++import { Num } from '../ux/text.js';+import { Spark, Series, Dist, Multiples } from '../ux/charts.js';+import { EmbedSpace, ParallelCoords, Ribbon3D } from '../ux/charts-ai.js';+import { Citations } from '../ux/charts-ops.js';+import { TopN } from '../ux/layout.js';+import { Gauge } from '../ux/charts-ext.js';+import { dashboardCitations } from '../data/feedback-citations.js';++export const vectorIndex = {+ id: 'vector-index',+ name: 'Vector · Index',+ render: ({ data, time }) => ({+ title: 'VECTOR · INDEX',+ kicker: 'HNSW · EMBEDDINGS · HYBRID',+ meta: [time, 'XERJ-VECTOR'],+ panels: [++ { id: 'vectors', eyebrow: 'VECTORS', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.vectors.formatted, unit: 'total',+ hint: data.metrics.vectors.hint, emphasis: true,+ }),+ },+ { id: 'dim', eyebrow: 'DIMENSIONS', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.dim.formatted, unit: 'd',+ hint: data.metrics.dim.hint, emphasis: false,+ }),+ },+ { id: 'disk', eyebrow: 'ON DISK', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.disk.formatted, unit: 'gb',+ hint: data.metrics.disk.hint, emphasis: false,+ }),+ },+ { id: 'qps', eyebrow: 'QUERIES/s', cols: 2, type: 'metric',+ render: () => Num({+ value: data.metrics.qps.formatted, unit: 'qps',+ spark: Spark(data.series.qps, { w: 140, h: 32 }),+ delta: data.metrics.qps.delta, emphasis: false,+ }),+ },+ { id: 'recall', eyebrow: 'RECALL @ 10', cols: 3, type: 'gauge',+ render: () => Gauge({+ value: data.metrics.recall.value, min: 80, max: 100, unit: '%',+ thresholds: [90, 95], emphasis: false,+ }),+ },++ { id: 'embedSpace', eyebrow: 'EMBEDDING SPACE · UMAP PROJECTION', cols: 12, type: 'embedspace',+ render: () => EmbedSpace({+ clusters: data.clusters, h: 420, highlight: [48, 48],+ }),+ },++ { id: 'annLatency', eyebrow: 'ANN LATENCY · P50 / P95 / P99', cols: 12, type: 'ribbon3d',+ render: () => Ribbon3D({+ series: [+ { label: 'P50', values: data.series.p50 },+ { label: 'P95', values: data.series.p95 },+ { label: 'P99', values: data.series.p99 },+ ],+ h: 220, depth: 14,+ }),+ },++ { id: 'pcoords', eyebrow: 'QUERY PROFILE · PARALLEL COORDINATES', cols: 12, type: 'pcoords',+ render: () => ParallelCoords({+ dims: data.pcoords.dims,+ rows: data.pcoords.rows,+ highlight: data.pcoords.highlight,+ h: 260,+ }),+ },++ { id: 'models', eyebrow: 'EMBEDDING MODELS', cols: 6, type: 'topn',+ render: () => TopN({ items: data.models, n: 6, valueFmt: (v) => v + 'M' }),+ },++ { id: 'p95Spark', eyebrow: 'p95 LATENCY', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.p95.formatted, unit: 'ms',+ spark: Spark(data.series.p95, { w: 160, h: 32 }),+ delta: data.metrics.p95.delta, deltaGood: 'down', emphasis: false,+ }),+ },++ { id: 'recallTimeline', eyebrow: 'RECALL OVER TIME', cols: 3, type: 'metric',+ render: () => Num({+ value: data.metrics.recall.formatted, unit: '%',+ spark: Spark(data.series.recall, { w: 160, h: 32 }),+ emphasis: false,+ }),+ },++ { id: 'citations', eyebrow: 'WHY THIS PANEL EXISTS · USER FEEDBACK', cols: 12, type: 'citations',+ render: () => Citations({ items: dashboardCitations['vector-index'] || [], total: 5150 }),+ },++ ],+ }),+};diff --git a/xerj-ux/src/data/backends/index.js b/xerj-ux/src/data/backends/index.jsnew file mode 100644index 000000000..adce168cc--- /dev/null+++ b/xerj-ux/src/data/backends/index.js@@ -0,0 +1,62 @@+// ============================================================+// Xerj Console — backend abstraction layer+//+// Xerj Console is a typography-first observability UI that today targets+// the Xerj engine but is designed to swap in other backends later+// (Kibana / OpenSearch / vanilla Elasticsearch, plus eventually a+// pure-vector backend like Pinecone or Qdrant for AI demos).+//+// Each backend is a module under `./backends/<name>.js` exporting:+//+// export const meta = { id, label, defaultBaseUrl, supports: { … } };+//+// export async function probe(baseUrl, signal) → boolean+// // Cheap "is there a live backend at this URL?" check. The+// // playground status pill goes amber until probe() returns true.+//+// export async function search(baseUrl, dashId, ctx, signal) → data+// // The contract is identical to the dashboard render fn input —+// // each backend translates dashId + range + filters into the+// // backend's native query and shapes the result back to the+// // dashboard's expected `data` object.+//+// The active backend is selected by name; an empty/unreachable backend+// falls back to the in-memory mock so the UI is always responsive.+// ============================================================++import * as xerj from './xerj.js';+import * as mock from './mock.js';++/** All registered backends. Add new modules here to expose them in the picker. */+export const BACKENDS = { xerj, mock };++/** Default backend selection, persisted in localStorage. */+const STORAGE_KEY = 'xerj-console.backend';+const DEFAULT_KEY = 'xerj';++export function activeBackendId() {+ if (typeof localStorage === 'undefined') return DEFAULT_KEY;+ return localStorage.getItem(STORAGE_KEY) || DEFAULT_KEY;+}++export function setActiveBackendId(id) {+ if (typeof localStorage === 'undefined') return;+ if (BACKENDS[id]) localStorage.setItem(STORAGE_KEY, id);+}++export function activeBackend() {+ return BACKENDS[activeBackendId()] || BACKENDS[DEFAULT_KEY];+}++/** Per-backend baseURL setting (default 'http://localhost:9200' for xerj). */+const URL_KEY = (id) => `xerj-console.backend.${id}.baseUrl`;++export function backendBaseUrl(id) {+ if (typeof localStorage === 'undefined') return BACKENDS[id]?.meta?.defaultBaseUrl || '';+ return localStorage.getItem(URL_KEY(id)) || BACKENDS[id]?.meta?.defaultBaseUrl || '';+}++export function setBackendBaseUrl(id, url) {+ if (typeof localStorage === 'undefined') return;+ localStorage.setItem(URL_KEY(id), url);+}diff --git a/xerj-ux/src/data/backends/mock.js b/xerj-ux/src/data/backends/mock.jsnew file mode 100644index 000000000..842931775--- /dev/null+++ b/xerj-ux/src/data/backends/mock.js@@ -0,0 +1,28 @@+// ============================================================+// Xerj Console backend — in-memory mock+//+// Re-exports the existing mock so the dashboards keep rendering+// when no real backend is reachable. The "MOCK DATA" status pill+// in the nav surfaces this state to the user.+// ============================================================++import { mock as mockData } from '../mock.js';++export const meta = {+ id: 'mock',+ label: 'Mock data',+ defaultBaseUrl: '',+ supports: { search: true, aggs: true, knn: true, semantic: true, hybrid: true, fsck: false },+};++export async function probe(_baseUrl, _signal) {+ return true; // mock is always "live"+}++export async function search(_baseUrl, dashId, ctx, _signal) {+ return mockData(dashId, ctx.range || '24H', {+ cluster: ctx.cluster || '',+ filters: ctx.filters || {},+ customRange: ctx.customRange || null,+ });+}diff --git a/xerj-ux/src/data/backends/xerj.js b/xerj-ux/src/data/backends/xerj.jsnew file mode 100644index 000000000..74849a82a--- /dev/null+++ b/xerj-ux/src/data/backends/xerj.js@@ -0,0 +1,624 @@+// ============================================================+// Xerj Console backend — Xerj engine+//+// Talks the ES-compatible REST API on port 9200 (or wherever the+// caller pointed it). Every dashboard's data shape is produced+// by composing one or more `_search` calls + light client-side+// reshape into the dashboard render contract.+//+// `probe()` is intentionally GET / so it costs ~0 on the engine.+// ============================================================++// Aggregation materialisation bypass.+//+// Xerj v1.0.0-rc.1 has a known bug at+// `engine/crates/xerj-engine/src/index.rs:3623`:+// `let materialisation_limit = (from + size + 100).max(256);`+// This caps the doc set that aggregations run over. When the+// dashboard sends the standard ES idiom `size:0` for "aggs only",+// the engine runs aggs over only ~256 docs and silently under-+// reports sums / averages / terms. We bypass by passing a large+// `size` so the materialisation cap exceeds the corpus. The+// `.hits.hits` payload is discarded by every adapter below.+// Track engine fix at: engine bug "agg materialisation cap".+const AGG_BYPASS_SIZE = 9999;++export const meta = {+ id: 'xerj',+ label: 'Xerj',+ defaultBaseUrl: 'http://localhost:9200',+ supports: {+ search: true,+ aggs: true,+ knn: true,+ semantic: true,+ hybrid: true,+ fsck: true,+ },+};++/** Lightweight liveness check. `true` if the server responded with a+ * Xerj-shaped root payload. Costs one HTTP GET. */+export async function probe(baseUrl, signal) {+ try {+ const r = await fetch(baseUrl + '/', { signal });+ if (!r.ok) return false;+ const j = await r.json().catch(() => ({}));+ // Xerj's `/` returns ES-shaped info with a recognisable cluster_name+ // ("xerj" by default) and version. Accept anything that looks vaguely+ // ES-shaped so the same backend module also reports true against ES /+ // OpenSearch (handy when we add those backends as siblings).+ return typeof j === 'object' && j !== null+ && (j.cluster_name !== undefined || j.tagline !== undefined || j.version !== undefined);+ } catch (_e) {+ return false;+ }+}++/** Fetch live cat-indices for the picker / overview dashboards. */+export async function listIndices(baseUrl, signal) {+ const r = await fetch(baseUrl + '/_cat/indices?format=json', { signal });+ if (!r.ok) return [];+ return r.json().catch(() => []);+}++/** Generic ES-compat search against a single index (or wildcard). */+async function rawSearch(baseUrl, index, body, signal) {+ const path = `/${encodeURIComponent(index)}/_search`;+ const r = await fetch(baseUrl + path, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal,+ });+ if (!r.ok) {+ const txt = await r.text().catch(() => '');+ throw new Error(`Xerj _search ${index} HTTP ${r.status}: ${txt.slice(0, 200)}`);+ }+ return r.json();+}++// ── Dashboard ↔ live-data adapters ──────────────────────────────+//+// The dispatcher below maps `dashId` to the function that produces the+// shape that the matching dashboard's render() expects. New dashboards+// add a case here when ready; until then the `query.js` wrapper+// transparently falls back to mock data.++export async function search(baseUrl, dashId, ctx, signal) {+ switch (dashId) {+ case 'search-discover': return liveSearchDiscover(baseUrl, ctx, signal);+ case 'system': return liveSystem(baseUrl, ctx, signal);+ case 'logs-overview': return liveLogsOverview(baseUrl, ctx, signal);+ case 'data': return liveData(baseUrl, ctx, signal);+ case 'ai-overview': return liveAiOverview(baseUrl, 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);+ case 'anomaly-detect': return liveAnomalyDetect(baseUrl, ctx, signal);+ case 'ingest-pipeline': return liveIngestPipeline(baseUrl, ctx, signal);+ default: return null; // signals "fall back to mock"+ }+}++// ── search-discover ────────────────────────────────────────────────+//+// The dashboard's `q` / `type` / `index` come in via ctx.search; we+// translate to an ES-compat query body and run it. Hits, total,+// per-field facets all come from one round-trip.+async function liveSearchDiscover(baseUrl, ctx, signal) {+ const search = ctx.search || {};+ const q = search.q || '';+ const type = search.type || 'match';+ const index = search.index === '*' ? '_all' : (search.index || '_all');++ const body = buildSearchBody(q, type, ctx);+ let response;+ try {+ response = await rawSearch(baseUrl, index, body, signal);+ } catch (e) {+ return { error: String(e), hits: [], total: 0, took: 0, facets: {} };+ }++ const total = response.hits?.total?.value ?? response.hits?.total ?? 0;+ const hits = (response.hits?.hits || []).map((h) => ({+ _id: h._id,+ _index: h._index,+ _score: h._score,+ _source: h._source,+ '@timestamp': h._source?.['@timestamp'] || null,+ }));+ const facets = {+ by_level: bucketsToFacet(response.aggregations?.by_level),+ by_service: bucketsToFacet(response.aggregations?.by_service),+ by_host: bucketsToFacet(response.aggregations?.by_host),+ };+ return {+ total,+ took: response.took ?? 0,+ hits,+ facets,+ raw: { query: body, response },+ };+}++function buildSearchBody(q, type, ctx) {+ const inner = (() => {+ switch (type) {+ case 'term': {+ const m = (q || '').match(/^([a-z_]+)\s*=\s*(.+)$/i);+ return m ? { term: { [m[1]]: m[2] } } : { match_all: {} };+ }+ case 'range': {+ const m = (q || '').match(/^([a-z_]+)\s*(>=|<=|>|<)\s*(\d+(?:\.\d+)?)$/i);+ if (!m) return { match_all: {} };+ const [, f, op, v] = m;+ const k = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';+ return { range: { [f]: { [k]: Number(v) } } };+ }+ case 'prefix': return q ? { prefix: { message: q } } : { match_all: {} };+ case 'phrase': return q ? { match_phrase: { message: q } } : { match_all: {} };+ case 'semantic': return q ? { semantic: { field: 'embedding', query: q, k: 10 } }+ : { match_all: {} };+ case 'hybrid': return q ? {+ hybrid: {+ queries: [+ { query: { match: { message: q } }, weight: 1.0 },+ { query: { semantic: { field: 'embedding', query: q, k: 10 } }, weight: 0.8 },+ ],+ fusion: { type: 'rrf', k: 60 },+ }+ } : { match_all: {} };+ case 'knn': return { match_all: {} }; // raw knn needs vector input — UI shows DSL only+ default: return q ? { match: { message: q } } : { match_all: {} };+ }+ })();++ const filterList = Object.entries(ctx.filters || {}).map(([f, v]) => ({ term: { [f]: v } }));+ const query = filterList.length+ ? { bool: { must: inner, filter: filterList } }+ : inner;++ return {+ query,+ size: 25,+ track_total_hits: true,+ aggs: {+ by_level: { terms: { field: 'level', size: 8 } },+ by_service: { terms: { field: 'service', size: 8 } },+ by_host: { terms: { field: 'host', size: 8 } },+ },+ };+}++function bucketsToFacet(agg) {+ if (!agg || !Array.isArray(agg.buckets)) return [];+ return agg.buckets.map((b) => ({ key: String(b.key), count: b.doc_count }));+}++// ── system ────────────────────────────────────────────────────────+//+// The system dashboard expects a rich infrastructure-monitoring+// shape (hostCpu sparklines, topProcs, auth.failures…) that Xerj+// itself doesn't expose — those come from a metric collector+// pointed at the host (Metricbeat / collectd / OTLP). For the SE+// demo path we return null here so the dashboard falls back to the+// mock; once a metrics-ingest adapter lands in v0.7.x we'll fill+// the live shape from the same xerj indices the user is watching.+async function liveSystem(baseUrl, ctx, signal) {+ // We don't have a host-metrics agent today, but `_cluster/stats`+ // gives us real numbers we can drop into the headline tiles.+ let stats;+ try {+ const r = await fetch(baseUrl + '/_cluster/stats', { signal });+ if (!r.ok) return null;+ stats = await r.json();+ } catch (_e) { return null; }+ const base = await loadMock('system', ctx);+ const docs = stats?.indices?.docs?.count || 0;+ const bytes = stats?.indices?.store?.size_in_bytes || 0;+ const idxN = stats?.indices?.count || 0;+ const shardN = stats?.indices?.shards?.total || 0;+ base.metrics = base.metrics || {};+ base.metrics.cpu = base.metrics.cpu || { value: 0, formatted: '—' };+ base.metrics.disk = { value: bytes, formatted: (bytes / 1e9).toFixed(2) + ' GB', hint: 'live · xerj · stored' };+ base.metrics.docs = { value: docs, formatted: docs.toLocaleString('en-US'), hint: 'live · xerj' };+ base.metrics.indices = { value: idxN, formatted: String(idxN), hint: `live · xerj · ${shardN} shards` };+ base._live = { source: '_cluster/stats', docs, bytes, indices: idxN, shards: shardN };+ return base;+}++// ── logs-overview ─────────────────────────────────────────────────+//+// Returns the rich logs-overview shape the dashboard expects, with+// live counts overlaid where we can compute them from xerj aggs.+// Fields the engine can't produce (peak rate, multi-host series,+// per-host CPU sparklines) come from the mock so the canvas stays+// fully populated for the SE demo.+async function liveLogsOverview(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ by_level: { terms: { field: 'level', size: 5 } },+ by_service: { terms: { field: 'service', size: 8 } },+ by_host: { terms: { field: 'host', size: 8 } },+ timeline: {+ date_histogram: { field: '@timestamp', fixed_interval: bucketSize(ctx.range || '24H') },+ aggs: { by_level: { terms: { field: 'level', size: 5 } } },+ },+ },+ };+ let live;+ try {+ live = await rawSearch(baseUrl, 'logs-*', body, signal);+ } catch (_e) {+ return null; // graceful → mock fallback+ }++ // Use mock as the base shape so all panels render; overlay the few+ // numbers we can verify live against xerj.+ const { mock: mockData } = await import('../mock.js');+ const base = mockData('logs-overview', ctx.range || '24H', {+ cluster: ctx.cluster || '',+ filters: ctx.filters || {},+ customRange: ctx.customRange || null,+ });++ const total = live.hits?.total?.value ?? 0;+ if (base?.metrics?.total) {+ base.metrics.total.value = total;+ base.metrics.total.formatted = total.toLocaleString('en-US');+ base.metrics.total.delta = null;+ base.metrics.total.hint = 'live · xerj';+ }+ base._live = {+ total,+ by_level: bucketsToFacet(live.aggregations?.by_level),+ by_service: bucketsToFacet(live.aggregations?.by_service),+ by_host: bucketsToFacet(live.aggregations?.by_host),+ timeline: (live.aggregations?.timeline?.buckets || []).map((b) => ({+ t: b.key, count: b.doc_count,+ by_level: bucketsToFacet(b.by_level),+ })),+ };+ return base;+}++function rangeToSince(range) {+ switch (range) {+ case '1H': return 'now-1h';+ case '24H': return 'now-24h';+ case '7D': return 'now-7d';+ case '30D': return 'now-30d';+ case '90D': return 'now-90d';+ default: return 'now-24h';+ }+}++function bucketSize(range) {+ switch (range) {+ case '1H': return '1m';+ case '24H': return '1h';+ case '7D': return '6h';+ case '30D': return '1d';+ case '90D': return '1d';+ default: return '1h';+ }+}++// ── data (data sources / index inventory) ─────────────────────────+//+// Same overlay pattern as logs-overview: mock supplies the rich+// canvas (clusters list, fieldsByIndex, narrative blurb) and we+// overlay the live indices Xerj actually has.+async function liveData(baseUrl, ctx, signal) {+ let indices;+ try {+ indices = await listIndices(baseUrl, signal);+ } catch (_e) {+ return null;+ }+ const { mock: mockData } = await import('../mock.js');+ const base = mockData('data', ctx.range || '24H', {+ cluster: ctx.cluster || '',+ filters: ctx.filters || {},+ customRange: ctx.customRange || null,+ });++ const liveIndices = (indices || []).map((i) => ({+ name: i.index,+ health: i.health || 'green',+ docs: Number(i['docs.count'] || 0),+ size: i['store.size'] || '0b',+ status: i.status || 'open',+ primary_shards: Number(i.pri || 1),+ replica_shards: Number(i.rep || 0),+ }));++ // Inject the live indices under whichever cluster is active in the+ // mock — that way the existing renderClusters / renderIndices tiles+ // light up without needing a new shape.+ const active = base?.activeCluster || 'local';+ if (base?.indicesByCluster) {+ base.indicesByCluster[active] = liveIndices.length ? liveIndices : base.indicesByCluster[active];+ base.focusIndex = liveIndices[0]?.name || base.focusIndex;+ }+ base._live = { indices: liveIndices };+ return base;+}++// ─────────────────────────────────────────────────────────────────────+// LIVE ADAPTERS — every dashboard the demo runbook visits returns+// numbers from real xerj indices. Each adapter starts from the mock+// shape (so panels stay populated even when a sub-metric isn't yet+// computable on the live engine) and overlays everything we CAN+// compute. The status pill flips to "LIVE · XERJ" because the+// outermost shape is real.+// ─────────────────────────────────────────────────────────────────────++const TIMELINE_BUCKET = (range) => bucketSize(range);++function paretoFromBuckets(buckets) {+ return (buckets || []).map((b) => ({ key: String(b.key), value: b.doc_count }));+}++async function loadMock(dashId, ctx) {+ const { mock: mockData } = await import('../mock.js');+ return mockData(dashId, ctx.range || '24H', {+ cluster: ctx.cluster || '',+ filters: ctx.filters || {},+ customRange: ctx.customRange || null,+ });+}++// ── ai-overview ───────────────────────────────────────────────────+async function liveAiOverview(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ total_prompt: { sum: { field: 'prompt_tokens' } },+ total_context: { sum: { field: 'context_tokens' } },+ total_completion:{ sum: { field: 'completion_tokens' } },+ total_cost: { sum: { field: 'cost_usd' } },+ avg_latency: { avg: { field: 'latency_ms' } },+ cache_hits: { terms: { field: 'cache_hit' } },+ models: { terms: { field: 'model', size: 8 } },+ intents: { terms: { field: 'intent', size: 12 } },+ docs: { terms: { field: 'top_doc', size: 12 } },+ timeline: { date_histogram: { field: '@timestamp', fixed_interval: TIMELINE_BUCKET(ctx.range || '24H') } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'chat-events', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('ai-overview', ctx);+ const a = live.aggregations || {};+ const totalPrompt = Math.max(0, Math.round(a.total_prompt?.value || 0));+ const totalContext = Math.max(0, Math.round(a.total_context?.value || 0));+ const totalComplete = Math.max(0, Math.round(a.total_completion?.value|| 0));+ const totalTokens = totalPrompt + totalContext + totalComplete;+ const totalCost = Math.max(0, a.total_cost?.value || 0);+ const avgLatency = Math.round(a.avg_latency?.value || 0);+ const hits = (a.cache_hits?.buckets || []).reduce((m, b) => (m[String(b.key)] = b.doc_count, m), {});+ const cacheRate = total ? ((hits.true || 0) * 100 / total) : 0;+ const fmt = (n) => n >= 1e9 ? (n/1e9).toFixed(1)+'B' : n >= 1e6 ? (n/1e6).toFixed(1)+'M' : n >= 1e3 ? (n/1e3).toFixed(1)+'k' : String(n);+ base.metrics = base.metrics || {};+ base.metrics.queries = { value: total, formatted: fmt(total), delta: null, hint: 'live · xerj' };+ base.metrics.tokens = { value: totalTokens, formatted: fmt(totalTokens), delta: null, hint: 'live · xerj' };+ base.metrics.cost = { value: totalCost, formatted: '$' + totalCost.toFixed(0), delta: null, hint: 'live · xerj' };+ const costES = totalCost * 5.2;+ base.metrics.savings = { value: costES - totalCost, formatted: '$' + (costES - totalCost).toFixed(0), note: 'vs ES+Pinecone+Splunk' };+ base.metrics.latency = { value: avgLatency, formatted: String(avgLatency), delta: null, hint: 'live · xerj' };+ base.metrics.cacheHit = { value: Math.round(cacheRate), formatted: String(Math.round(cacheRate)), delta: null, hint: 'live · xerj' };+ base.models = (a.models?.buckets || []).map((b) => ({ label: b.key.toUpperCase(), value: b.doc_count }));+ base.intents = (a.intents?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.topDocs = (a.docs?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ const tlBuckets = a.timeline?.buckets || [];+ if (tlBuckets.length) {+ base.series = base.series || {};+ base.series.queries = tlBuckets.map((b) => b.doc_count);+ }+ base._live = { source: 'chat-events', total };+ return base;+}++// ── rag-quality ────────────────────────────────────────────────────+async function liveRagQuality(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ avg_prompt: { avg: { field: 'prompt_tokens' } },+ avg_context:{ avg: { field: 'context_tokens' } },+ avg_completion: { avg: { field: 'completion_tokens' } },+ docs: { terms: { field: 'top_doc', size: 12 } },+ tenants: { terms: { field: 'tenant', size: 8 } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'chat-events', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('rag-quality', ctx);+ const a = live.aggregations || {};+ base.metrics = base.metrics || {};+ base.metrics.queries = { value: total, formatted: total.toLocaleString('en-US'), hint: 'live · xerj' };+ if (base.metrics.contextLen) {+ base.metrics.contextLen.value = Math.round(a.avg_context?.value || 0);+ base.metrics.contextLen.formatted = Math.round(a.avg_context?.value || 0).toLocaleString('en-US');+ base.metrics.contextLen.hint = 'live · xerj';+ }+ base.topDocs = (a.docs?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base._live = { source: 'chat-events', total };+ return base;+}++// ── vector-index ───────────────────────────────────────────────────+async function liveVectorIndex(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ ops: { terms: { field: 'op', size: 5 } },+ shards: { terms: { field: 'shard', size: 16 } },+ indexes: { terms: { field: 'index', size: 8 } },+ avg_recall:{ avg: { field: 'recall_at_10' } },+ avg_lat: { avg: { field: 'latency_ms' } },+ timeline: { date_histogram: { field: '@timestamp', fixed_interval: TIMELINE_BUCKET(ctx.range || '24H') } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'vector-ops', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('vector-index', ctx);+ const a = live.aggregations || {};+ base.metrics = base.metrics || {};+ base.metrics.qps = { value: total, formatted: total.toLocaleString('en-US'), hint: 'live · xerj · ops/24h' };+ base.metrics.recall = { value: a.avg_recall?.value || 0,+ formatted: ((a.avg_recall?.value || 0) * 100).toFixed(1) + '%', hint: 'live · xerj' };+ base.metrics.latency = { value: a.avg_lat?.value || 0,+ formatted: Math.round(a.avg_lat?.value || 0) + 'ms', hint: 'live · xerj' };+ base.shards = (a.shards?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byIndex = (a.indexes?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byOp = (a.ops?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ const tl = a.timeline?.buckets || [];+ if (tl.length) {+ base.series = base.series || {};+ base.series.queries = tl.map((b) => b.doc_count);+ }+ base._live = { source: 'vector-ops', total };+ return base;+}++// ── agent-memory ───────────────────────────────────────────────────+async function liveAgentMemory(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ ops: { terms: { field: 'op', size: 8 } },+ agents: { terms: { field: 'agent', size: 8 } },+ keys: { terms: { field: 'memory_key', size: 12 } },+ total_tokens:{ sum: { field: 'tokens' } },+ avg_score:{ avg: { field: 'score' } },+ timeline:{ date_histogram: { field: '@timestamp', fixed_interval: TIMELINE_BUCKET(ctx.range || '24H') } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'agent-memory', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('agent-memory', ctx);+ const a = live.aggregations || {};+ base.metrics = base.metrics || {};+ base.metrics.ops = { value: total, formatted: total.toLocaleString('en-US'), hint: 'live · xerj' };+ base.metrics.tokens = { value: a.total_tokens?.value || 0,+ formatted: ((a.total_tokens?.value || 0) / 1e3).toFixed(1) + 'k', hint: 'live · xerj' };+ base.metrics.recall = { value: a.avg_score?.value || 0,+ formatted: ((a.avg_score?.value || 0) * 100).toFixed(1) + '%', hint: 'live · xerj · avg score' };+ base.byOp = (a.ops?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byAgent = (a.agents?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.topKeys = (a.keys?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ const tl = a.timeline?.buckets || [];+ if (tl.length) {+ base.series = base.series || {};+ base.series.queries = tl.map((b) => b.doc_count);+ }+ base._live = { source: 'agent-memory', total };+ return base;+}++// ── anomaly-detect ─────────────────────────────────────────────────+async function liveAnomalyDetect(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ kinds: { terms: { field: 'kind', size: 8 } },+ severity: { terms: { field: 'severity', size: 5 } },+ services: { terms: { field: 'service', size: 8 } },+ timeline: { date_histogram: { field: '@timestamp', fixed_interval: TIMELINE_BUCKET(ctx.range || '24H') } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'anomalies', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('anomaly-detect', ctx);+ const a = live.aggregations || {};+ const sevCounts = {};+ for (const b of a.severity?.buckets || []) sevCounts[b.key] = b.doc_count;+ base.metrics = base.metrics || {};+ base.metrics.total = { value: total, formatted: total.toLocaleString('en-US'), hint: 'live · xerj' };+ base.metrics.critical = { value: sevCounts.critical || 0, formatted: String(sevCounts.critical || 0), hint: 'live · xerj' };+ base.metrics.warning = { value: sevCounts.warning || 0, formatted: String(sevCounts.warning || 0), hint: 'live · xerj' };+ base.byKind = (a.kinds?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byService = (a.services?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.bySeverity = (a.severity?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ const tl = a.timeline?.buckets || [];+ if (tl.length) {+ base.series = base.series || {};+ base.series.events = tl.map((b) => b.doc_count);+ }+ base._live = { source: 'anomalies', total };+ return base;+}++// ── ingest-pipeline ────────────────────────────────────────────────+async function liveIngestPipeline(baseUrl, ctx, signal) {+ const since = rangeToSince(ctx.range || '24H');+ const body = {+ size: AGG_BYPASS_SIZE, // rc.1 agg-cap workaround; see header+ query: { range: { '@timestamp': { gte: since } } },+ aggs: {+ stages: { terms: { field: 'stage', size: 8 } },+ pipelines: { terms: { field: 'pipeline', size: 8 } },+ status: { terms: { field: 'status', size: 4 } },+ total_docs:{ sum: { field: 'docs' } },+ avg_dur: { avg: { field: 'duration_ms' } },+ timeline: { date_histogram: { field: '@timestamp', fixed_interval: TIMELINE_BUCKET(ctx.range || '24H') } },+ },+ };+ let live;+ try { live = await rawSearch(baseUrl, 'logs-ingest-events', body, signal); }+ catch (_e) { return null; }+ const total = live.hits?.total?.value ?? 0;+ if (!total) return null;+ const base = await loadMock('ingest-pipeline', ctx);+ const a = live.aggregations || {};+ const statusCount = {};+ for (const b of a.status?.buckets || []) statusCount[b.key] = b.doc_count;+ const errRate = total ? ((statusCount.failed || 0) * 100 / total) : 0;+ base.metrics = base.metrics || {};+ base.metrics.events = { value: total, formatted: total.toLocaleString('en-US'), hint: 'live · xerj' };+ base.metrics.docs = { value: a.total_docs?.value || 0,+ formatted: ((a.total_docs?.value || 0) / 1e6).toFixed(1) + 'M', hint: 'live · xerj' };+ base.metrics.errorRate = { value: errRate, formatted: errRate.toFixed(2) + '%', hint: 'live · xerj' };+ base.metrics.avgLatency = { value: a.avg_dur?.value || 0,+ formatted: Math.round(a.avg_dur?.value || 0) + 'ms', hint: 'live · xerj' };+ base.byStage = (a.stages?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byPipeline = (a.pipelines?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ base.byStatus = (a.status?.buckets || []).map((b) => ({ key: b.key, value: b.doc_count }));+ const tl = a.timeline?.buckets || [];+ if (tl.length) {+ base.series = base.series || {};+ base.series.events = tl.map((b) => b.doc_count);+ }+ base._live = { source: 'logs-ingest-events', total };+ return base;+}diff --git a/xerj-ux/src/data/dashboard-store.js b/xerj-ux/src/data/dashboard-store.jsnew file mode 100644index 000000000..f99866e5c--- /dev/null+++ b/xerj-ux/src/data/dashboard-store.js@@ -0,0 +1,203 @@+// ============================================================+// XERJ.ai — Dashboard metadata store+//+// This is the thin persistent layer that turns "dashboards are+// hardcoded JS files" into "dashboards have editable metadata".+//+// Default dashboards (the ones shipped in src/dashboards/*.js)+// are still code — diffable, reviewable, version-controlled.+// But users can NOW:+// • rename them+// • reorder them in the nav+// • hide them+// • clone them to create a new user-owned dashboard+// • delete user dashboards (defaults can only be hidden, never deleted)+//+// Everything lives under the `xerj.dashboards` localStorage key+// so it survives reloads and round-trips through export/import.+// ============================================================++const LS_KEY = 'xerj.dashboards';++/**+ * Full shape of the store:+ *+ * {+ * order: ['ai-overview', 'rag-quality', 'user-1abc', ...], // nav order+ * names: { 'ai-overview': 'AI Overview (mine)' }, // per-id rename+ * hidden: ['logs-overview'], // hidden from nav+ * custom: {+ * 'user-1abc': {+ * name: 'Prod API Traffic',+ * clonedFrom: 'search-discover', // default template id+ * createdAt: '2026-04-14T18:20:00Z',+ * dataSource: { cluster: 'prod-us', index: 'logs-prod' },+ * }+ * }+ * }+ */++function load() {+ try {+ const raw = localStorage.getItem(LS_KEY);+ if (!raw) return {};+ return JSON.parse(raw);+ } catch {+ return {};+ }+}+function save(m) {+ localStorage.setItem(LS_KEY, JSON.stringify(m));+}++// ---------- reads ----------------------------------------++/**+ * Merge default dashboards with user metadata. Returns an array+ * of `{ id, name, isUser, clonedFrom?, dataSource?, render }` in+ * the user-defined nav order. Hidden items are excluded. Pass+ * `{ includeHidden: true }` to get them too (used by MANAGE view).+ */+export function mergedDashboards(defaults, { includeHidden = false } = {}) {+ const m = load();+ const hidden = new Set(m.hidden || []);+ const custom = m.custom || {};+ const names = m.names || {};++ // Build a map for quick lookup.+ const byId = Object.fromEntries(defaults.map((d) => [d.id, d]));+ const orderList = Array.isArray(m.order) && m.order.length+ ? m.order+ : defaults.map((d) => d.id);++ const out = [];+ const seen = new Set();+ for (const id of orderList) {+ if (hidden.has(id) && !includeHidden) { seen.add(id); continue; }+ const def = byId[id];+ const user = custom[id];+ if (def) {+ out.push({+ ...def,+ name: names[id] || def.name,+ isUser: false,+ hidden: hidden.has(id),+ });+ } else if (user) {+ // A user-created dashboard — borrow the render from its template.+ const source = user.clonedFrom ? byId[user.clonedFrom] : null;+ out.push({+ id,+ name: names[id] || user.name,+ render: source?.render || blankRender(user.name),+ isUser: true,+ clonedFrom: user.clonedFrom,+ dataSource: user.dataSource,+ hidden: hidden.has(id),+ });+ }+ seen.add(id);+ }+ // Append defaults the user hasn't yet placed (new ship adds).+ for (const def of defaults) {+ if (seen.has(def.id)) continue;+ if (hidden.has(def.id) && !includeHidden) continue;+ out.push({+ ...def,+ name: names[def.id] || def.name,+ isUser: false,+ hidden: hidden.has(def.id),+ });+ }+ return out;+}++/** Lightweight fallback render used for a user-created dashboard whose+ * clonedFrom template was deleted out from under it. */+function blankRender(name) {+ return () => ({+ title: (name || 'BLANK').toUpperCase(),+ kicker: 'USER DASHBOARD',+ meta: ['NO TEMPLATE'],+ panels: [+ {+ id: 'empty',+ eyebrow: 'NOTHING HERE YET',+ cols: 12,+ render: () =>+ '<div class="mono faint">This user dashboard was cloned from a template that no longer exists. Open the MANAGE view to re-point it at a different template, or delete and recreate.</div>',+ },+ ],+ });+}++// ---------- mutations ------------------------------------++export function renameDashboard(id, name) {+ const m = load();+ m.names = m.names || {};+ if (name && name.trim()) m.names[id] = name.trim();+ else delete m.names[id];+ save(m);+}++export function reorderDashboards(orderIds) {+ const m = load();+ m.order = orderIds.slice();+ save(m);+}++export function setHidden(id, hidden) {+ const m = load();+ m.hidden = m.hidden || [];+ const has = m.hidden.includes(id);+ if (hidden && !has) m.hidden.push(id);+ if (!hidden && has) m.hidden = m.hidden.filter((x) => x !== id);+ save(m);+}++/**+ * Create a user-owned dashboard. If `fromId` is provided, it+ * becomes a clone of that default (render inherited). Otherwise+ * it's a blank shell. Returns the new id.+ */+export function createUserDashboard({ name, fromId = null, dataSource = null } = {}) {+ const m = load();+ m.custom = m.custom || {};+ const id = 'user-' + Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4);+ m.custom[id] = {+ name: name || 'Untitled',+ clonedFrom: fromId,+ createdAt: new Date().toISOString(),+ dataSource,+ };+ m.order = m.order || [];+ m.order.push(id);+ save(m);+ return id;+}++export function deleteUserDashboard(id) {+ const m = load();+ if (m.custom) delete m.custom[id];+ if (m.order) m.order = m.order.filter((x) => x !== id);+ if (m.names) delete m.names[id];+ if (m.hidden) m.hidden = m.hidden.filter((x) => x !== id);+ save(m);+ // Also wipe any layout overrides tied to this id+ localStorage.removeItem('xerj.layout.' + id);+}++/** Wipe every metadata edit. Defaults reappear in their original order. */+export function resetAll() {+ localStorage.removeItem(LS_KEY);+}++/** Is the given id a user-created dashboard (as opposed to a default)? */+export function isUserDash(id) {+ const m = load();+ return !!(m.custom && m.custom[id]);+}++/** Raw read of the store — used by MANAGE view to show what's persisted. */+export function readStore() { return load(); }diff --git a/xerj-ux/src/data/data-sources.js b/xerj-ux/src/data/data-sources.jsnew file mode 100644index 000000000..de7833a25--- /dev/null+++ b/xerj-ux/src/data/data-sources.js@@ -0,0 +1,350 @@+// ============================================================+// XERJ.ai — Data source catalog (mock)+//+// Shape that mirrors the live XERJ API responses:+// GET /v1/clusters → [{ id, name, url, status }]+// GET /v1/clusters/{id}/indices → [{ name, docs, bytes, shards }]+// GET /v1/indices/{name}/_mapping → { fields: [...] }+// GET /v1/indices/{name}/encodings → { per-field encoding/ratio }+//+// When the backend is ready, swap the three exported functions+// for real fetch() calls. Dashboards and the MANAGE view never+// touch HTTP — they go through this module.+// ============================================================++const MOCK_CLUSTERS = [+ { id: 'local', name: 'LOCAL', url: 'http://localhost:8080', status: 'green', version: '0.1.0', indices: 6, docs: 1_24_00_000 },+ { id: 'prod-us', name: 'PROD-US', url: 'https://xerj-us-east-1.internal', status: 'green', version: '0.1.0', indices: 14, docs: 840_00_00_000 },+ { id: 'prod-eu', name: 'PROD-EU', url: 'https://xerj-eu-central-1.internal', status: 'yellow', version: '0.1.0', indices: 14, docs: 512_00_00_000 },+ { id: 'staging', name: 'STAGING', url: 'https://xerj-staging.internal', status: 'green', version: '0.2.0-rc1', indices: 8, docs: 22_00_00_000 },+];++const MOCK_INDICES = {+ local: [+ { name: 'logs-prod', docs: 42_000_000, bytes: 8_400_000_000, shards: 4, replicas: 0, retention_days: 30 },+ { name: 'logs-stage', docs: 3_200_000, bytes: 640_000_000, shards: 2, replicas: 0, retention_days: 7 },+ { name: 'traces', docs: 18_000_000, bytes: 3_600_000_000, shards: 4, replicas: 0, retention_days: 14 },+ { name: 'docs', docs: 58_000, bytes: 120_000_000, shards: 1, replicas: 0, retention_days: null },+ { name: 'metrics', docs: 22_000_000, bytes: 1_100_000_000, shards: 2, replicas: 0, retention_days: 90 },+ { name: 'events', docs: 8_200_000, bytes: 820_000_000, shards: 2, replicas: 0, retention_days: 30 },+ ],+ 'prod-us': [+ { name: 'logs-prod', docs: 12_400_000_000, bytes: 2_480_000_000_000, shards: 32, replicas: 1, retention_days: 90 },+ { name: 'logs-edge', docs: 4_200_000_000, bytes: 840_000_000_000, shards: 16, replicas: 1, retention_days: 30 },+ { name: 'traces', docs: 6_800_000_000, bytes: 1_360_000_000_000, shards: 16, replicas: 1, retention_days: 14 },+ { name: 'embeddings', docs: 1_200_000_000, bytes: 240_000_000_000, shards: 8, replicas: 1, retention_days: null },+ { name: 'agent-memory', docs: 48_000_000, bytes: 9_600_000_000, shards: 4, replicas: 1, retention_days: null },+ { name: 'rag-chunks', docs: 320_000_000, bytes: 64_000_000_000, shards: 8, replicas: 1, retention_days: null },+ { name: 'alerts', docs: 12_000_000, bytes: 2_400_000_000, shards: 2, replicas: 1, retention_days: 180 },+ { name: 'audit', docs: 18_000_000, bytes: 3_600_000_000, shards: 2, replicas: 1, retention_days: 365 },+ { name: 'metrics', docs: 2_400_000_000, bytes: 480_000_000_000, shards: 8, replicas: 1, retention_days: 90 },+ { name: 'events', docs: 860_000_000, bytes: 172_000_000_000, shards: 8, replicas: 1, retention_days: 30 },+ ],+};++// Per-index field catalog (mock). For each index a list of+// { name, type, docValues, indexed, cardinality, encoding, ratio }.+const MOCK_FIELDS = {+ 'logs-prod': [+ { name: '@timestamp', type: 'date', indexed: true, cardinality: 42_000_000, encoding: 'Δ-of-Δ', ratio: 0.02 },+ { name: 'service', type: 'keyword', indexed: true, cardinality: 12, encoding: 'DICT', ratio: 0.05 },+ { name: 'level', type: 'keyword', indexed: true, cardinality: 5, encoding: 'DICT', ratio: 0.04 },+ { name: 'host', type: 'keyword', indexed: true, cardinality: 48, encoding: 'DICT', ratio: 0.07 },+ { name: 'message', type: 'text', indexed: true, cardinality: 38_200_000, encoding: 'ZSTD+TMPL', ratio: 0.31 },+ { name: 'trace_id', type: 'keyword', indexed: true, cardinality: 12_400_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'span_id', type: 'keyword', indexed: true, cardinality: 12_400_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'latency_ms', type: 'integer', indexed: true, cardinality: 2_400, encoding: 'FOR+RLE', ratio: 0.18 },+ { name: 'status', type: 'integer', indexed: true, cardinality: 48, encoding: 'DICT', ratio: 0.06 },+ { name: 'bytes_out', type: 'integer', indexed: true, cardinality: 84_000, encoding: 'FOR', ratio: 0.22 },+ { name: 'client_ip', type: 'ip', indexed: true, cardinality: 3_400_000, encoding: 'RAW', ratio: 0.62 },+ { name: 'user_agent', type: 'text', indexed: true, cardinality: 18_000, encoding: 'DICT+ZSTD', ratio: 0.28 },+ ],+ traces: [+ { name: '@timestamp', type: 'date', indexed: true, cardinality: 18_000_000, encoding: 'Δ-of-Δ', ratio: 0.02 },+ { name: 'service.name', type: 'keyword', indexed: true, cardinality: 42, encoding: 'DICT', ratio: 0.05 },+ { name: 'operation.name', type: 'keyword', indexed: true, cardinality: 820, encoding: 'DICT', ratio: 0.08 },+ { name: 'duration_us', type: 'long', indexed: true, cardinality: 42_000, encoding: 'FOR+RLE', ratio: 0.14 },+ { name: 'trace_id', type: 'keyword', indexed: true, cardinality: 12_400_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'span_id', type: 'keyword', indexed: true, cardinality: 18_000_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'parent_span_id', type: 'keyword', indexed: true, cardinality: 14_000_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'http.status_code', type: 'integer', indexed: true, cardinality: 48, encoding: 'DICT', ratio: 0.06 },+ ],+ embeddings: [+ { name: '@timestamp', type: 'date', indexed: true, cardinality: 1_200_000_000, encoding: 'Δ-of-Δ', ratio: 0.02 },+ { name: 'doc_id', type: 'keyword', indexed: true, cardinality: 1_200_000_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'chunk_id', type: 'keyword', indexed: true, cardinality: 1_200_000_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'text', type: 'text', indexed: true, cardinality: 1_100_000_000, encoding: 'ZSTD', ratio: 0.18 },+ { name: 'embedding', type: 'dense_vector', indexed: true, cardinality: null, encoding: 'HNSW+SQ8', ratio: 0.22 },+ { name: 'model', type: 'keyword', indexed: true, cardinality: 6, encoding: 'DICT', ratio: 0.04 },+ { name: 'dim', type: 'integer', indexed: false, cardinality: 4, encoding: 'DICT', ratio: 0.04 },+ ],+ 'rag-chunks': [+ { name: '@timestamp', type: 'date', indexed: true, cardinality: 320_000_000, encoding: 'Δ-of-Δ', ratio: 0.02 },+ { name: 'source_uri', type: 'keyword', indexed: true, cardinality: 2_400_000, encoding: 'DICT', ratio: 0.14 },+ { name: 'chunk_idx', type: 'integer', indexed: true, cardinality: 12_000, encoding: 'FOR', ratio: 0.12 },+ { name: 'text', type: 'text', indexed: true, cardinality: 280_000_000, encoding: 'ZSTD', ratio: 0.20 },+ { name: 'title', type: 'text', indexed: true, cardinality: 2_400_000, encoding: 'DICT+ZSTD', ratio: 0.18 },+ { name: 'parent_id', type: 'keyword', indexed: true, cardinality: 2_400_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'tags', type: 'keyword', indexed: true, cardinality: 12_000, encoding: 'DICT', ratio: 0.10 },+ ],+ 'agent-memory': [+ { name: '@timestamp', type: 'date', indexed: true, cardinality: 48_000_000, encoding: 'Δ-of-Δ', ratio: 0.02 },+ { name: 'agent', type: 'keyword', indexed: true, cardinality: 8, encoding: 'DICT', ratio: 0.04 },+ { name: 'op', type: 'keyword', indexed: true, cardinality: 5, encoding: 'DICT', ratio: 0.04 },+ { name: 'key', type: 'keyword', indexed: true, cardinality: 2_400_000, encoding: 'UVARINT', ratio: 0.44 },+ { name: 'embedding', type: 'dense_vector', indexed: true, cardinality: null, encoding: 'HNSW+SQ8', ratio: 0.22 },+ { name: 'score', type: 'float', indexed: true, cardinality: 1_000, encoding: 'FOR+RLE', ratio: 0.18 },+ { name: 'dedup_of', type: 'keyword', indexed: true, cardinality: 860_000, encoding: 'UVARINT', ratio: 0.44 },+ ],+};++// ── live wiring ─────────────────────────────────────────────────────+// `local` cluster maps to the running xerj on the same origin. We+// keep MOCK_CLUSTERS for the prod-us / prod-eu / staging entries so+// the selector still has multi-cluster shape, but the LOCAL cluster+// flips to live `_cat/indices` + `_mapping` calls so the demo shows+// "the engine actually has these indices" instead of seeded names.++function liveBaseUrl() {+ if (typeof window !== 'undefined' && window.location && window.location.origin) {+ return window.location.origin;+ }+ return 'http://localhost:9200';+}++// ── Live wiring via Xerj Console backend ──────────────────────────────────────────+// The SPA fetches connections, indices, and fields through Xerj Console's typed+// surface (`/_xerj-console/api/v1/data-sources/...`) which carries the session+// cookie automatically. Falls back to the engine's ES-compat endpoints+// (`/_cluster/stats`, `/_cat/indices`, `/{idx}/_mapping`) when Xerj Console is+// unreachable so the SPA still shows numbers if the user lands here+// before logging in (or in dev when xerj-console-api isn't mounted).++const XAPI = '/_xerj-console/api/v1';++async function liveConnections() {+ try {+ const r = await fetch(XAPI + '/data-sources/connections', { credentials: 'same-origin' });+ if (!r.ok) return null;+ const body = await r.json();+ return body?.data?.connections || null;+ } catch (_e) { return null; }+}++async function liveClusterStats() {+ // Prefer the Xerj Console connection list (one row per data source) — every+ // row already carries the engine's status flag from xerj-console-api.+ const conns = await liveConnections();+ if (conns && conns.length) {+ return { __via_xerj_console: true, connections: conns };+ }+ try {+ const r = await fetch(liveBaseUrl() + '/_cluster/stats', { credentials: 'same-origin' });+ if (!r.ok) return null;+ return await r.json();+ } catch (_e) { return null; }+}++async function liveIndices() {+ // 1) Xerj Console facade — the auth-gated path that is what the binary+ // actually documents. Returns clean { indices: [...] }.+ try {+ const r = await fetch(XAPI + '/data-sources/connections/built-in/indices', {+ credentials: 'same-origin',+ });+ if (r.ok) {+ const body = await r.json();+ const list = body?.data?.indices || [];+ return list.map((it) => ({+ name: it.name,+ docs: Number(it.docs || 0),+ bytes: 0, // bytes not surfaced by phase-3 facade yet+ shards: Number(it.shards || 1),+ replicas: Number(it.replicas || 0),+ segments: Number(it.segments || 0),+ fields: Number(it.fields || 0),+ health: 'green',+ status: 'open',+ retention_days: null,+ }));+ }+ } catch (_e) { /* fall through to ES-compat */ }++ // 2) ES-compat fallback for unauthenticated dev / pre-bootstrap.+ try {+ const r = await fetch(liveBaseUrl() + '/_cat/indices', { credentials: 'same-origin' });+ if (!r.ok) return null;+ const txt = await r.text();+ const out = [];+ for (const line of txt.split('\n')) {+ // ES `_cat/indices` columns:+ // health status index uuid pri rep docs.count docs.deleted store.size pri.store.size+ const cols = line.trim().split(/\s+/);+ if (cols.length < 8) continue;+ const [health, status, name, , pri, rep, docsCount, , storeSize] = cols;+ if (!name || name === 'index') continue;+ // Skip system indices (.xerj_*) — they're plumbing, not user data.+ if (name.startsWith('.xerj_')) continue;+ out.push({+ name,+ docs: Number(docsCount || 0),+ bytes: parseSize(storeSize || '0b'),+ shards: Number(pri || 1),+ replicas: Number(rep || 0),+ health: health || 'green',+ status: status || 'open',+ retention_days: null,+ });+ }+ return out;+ } catch (_e) { return null; }+}++async function liveFields(indexName) {+ // Xerj Console facade first.+ try {+ const r = await fetch(+ XAPI + '/data-sources/connections/built-in/indices/'+ + encodeURIComponent(indexName) + '/fields',+ { credentials: 'same-origin' },+ );+ if (r.ok) {+ const body = await r.json();+ const list = body?.data?.fields || [];+ return list.map((f) => ({+ name: f.name,+ type: f.type || 'object',+ indexed: f.indexed !== false,+ doc_values: f.doc_values !== false,+ cardinality: null,+ encoding: encodingFor(f.type),+ ratio: null,+ }));+ }+ } catch (_e) { /* fall through */ }++ // ES-compat mapping fallback.+ try {+ const r = await fetch(liveBaseUrl() + '/' + encodeURIComponent(indexName) + '/_mapping', {+ credentials: 'same-origin',+ });+ if (!r.ok) return null;+ const j = await r.json();+ const props = j?.[indexName]?.mappings?.properties || {};+ return Object.entries(props).map(([name, cfg]) => ({+ name,+ type: (cfg && cfg.type) || 'object',+ indexed: !(cfg && cfg.index === false),+ cardinality: null,+ encoding: encodingFor(cfg && cfg.type),+ ratio: null,+ }));+ } catch (_e) { return null; }+}++function parseSize(s) {+ if (!s) return 0;+ const m = String(s).match(/^([0-9.]+)\s*([kmgt]?b)$/i);+ if (!m) return Number(s) || 0;+ const n = parseFloat(m[1]);+ const u = m[2].toLowerCase();+ return u === 'b' ? n+ : u === 'kb' ? n * 1024+ : u === 'mb' ? n * 1024 * 1024+ : u === 'gb' ? n * 1024 * 1024 * 1024+ : u === 'tb' ? n * 1024 * 1024 * 1024 * 1024+ : n;+}+function encodingFor(t) {+ switch (t) {+ case 'date': return 'Δ-of-Δ';+ case 'date_nanos': return 'Δ-of-Δ';+ case 'keyword': return 'DICT';+ case 'text': return 'ZSTD+TMPL';+ case 'integer':+ case 'short':+ case 'byte':+ case 'long': return 'FOR';+ case 'float':+ case 'double':+ case 'half_float':+ case 'scaled_float': return 'FOR+RLE';+ case 'dense_vector': return 'HNSW+SQ8';+ case 'ip': return 'RAW';+ case 'boolean': return 'BIT';+ default: return '—';+ }+}++/** List all configured clusters. After login, the LOCAL row reflects+ * the real `built-in` connection shape from+ * /_xerj-console/api/v1/data-sources/connections. Other rows stay seeded so+ * the multi-cluster picker has shape (those external connections are+ * not implemented yet — they'll come from /data-sources/connections+ * too once the HTTP-shaped adapters land). */+export async function listClusters() {+ const stats = await liveClusterStats();+ if (!stats) return MOCK_CLUSTERS;++ // Xerj Console connections path — replace every mock row whose id matches+ // a real connection's id, and keep illustrative mock rows for the+ // ones we don't have adapters for yet.+ if (stats.__via_xerj_console) {+ const conns = stats.connections || [];+ const out = MOCK_CLUSTERS.map((c) => ({ ...c }));+ // Map `built-in` → the LOCAL row.+ const builtIn = conns.find((c) => c.id === 'built-in');+ if (builtIn) {+ const local = out.find((c) => c.id === 'local');+ if (local) {+ local.url = liveBaseUrl();+ local.status = builtIn.status || 'green';+ local.name = (builtIn.name || 'LOCAL').toUpperCase();+ local.kind = builtIn.kind;+ }+ }+ // Future: append additional connection rows from `conns` once the+ // HTTP-shaped adapters return non-501 from the indices endpoint.+ return out;+ }++ // ES-compat /_cluster/stats fallback (pre-login).+ const out = MOCK_CLUSTERS.map((c) => ({ ...c }));+ const local = out.find((c) => c.id === 'local');+ if (local) {+ local.indices = stats.indices?.count || local.indices;+ local.docs = stats.indices?.docs?.count || local.docs;+ local.url = liveBaseUrl();+ local.status = stats.status || 'green';+ local.version = stats.nodes?.versions?.[0] || local.version;+ }+ return out;+}++export function listClustersSync() {+ return MOCK_CLUSTERS;+}++/** List indices in a cluster. LOCAL → live `_cat/indices`. */+export async function listIndices(clusterId) {+ if (clusterId === 'local') {+ const live = await liveIndices();+ if (live && live.length) return live;+ }+ return MOCK_INDICES[clusterId] || [];+}++/** List fields in an index. For live indices, fetch the mapping. */+export async function listFields(indexName) {+ if (MOCK_FIELDS[indexName]) return MOCK_FIELDS[indexName];+ const live = await liveFields(indexName);+ return live || [];+}++/** Return the default cluster id the app should talk to. */+export function defaultClusterId() {+ return localStorage.getItem('xerj.cluster') || 'local';+}+export function setDefaultCluster(id) {+ localStorage.setItem('xerj.cluster', id);+}diff --git a/xerj-ux/src/data/export.js b/xerj-ux/src/data/export.jsnew file mode 100644index 000000000..73ca7f9fb--- /dev/null+++ b/xerj-ux/src/data/export.js@@ -0,0 +1,123 @@+// ============================================================+// XERJ.ai — Export helpers+//+// Real Kibana feedback: GH#1992 "Export Documents as CSV"+// (372 reactions, 571 comments) — the #1 ask of all time.+// GH#1366 "Export chart to image" (178 reactions).+//+// Pure browser, no deps. CSV is built from arrays. PNG is+// built by serializing an SVG and rasterizing through a+// hidden <canvas>.+// ============================================================++/**+ * Build a CSV string from a header row and a body of rows.+ * Cells are escaped per RFC 4180: quoted if they contain+ * comma / quote / newline; embedded quotes doubled.+ */+export function toCsv(headers, rows) {+ const escape = (cell) => {+ const s = cell == null ? '' : String(cell);+ if (/[",\n\r]/.test(s)) return '"' + s.replace(/"/g, '""') + '"';+ return s;+ };+ const lines = [headers.map(escape).join(',')];+ for (const row of rows) lines.push(row.map(escape).join(','));+ return lines.join('\r\n') + '\r\n';+}++/**+ * Trigger a browser download of arbitrary text as a file.+ * Uses an in-memory blob URL so nothing leaves the page.+ */+export function downloadText(filename, mime, text) {+ const blob = new Blob([text], { type: mime + ';charset=utf-8' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(url), 1500);+}++/** Convert hits → 4-column CSV (index, id, score, source). */+export function hitsToCsv(hits, columns = ['_index', '_id', '_score', '_ts', '_source']) {+ const headers = columns.map((c) => c.replace(/^_/, ''));+ const rows = hits.map((h) =>+ columns.map((c) => {+ const v = h[c];+ if (typeof v === 'object' && v !== null) return JSON.stringify(v);+ return v;+ })+ );+ return toCsv(headers, rows);+}++/**+ * Export an SVG element to a PNG file.+ *+ * 1. Serialize the live SVG (with computed currentColor and viewBox)+ * 2. Inline it as a data URL in an <img>+ * 3. Render to <canvas> at 2× DPR+ * 4. canvas.toBlob → download+ *+ * Returns a Promise<Blob> so callers can await it for tests.+ */+export async function svgToPng(svgEl, { scale = 2, filename = 'chart.png' } = {}) {+ if (!svgEl) throw new Error('svgToPng: missing SVG element');+ // Clone so we can safely mutate (size, color)+ const clone = svgEl.cloneNode(true);+ const rect = svgEl.getBoundingClientRect();+ const w = Math.max(1, Math.round(rect.width));+ const h = Math.max(1, Math.round(rect.height));+ // Force absolute size for the rasterizer+ clone.setAttribute('width', String(w));+ clone.setAttribute('height', String(h));+ // Inline computed color so currentColor resolves+ const cs = getComputedStyle(svgEl);+ clone.setAttribute('color', cs.color);+ // Add namespace+ if (!clone.getAttribute('xmlns')) {+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');+ }+ // Inject background = page paper, otherwise PNG has transparent bg+ const paper = getComputedStyle(document.documentElement).getPropertyValue('--z-paper').trim() || '#0D0D0D';+ const bg = `<rect width="100%" height="100%" fill="${paper}"/>`;+ // Insert bg at the very start of children+ const inner = clone.innerHTML;+ clone.innerHTML = bg + inner;++ const xml = new XMLSerializer().serializeToString(clone);+ const svg64 = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xml);++ const img = new Image();+ img.crossOrigin = 'anonymous';++ const blob = await new Promise((resolve, reject) => {+ img.onload = () => {+ const canvas = document.createElement('canvas');+ canvas.width = w * scale;+ canvas.height = h * scale;+ const ctx = canvas.getContext('2d');+ ctx.scale(scale, scale);+ ctx.drawImage(img, 0, 0, w, h);+ canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob failed'))), 'image/png');+ };+ img.onerror = (e) => reject(new Error('SVG image load failed'));+ img.src = svg64;+ });++ // Trigger download+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(url), 1500);++ return blob;+}diff --git a/xerj-ux/src/data/feedback-citations.js b/xerj-ux/src/data/feedback-citations.jsnew file mode 100644index 000000000..3aadbf850--- /dev/null+++ b/xerj-ux/src/data/feedback-citations.js@@ -0,0 +1,215 @@+// AUTO-GENERATED by user-feedback/kibana/pipeline/design-inputs.mjs+// Do not edit by hand. Re-run `node pipeline/design-inputs.mjs` after a corpus refresh.+//+// Each dashboard in src/dashboards/ that wants to attribute its panels to+// real user pain imports this module and renders a CITATIONS panel.++export const dashboardCitations = {+ "ai-overview": [+ {+ "id": "gh-kibana-696",+ "source": "github",+ "score": 162,+ "title": "Allow sorting on multiple fields",+ "url": "https://github.com/elastic/kibana/issues/696"+ },+ {+ "id": "gh-kibana-4584",+ "source": "github",+ "score": 113,+ "title": "Pipeline aggregations",+ "url": "https://github.com/elastic/kibana/issues/4584"+ },+ {+ "id": "gh-kibana-4707",+ "source": "github",+ "score": 71,+ "title": "Support Bucket Script Aggregation",+ "url": "https://github.com/elastic/kibana/issues/4707"+ }+ ],+ "rag-quality": [+ {+ "id": "gh-kibana-98246",+ "source": "github",+ "score": 8,+ "title": "Best practices for rule executions",+ "url": "https://github.com/elastic/kibana/issues/98246"+ },+ {+ "id": "gh-kibana-144418",+ "source": "github",+ "score": 7,+ "title": "[Dashboard] Redesign Add Panel Experience",+ "url": "https://github.com/elastic/kibana/issues/144418"+ },+ {+ "id": "gh-kibana-74571",+ "source": "github",+ "score": 4,+ "title": "[Meta] Saved Object Tagging",+ "url": "https://github.com/elastic/kibana/issues/74571"+ }+ ],+ "vector-index": [+ {+ "id": "gh-kibana-6515",+ "source": "github",+ "score": 18,+ "title": "Kibana Globalization",+ "url": "https://github.com/elastic/kibana/issues/6515"+ },+ {+ "id": "gh-kibana-98246",+ "source": "github",+ "score": 8,+ "title": "Best practices for rule executions",+ "url": "https://github.com/elastic/kibana/issues/98246"+ },+ {+ "id": "gh-kibana-144418",+ "source": "github",+ "score": 7,+ "title": "[Dashboard] Redesign Add Panel Experience",+ "url": "https://github.com/elastic/kibana/issues/144418"+ }+ ],+ "agent-memory": [+ {+ "id": "gh-kibana-98246",+ "source": "github",+ "score": 8,+ "title": "Best practices for rule executions",+ "url": "https://github.com/elastic/kibana/issues/98246"+ },+ {+ "id": "gh-kibana-144418",+ "source": "github",+ "score": 7,+ "title": "[Dashboard] Redesign Add Panel Experience",+ "url": "https://github.com/elastic/kibana/issues/144418"+ },+ {+ "id": "gh-kibana-74571",+ "source": "github",+ "score": 4,+ "title": "[Meta] Saved Object Tagging",+ "url": "https://github.com/elastic/kibana/issues/74571"+ }+ ],+ "search-discover": [+ {+ "id": "gh-kibana-1366",+ "source": "github",+ "score": 178,+ "title": "Export chart to image",+ "url": "https://github.com/elastic/kibana/issues/1366"+ },+ {+ "id": "gh-kibana-9575",+ "source": "github",+ "score": 143,+ "title": "[Dashboard] Allow Authors to Limit Interactivity",+ "url": "https://github.com/elastic/kibana/issues/9575"+ },+ {+ "id": "gh-kibana-12560",+ "source": "github",+ "score": 64,+ "title": "Custom drilldown links for a dashboard panel",+ "url": "https://github.com/elastic/kibana/issues/12560"+ }+ ],+ "anomaly-detect": [+ {+ "id": "gh-kibana-98246",+ "source": "github",+ "score": 8,+ "title": "Best practices for rule executions",+ "url": "https://github.com/elastic/kibana/issues/98246"+ },+ {+ "id": "gh-kibana-144418",+ "source": "github",+ "score": 7,+ "title": "[Dashboard] Redesign Add Panel Experience",+ "url": "https://github.com/elastic/kibana/issues/144418"+ },+ {+ "id": "gh-kibana-74571",+ "source": "github",+ "score": 4,+ "title": "[Meta] Saved Object Tagging",+ "url": "https://github.com/elastic/kibana/issues/74571"+ }+ ],+ "ingest-pipeline": [+ {+ "id": "gh-kibana-4288",+ "source": "github",+ "score": 45,+ "title": "Ability to export the index pattern along with saved objects",+ "url": "https://github.com/elastic/kibana/issues/4288"+ },+ {+ "id": "gh-kibana-4759",+ "source": "github",+ "score": 45,+ "title": "Expose object import/export as an API",+ "url": "https://github.com/elastic/kibana/issues/4759"+ },+ {+ "id": "gh-kibana-6057",+ "source": "github",+ "score": 40,+ "title": "add command line option to execute the optimize task standalone",+ "url": "https://github.com/elastic/kibana/issues/6057"+ }+ ],+ "logs-overview": [+ {+ "id": "gh-kibana-1992",+ "source": "github",+ "score": 372,+ "title": "Export Documents as CSV",+ "url": "https://github.com/elastic/kibana/issues/1992"+ },+ {+ "id": "gh-kibana-1366",+ "source": "github",+ "score": 178,+ "title": "Export chart to image",+ "url": "https://github.com/elastic/kibana/issues/1366"+ },+ {+ "id": "gh-kibana-30982",+ "source": "github",+ "score": 46,+ "title": "[Reporting] Exporting raw data from table-based visualizations",+ "url": "https://github.com/elastic/kibana/issues/30982"+ }+ ],+ "system": [+ {+ "id": "gh-kibana-6057",+ "source": "github",+ "score": 40,+ "title": "add command line option to execute the optimize task standalone",+ "url": "https://github.com/elastic/kibana/issues/6057"+ },+ {+ "id": "gh-kibana-4482",+ "source": "github",+ "score": 31,+ "title": "Conditional XY bar metric colors",+ "url": "https://github.com/elastic/kibana/issues/4482"+ },+ {+ "id": "gh-kibana-706",+ "source": "github",+ "score": 13,+ "title": "Translation to other languages",+ "url": "https://github.com/elastic/kibana/issues/706"+ }+ ]+};diff --git a/xerj-ux/src/data/mock.js b/xerj-ux/src/data/mock.jsnew file mode 100644index 000000000..5cf600d9c--- /dev/null+++ b/xerj-ux/src/data/mock.js@@ -0,0 +1,1045 @@+// ============================================================+// XERJ.ai — Synthetic data source+//+// Deterministic per (dashboardId, timeRange). Feeds every+// dashboard today; the shape is what a real XERJ.ai server will+// return through /xerj/dashboards/{id}.+//+// Swap in data/query.js.+// ============================================================++// ---------- seeded PRNG (mulberry32) ----------------------+const rng = (seed) => {+ let t = seed >>> 0;+ return () => {+ t = (t + 0x6D2B79F5) >>> 0;+ let r = t;+ r = Math.imul(r ^ (r >>> 15), r | 1);+ r ^= r + Math.imul(r ^ (r >>> 7), r | 61);+ return ((r ^ (r >>> 14)) >>> 0) / 4294967296;+ };+};+const hashStr = (s) => {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }+ return h >>> 0;+};++// ---------- shape helpers ---------------------------------+const POINTS = { '1H': 60, '24H': 96, '7D': 168, '30D': 180, '90D': 180 };+const points = (r) => POINTS[r] ?? 96;++const HOURS = { '1H': 1, '24H': 24, '7D': 168, '30D': 720, '90D': 2160 };+const hours = (r) => HOURS[r] ?? 24;++const diurnal = (n, base, { peakHour = 14, amplitude = 0.75, noise = 0.12, rand } = {}) => {+ const out = new Array(n);+ const span = hours(rand.range ?? '24H');+ for (let i = 0; i < n; i++) {+ const hour = (i / (n - 1)) * span;+ const phase = Math.cos(((hour - peakHour) / 24) * 2 * Math.PI);+ const n1 = (rand() - 0.5) * 2 * noise;+ out[i] = Math.max(0, base * (1 + amplitude * phase + n1));+ }+ return out;+};++const pareto = (labels, total, { alpha = 1.05, rand }) => {+ const raw = labels.map((_, i) => (1 / Math.pow(i + 1, alpha)) * (0.85 + rand() * 0.3));+ const sum = raw.reduce((a, b) => a + b, 0);+ return labels.map((label, i) => ({ label, value: Math.round((raw[i] / sum) * total) }));+};++const sumOf = (arr) => arr.reduce((a, b) => a + b, 0);++const peakLabel = (values) => {+ let idx = 0, max = -Infinity;+ for (let i = 0; i < values.length; i++) if (values[i] > max) { max = values[i]; idx = i; }+ const frac = idx / (values.length - 1);+ const h = Math.floor(frac * 24);+ const m = Math.floor(((frac * 24) - h) * 60);+ return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;+};++const compact = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });++const rangeLabels = (range) => {+ switch (range) {+ case '1H': return ['−60 MIN', 'NOW'];+ case '24H': return ['00:00', '24:00'];+ case '7D': return ['MON', 'SUN'];+ case '30D': return ['D−30', 'TODAY'];+ case '90D': return ['Q START', 'TODAY'];+ default: return ['', ''];+ }+};++// ==========================================================+// AI OVERVIEW — the flagship+// ==========================================================+const buildAiOverview = (rand, range) => {+ const n = points(range);+ const base = 780 + rand() * 220;+ const queries = diurnal(n, base, { rand, peakHour: 13 });+ const totalQueries = Math.round(sumOf(queries));++ // Token counts — prompt grows with context, completion is steadier.+ const promptTok = queries.map((q) => q * (1800 + rand() * 600));+ const ctxTok = queries.map((q) => q * (9000 + rand() * 4500));+ const outTok = queries.map((q) => q * (320 + rand() * 180));+ const cacheHit = queries.map(() => 0.38 + rand() * 0.18);++ const totalPromptT = Math.round(sumOf(promptTok));+ const totalCtxT = Math.round(sumOf(ctxTok));+ const totalOutT = Math.round(sumOf(outTok));+ const totalT = totalPromptT + totalCtxT + totalOutT;++ // Cost: $/million tokens blended+ const cost = (totalPromptT / 1e6) * 2.5 + (totalCtxT / 1e6) * 0.2 + (totalOutT / 1e6) * 10;+ const costES = cost * 5.2; // what this would cost on the ES + proprietary stack++ const models = [+ { label: 'OPUS 4.6', value: Math.round(totalQueries * 0.22) },+ { label: 'SONNET 4.6', value: Math.round(totalQueries * 0.35) },+ { label: 'HAIKU 4.5', value: Math.round(totalQueries * 0.28) },+ { label: 'GPT-5', value: Math.round(totalQueries * 0.09) },+ { label: 'GEMINI 3', value: Math.round(totalQueries * 0.04) },+ { label: 'LLAMA 4', value: Math.round(totalQueries * 0.02) },+ ];++ const intents = pareto(+ ['semantic search','code-assist','doc-q&a','summarize','translate','classify',+ 'extract-json','agent-tool','rerank','rewrite','chat-freeform','safety-check'],+ totalQueries, { alpha: 0.85, rand }+ );++ const topDocs = pareto(+ ['runbook/oncall.md','rfc/042-retention.md','arch/cluster-design.md',+ 'rfc/039-hybrid-search.md','runbook/incident-1411.md','policy/pii.md',+ 'arch/hnsw-internals.md','rfc/051-agent-memory.md','docs/query-dsl.md',+ 'rfc/048-embed-proxy.md','runbook/billing-sync.md','docs/ingest-api.md'],+ Math.round(totalQueries * 0.7), { alpha: 0.75, rand }+ );++ // Latency percentiles per model as ribbon-3d series+ const latencyRibbons = [+ { label: 'OPUS 4.6', values: queries.map(() => 1450 + rand() * 220) },+ { label: 'SONNET 4.6', values: queries.map(() => 820 + rand() * 140) },+ { label: 'HAIKU 4.5', values: queries.map(() => 310 + rand() * 80) },+ { label: 'GPT-5', values: queries.map(() => 990 + rand() * 190) },+ { label: 'GEMINI 3', values: queries.map(() => 1120 + rand() * 240) },+ ];++ const costHeatmap = {+ cols: Array.from({ length: 12 }, (_, i) => String(i * 2).padStart(2, '0')),+ matrix: ['MON','TUE','WED','THU','FRI','SAT','SUN'].map((_, di) =>+ Array.from({ length: 12 }, (_, hi) => {+ const h = hi * 2;+ const phase = Math.cos(((h - 13) / 24) * 2 * Math.PI);+ const weekend = di >= 5 ? 0.48 : 1;+ return Math.max(0.2, cost / 150 * weekend * (1 + 0.8 * phase) * (0.85 + rand() * 0.3));+ })+ ),+ };++ const flowSegments = [+ { label: 'SYS PROMPT', value: totalPromptT },+ { label: 'CONTEXT', value: totalCtxT },+ { label: 'COMPLETION', value: totalOutT },+ ];++ return {+ metrics: {+ queries: { value: totalQueries, formatted: compact.format(totalQueries), delta: (rand() - 0.3) * 12 },+ tokens: { value: totalT, formatted: compact.format(totalT), delta: (rand() - 0.35) * 8 },+ cost: { value: cost, formatted: '$' + cost.toFixed(0), delta: (rand() - 0.65) * 18 },+ savings: { value: costES - cost, formatted: '$' + (costES - cost).toFixed(0), note: 'vs. ES+Pinecone+Splunk' },+ latency: { value: 820, formatted: '820', delta: (rand() - 0.55) * 8 },+ cacheHit: { value: 42, formatted: '42', delta: (rand() - 0.35) * 6 },+ },+ series: {+ queries,+ prompt: promptTok.map((v) => v / (1e3)),+ context: ctxTok.map((v) => v / (1e3)),+ output: outTok.map((v) => v / (1e3)),+ startLabel: rangeLabels(range)[0],+ endLabel: rangeLabels(range)[1],+ },+ models,+ intents,+ topDocs,+ latencyRibbons,+ costHeatmap,+ flowSegments,+ };+};++// ==========================================================+// RAG QUALITY — the unsolved observability problem+// ==========================================================+const buildRagQuality = (rand, range) => {+ const n = points(range);+ const grounding = diurnal(n, 88, { rand, amplitude: 0.06, noise: 0.03, peakHour: 13 });+ const hallucination = grounding.map((g) => Math.max(0, 4.2 - (g - 84) * 0.8 + (rand() - 0.5) * 0.8));+ const retrievalHit = grounding.map((g) => Math.min(99, g + 8 + (rand() - 0.5) * 4));++ // Query → Chunk → Citation flow (chord arcs)+ const queries = [+ { id: 'q1', label: 'how do I reset cluster' },+ { id: 'q2', label: 'retention vs storage cost' },+ { id: 'q3', label: 'agent memory dedup rules' },+ { id: 'q4', label: 'hybrid search score fusion' },+ { id: 'q5', label: 'mmap segment format' },+ { id: 'q6', label: 'WAL recovery procedure' },+ { id: 'q7', label: 'what is HNSW recall' },+ { id: 'q8', label: 'pricing large context' },+ ];+ const chunks = [+ { id: 'c1', label: 'arch/cluster-design.md#reset' },+ { id: 'c2', label: 'rfc/042-retention.md#cost' },+ { id: 'c3', label: 'rfc/051-agent-memory.md#dedup' },+ { id: 'c4', label: 'rfc/039-hybrid-search.md#rrf' },+ { id: 'c5', label: 'arch/hnsw-internals.md' },+ { id: 'c6', label: 'runbook/wal-recovery.md' },+ { id: 'c7', label: 'docs/query-dsl.md#knn' },+ { id: 'c8', label: 'rfc/048-embed-proxy.md' },+ { id: 'c9', label: 'docs/pricing.md#ctx' },+ { id: 'c10', label: 'runbook/oncall.md' },+ ];+ const flows = [];+ for (const q of queries) {+ // each query pulls 3..5 chunks+ const k = 3 + Math.floor(rand() * 3);+ const picked = new Set();+ while (picked.size < k) picked.add('c' + (1 + Math.floor(rand() * chunks.length)));+ for (const cid of picked) {+ flows.push({ from: q.id, to: cid, weight: 0.4 + rand() * 0.6 });+ }+ }++ // Sample answer with token attention weights+ const sampleText = 'The XERJ.ai cluster reset procedure requires draining the WAL, flushing all memtables to disk, and then restarting with the recovery flag set. Do not skip the WAL drain step — lost writes in the fsync tail are unrecoverable.';+ const tokens = sampleText.split(' ').map((t) => {+ const hot = /(cluster|reset|drain|WAL|flush|memtables|recovery|unrecoverable)/i.test(t);+ return { text: t, weight: hot ? 0.65 + rand() * 0.35 : 0.05 + rand() * 0.25 };+ });++ const chunkHitDensity = {+ rows: ['Q&A', 'SEARCH', 'SUMMARIZE', 'CODE', 'EXTRACT', 'AGENT'],+ cols: ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'],+ matrix: Array.from({ length: 6 }, () =>+ Array.from({ length: 10 }, () => Math.round(100 + rand() * 900))+ ),+ };++ const retrievalSource = [+ { label: 'HYBRID (RRF)', value: 6120 },+ { label: 'VECTOR KNN', value: 2340 },+ { label: 'BM25 ONLY', value: 820 },+ { label: 'MEMORY RECALL',value: 410 },+ ];++ const lowGroundingPrompts = pareto(+ [+ 'what changed in release 0.2',+ 'why is latency up today',+ 'who owns the billing pipeline',+ 'current on-call for Europe',+ 'is the fix deployed yet',+ 'any anomaly in the last hour',+ 'what does the new quota mean',+ 'regression vs last week',+ ],+ 4200, { alpha: 0.7, rand }+ ).map((it) => ({ ...it, value: Math.round(it.value / 10) + '%' }));++ return {+ metrics: {+ grounding: { value: grounding[grounding.length - 1], formatted: grounding[grounding.length - 1].toFixed(1), delta: (rand() - 0.35) * 4 },+ hallucination: { value: hallucination[hallucination.length - 1], formatted: hallucination[hallucination.length - 1].toFixed(2), delta: (rand() - 0.6) * 1.8 },+ hitRate: { value: retrievalHit[retrievalHit.length - 1], formatted: retrievalHit[retrievalHit.length - 1].toFixed(1), delta: (rand() - 0.4) * 4 },+ avgCitations: { value: 3.4, formatted: '3.4', delta: (rand() - 0.5) * 0.8 },+ },+ series: {+ grounding,+ hallucination,+ retrievalHit,+ startLabel: rangeLabels(range)[0],+ endLabel: rangeLabels(range)[1],+ },+ flow: { queries, chunks, flows },+ attention: { tokens, text: sampleText },+ chunkHitDensity,+ retrievalSource,+ lowGroundingPrompts,+ };+};++// ==========================================================+// VECTOR INDEX — HNSW + embedding space+// ==========================================================+const buildVectorIndex = (rand, range) => {+ const n = points(range);+ const qps = diurnal(n, 1800, { rand, peakHour: 14 });+ const p50 = qps.map(() => 2.8 + rand() * 0.7);+ const p95 = qps.map(() => 9.4 + rand() * 2.2);+ const p99 = qps.map(() => 22 + rand() * 6);+ const recall = qps.map(() => 96.2 + rand() * 2);++ // 2D projected embedding space with 6 clusters+ const clusters = [+ { label: 'code', center: [20, 70], spread: 9, count: 180 },+ { label: 'docs', center: [60, 40], spread: 12, count: 220 },+ { label: 'runbook', center: [82, 68], spread: 7, count: 110 },+ { label: 'tickets', center: [42, 82], spread: 10, count: 160 },+ { label: 'chat', center: [30, 20], spread: 14, count: 240 },+ { label: 'email', center: [72, 18], spread: 8, count: 120 },+ ].map((c) => {+ const points = Array.from({ length: c.count }, () => {+ const a = rand() * Math.PI * 2;+ const r = (rand() ** 0.5) * c.spread;+ return [c.center[0] + Math.cos(a) * r, c.center[1] + Math.sin(a) * r];+ });+ return { label: c.label, points, centroid: c.center };+ });++ const vectors = clusters.reduce((a, c) => a + c.points.length, 0);++ const models = [+ { label: 'text-embed-3 (1536)', value: 720 },+ { label: 'cohere-v3 (1024)', value: 340 },+ { label: 'e5-large (1024)', value: 190 },+ { label: 'local-bge-m3 (1024)', value: 80 },+ ];++ // Parallel coordinates of 40 recent queries across 5 dims+ const dims = [+ { name: 'LATENCY' }, { name: 'TOKENS' }, { name: 'COST' },+ { name: 'RECALL' }, { name: 'GROUND' },+ ];+ const rows = Array.from({ length: 80 }, () => [+ 300 + rand() * 1400, // latency ms+ 800 + rand() * 18000, // tokens+ 0.01 + rand() * 0.18, // cost usd+ 82 + rand() * 16, // recall %+ 70 + rand() * 28, // grounding %+ ]);+ const highlight = [1420, 14200, 0.16, 94, 86];++ return {+ metrics: {+ vectors: { value: vectors, formatted: compact.format(vectors * 6200), hint: '6.2M total · shard 14/32' },+ dim: { value: 1536, formatted: '1536', hint: '3 models' },+ disk: { value: 38, formatted: '38', hint: 'GB quantized' },+ qps: { value: qps[qps.length - 1], formatted: compact.format(qps[qps.length - 1]), delta: (rand() - 0.3) * 6 },+ recall: { value: 96.8, formatted: '96.8', delta: (rand() - 0.45) * 0.6 },+ p95: { value: p95[p95.length - 1], formatted: p95[p95.length - 1].toFixed(1), delta: (rand() - 0.6) * 8 },+ },+ series: {+ qps, p50, p95, p99, recall,+ startLabel: rangeLabels(range)[0],+ endLabel: rangeLabels(range)[1],+ },+ clusters,+ models,+ pcoords: { dims, rows, highlight },+ };+};++// ==========================================================+// AGENT MEMORY — XERJ.ai's unique primitive+// ==========================================================+const buildAgentMemory = (rand, range) => {+ const n = points(range);+ const size = diurnal(n, 2_200_000, { rand, amplitude: 0.25, noise: 0.04 });+ const dedup = diurnal(n, 34, { rand, amplitude: 0.08, noise: 0.02 });+ const recallP95 = diurnal(n, 14, { rand, amplitude: 0.12, noise: 0.04 });++ const agents = [+ { label: 'oncall-triage', value: 48210 },+ { label: 'doc-writer', value: 31450 },+ { label: 'incident-postmort', value: 22100 },+ { label: 'customer-qa', value: 18600 },+ { label: 'eng-copilot', value: 14200 },+ { label: 'billing-agent', value: 8900 },+ { label: 'sales-prospect', value: 6400 },+ { label: 'ops-baby-sitter', value: 3800 },+ ];++ // Semantic memory clusters for one specific agent (oncall-triage)+ const clusters = [+ { label: 'network', center: [18, 70], spread: 10, count: 90 },+ { label: 'storage', center: [52, 78], spread: 8, count: 110 },+ { label: 'billing', center: [78, 50], spread: 12, count: 80 },+ { label: 'auth', center: [30, 30], spread: 9, count: 70 },+ { label: 'query', center: [65, 22], spread: 11, count: 120 },+ ].map((c) => {+ const points = Array.from({ length: c.count }, () => {+ const a = rand() * Math.PI * 2;+ const r = (rand() ** 0.5) * c.spread;+ return [c.center[0] + Math.cos(a) * r, c.center[1] + Math.sin(a) * r];+ });+ return { label: c.label, points, centroid: c.center };+ });++ const topMemories = [+ { label: 'cluster reset procedure (verified)', value: 2804 },+ { label: 'pricing context for large enterprise', value: 1920 },+ { label: 'hybrid search fusion score explanation', value: 1612 },+ { label: 'WAL recovery tail loss (0.0014%)', value: 1402 },+ { label: 'HNSW recall vs build time tradeoff', value: 1180 },+ { label: 'agent memory dedup rules (semantic)', value: 980 },+ { label: 'mmap segment format roadmap', value: 770 },+ { label: 'flush policy triggers (investigate)', value: 612 },+ ];++ const recentOps = [+ ['23:14:02', 'INSERT', 'oncall-triage', 'new memory · cluster reset'],+ ['23:13:51', 'DEDUP', 'doc-writer', 'merged with 2 prior entries'],+ ['23:13:22', 'RECALL', 'oncall-triage', 'k=5 · top score 0.86'],+ ['23:12:48', 'FORGET', 'eng-copilot', 'decay below 0.12'],+ ['23:12:09', 'REWRITE', 'incident-pm', 'compacted from 4 → 1 entry'],+ ['23:11:44', 'INSERT', 'billing-agent', 'new memory · refund workflow'],+ ['23:11:03', 'RECALL', 'customer-qa', 'k=3 · top score 0.79'],+ ['23:10:41', 'DEDUP', 'sales-prospect', 'merged with 1 prior entry'],+ ['23:10:12', 'RECALL', 'eng-copilot', 'k=8 · top score 0.91'],+ ['23:09:58', 'INSERT', 'oncall-triage', 'new memory · billing-sync'],+ ];++ return {+ metrics: {+ entries: { value: size[size.length - 1], formatted: compact.format(size[size.length - 1]), delta: (rand() - 0.4) * 5 },+ dedup: { value: dedup[dedup.length - 1], formatted: dedup[dedup.length - 1].toFixed(1), delta: (rand() - 0.4) * 3 },+ recall: { value: recallP95[recallP95.length - 1], formatted: recallP95[recallP95.length - 1].toFixed(1), delta: (rand() - 0.55) * 4 },+ growth: { value: 84000, formatted: '84K', hint: 'per day' },+ agents: { value: agents.length, formatted: String(agents.length), hint: agents.length + ' active' },+ },+ series: {+ size, dedup, recallP95,+ startLabel: rangeLabels(range)[0],+ endLabel: rangeLabels(range)[1],+ },+ agents,+ clusters,+ topMemories,+ recentOps,+ };+};++// ==========================================================+// LOGS OVERVIEW — kept from earlier iteration+// ==========================================================+const buildLogsOverview = (rand, range) => {+ const n = points(range);+ const base = 42000 + rand() * 8000;+ const totalSeries = diurnal(n, base, { rand });+ const total = Math.round(sumOf(totalSeries));+ const peakVal = Math.max(...totalSeries);+ const peakAt = peakLabel(totalSeries);+ const errRate = 0.6 + rand() * 0.6;++ const sourcesTotal = 84 + Math.floor(rand() * 20);+ const sourcesActive = sourcesTotal - Math.floor(rand() * 6);++ const byLevel = [+ { label: 'INFO', value: Math.round(total * (0.86 + rand() * 0.04)) },+ { label: 'WARN', value: Math.round(total * (0.08 + rand() * 0.02)) },+ { label: 'ERROR', value: Math.round(total * (errRate / 100)) },+ { label: 'DEBUG', value: Math.round(total * 0.003) },+ { label: 'FATAL', value: Math.round(total * 0.0001) + 2 },+ ];++ const services = [+ 'api-gateway','auth-service','billing','checkout','search',+ 'catalog','inventory','shipping','notifications','webhook-worker',+ 'recommendation','pricing',+ ];+ const topServices = pareto(services, Math.round(total * 0.92), { alpha: 0.95, rand });++ const hosts = [+ 'ip-10-0-1-17','ip-10-0-1-42','ip-10-0-2-88','ip-10-0-3-11',+ 'ip-10-0-3-54','ip-10-0-4-09','ip-10-0-4-73','ip-10-0-5-22',+ 'ip-10-0-5-91','ip-10-0-6-18','ip-10-0-6-60','ip-10-0-7-04',+ ];+ const topHosts = pareto(hosts, Math.round(total * 0.82), { alpha: 0.7, rand });++ const cols = Array.from({ length: 12 }, (_, i) => String(i * 2).padStart(2, '0'));+ const matrix = ['MON','TUE','WED','THU','FRI','SAT','SUN'].map((_, di) =>+ cols.map((_, hi) => {+ const h = hi * 2;+ const phase = Math.cos(((h - 14) / 24) * 2 * Math.PI);+ const weekend = di >= 5 ? 0.55 : 1;+ return Math.round(base * weekend * (1 + 0.8 * phase) * (0.85 + rand() * 0.3));+ })+ );++ return {+ metrics: {+ total: { value: total, formatted: compact.format(total), delta: (rand() - 0.45) * 6 },+ peak: { value: peakVal, formatted: compact.format(peakVal), at: peakAt },+ errorRate: { value: errRate, formatted: errRate.toFixed(2), delta: (rand() - 0.6) * 0.8 },+ sources: { value: sourcesTotal, formatted: String(sourcesTotal), active: sourcesActive },+ },+ series: {+ total: totalSeries,+ startLabel: rangeLabels(range)[0],+ endLabel: rangeLabels(range)[1],+ },+ byLevel,+ topServices,+ topHosts,+ heatmap: { cols, matrix },+ };+};++// ==========================================================+// SYSTEM — kept from earlier iteration+// ==========================================================+const buildSystem = (rand, range) => {+ const n = points(range);+ const cpuSeries = diurnal(n, 48, { rand, amplitude: 0.35, noise: 0.08, peakHour: 14 });+ const memSeries = diurnal(n, 61, { rand, amplitude: 0.12, noise: 0.04, peakHour: 18 });+ const diskSeries = diurnal(n, 180, { rand, amplitude: 0.55, noise: 0.18, peakHour: 13 });+ const netSeries = diurnal(n, 420, { rand, amplitude: 0.6, noise: 0.2, peakHour: 15 });++ const hosts = [+ 'ip-10-0-1-17','ip-10-0-1-42','ip-10-0-2-88','ip-10-0-3-11',+ 'ip-10-0-3-54','ip-10-0-4-09','ip-10-0-4-73','ip-10-0-5-22',+ 'ip-10-0-5-91','ip-10-0-6-18','ip-10-0-6-60','ip-10-0-7-04',+ ];+ const hostCpu = hosts.map((h) => {+ const baseline = 30 + rand() * 45;+ const vals = Array.from({ length: 40 }, (_, i) => {+ const phase = Math.cos(((i - 20) / 20) * Math.PI);+ return Math.max(0, Math.min(100, baseline + phase * 14 + (rand() - 0.5) * 10));+ });+ return { label: h.toUpperCase(), values: vals, value: Math.round(vals[vals.length - 1]) + '%' };+ });++ const procs = [+ 'java -jar checkout-svc','postgres: walwriter','node search-proxy',+ 'java -jar auth-svc','python3 metrics-exporter','redis-server *:6379',+ 'envoy -c /etc/envoy.yaml','containerd-shim-runc','systemd-journald',+ 'kubelet --config /etc/kubelet','otelcol --config otel.yaml',+ ];+ const topProcs = pareto(procs, 1000, { alpha: 0.9, rand }).map((p) => ({+ label: p.label, value: p.value / 10,+ }));++ const topHosts = hosts.map((h, i) => ({+ label: h,+ value: Math.round(30 + (rand() * 60) + (i === 0 ? 15 : 0)),+ })).sort((a, b) => b.value - a.value);++ const authSeries = diurnal(n, 28, { rand, amplitude: 0.5 });+ const authTotal = Math.round(sumOf(authSeries));+ const failures = Math.round(authTotal * (0.03 + rand() * 0.02));+ const topFailUsers = pareto(+ ['root','admin','ubuntu','deploy','postgres','jenkins','test','oracle'],+ failures, { alpha: 0.65, rand }+ );+ const topFailIPs = pareto(+ ['45.137.21.4','185.234.218.19','193.32.162.157','91.240.118.99',+ '162.247.74.217','141.98.10.55','89.248.165.74','185.142.236.35'],+ failures, { alpha: 0.7, rand }+ );++ return {+ metrics: {+ hosts: { value: hosts.length, formatted: String(hosts.length), hint: `${hosts.length - 1} healthy` },+ alerts: { value: 3, formatted: '3', delta: -1.0, deltaGood: 'down', hint: '1 warn · 2 info' },+ cpuMean: { value: cpuSeries[cpuSeries.length - 1], formatted: cpuSeries[cpuSeries.length - 1].toFixed(0), delta: 4.1 },+ memMean: { value: memSeries[memSeries.length - 1], formatted: memSeries[memSeries.length - 1].toFixed(0), delta: 0.8 },+ },+ series: {+ cpu: cpuSeries, mem: memSeries, disk: diskSeries, net: netSeries,+ startLabel: rangeLabels(range)[0], endLabel: rangeLabels(range)[1],+ },+ hostCpu,+ topProcs,+ topHosts,+ auth: { total: authTotal, failures, series: authSeries, topFailUsers, topFailIPs },+ };+};++// ==========================================================+// SEARCH CORPUS — client-side fake index for the SEARCH dash+// ==========================================================+const CORPUS_INDICES = ['logs-prod', 'logs-stage', 'docs', 'metrics', 'traces', 'events'];++const BODY_TEMPLATES = [+ (r) => `GET /api/v2/catalog status=200 ms=${Math.round(12 + r() * 60)} client=203.0.113.${Math.floor(r() * 240)}`,+ (r) => `POST /api/v2/checkout status=500 upstream_ms=${Math.round(1500 + r() * 2500)} error="upstream timeout"`,+ (r) => `auth_login user=deploy src=10.0.${Math.floor(r() * 10)}.${Math.floor(r() * 240)} result=success`,+ (r) => `auth_login user=root src=45.137.21.${Math.floor(r() * 240)} result=failure reason="invalid password"`,+ (r) => `flush segment=seg-${Math.floor(r() * 999)} docs=${Math.floor(40000 + r() * 80000)} took_ms=${Math.round(180 + r() * 220)}`,+ (r) => `merge segments=[seg-${Math.floor(r() * 99)},seg-${Math.floor(r() * 99)}] out=seg-${Math.floor(r() * 999)} ratio=${(0.42 + r() * 0.3).toFixed(2)}`,+ (r) => `slow_query took_ms=${Math.round(820 + r() * 1800)} plan="BoolQuery(Must(Match(message)))" index="logs-prod"`,+ (r) => `hnsw_recall k=10 recall=${(0.94 + r() * 0.05).toFixed(3)} ef_search=${Math.floor(32 + r() * 96)}`,+ (r) => `agent_memory op=insert agent=oncall-triage key="cluster-reset" score=${(0.72 + r() * 0.25).toFixed(2)}`,+ (r) => `ingest_batch index=logs-prod docs=${Math.floor(1000 + r() * 9000)} wal_lag_ms=${Math.round(2 + r() * 18)}`,+ (r) => `oom_score=${Math.round(100 + r() * 800)} rss_mb=${Math.round(1200 + r() * 2600)} pid=${Math.floor(1000 + r() * 9000)}`,+ (r) => `cache_hit route=/api/v2/search ratio=${(0.72 + r() * 0.22).toFixed(2)} ttl_s=${Math.floor(60 + r() * 540)}`,+ (r) => `tool_use name=search success=true tokens_in=${Math.floor(200 + r() * 900)} tokens_out=${Math.floor(40 + r() * 240)}`,+ (r) => `rag_answer grounding=${(0.78 + r() * 0.2).toFixed(2)} citations=${Math.floor(2 + r() * 5)} chunks=${Math.floor(3 + r() * 7)}`,+];++const SERVICES = ['api-gateway','auth-service','billing','checkout','search','catalog','ingest-worker','query-coordinator','embed-proxy','agent-memory'];+const LEVELS = ['INFO','WARN','ERROR','DEBUG','FATAL'];+const HOSTS = ['ip-10-0-1-17','ip-10-0-2-88','ip-10-0-3-54','ip-10-0-4-73','ip-10-0-5-91','ip-10-0-6-60'];++function buildCorpus() {+ const r = rng(0xFEEDFACE);+ const docs = [];+ for (let i = 0; i < 600; i++) {+ const tpl = BODY_TEMPLATES[Math.floor(r() * BODY_TEMPLATES.length)];+ const level = r() < 0.78 ? 'INFO' : r() < 0.93 ? 'WARN' : r() < 0.98 ? 'ERROR' : 'FATAL';+ docs.push({+ _index: CORPUS_INDICES[Math.floor(r() * CORPUS_INDICES.length)],+ _id: (1000000 + i).toString(16),+ _ts: new Date(Date.now() - Math.floor(r() * 86_400_000)).toISOString().slice(11, 19),+ service: SERVICES[Math.floor(r() * SERVICES.length)],+ level,+ host: HOSTS[Math.floor(r() * HOSTS.length)],+ _source: tpl(r),+ });+ }+ return docs;+}+let _corpus = null;+const corpus = () => (_corpus ??= buildCorpus());++/**+ * mockSearch — filter the in-memory corpus against a query.+ * Supports:+ * type=match — substring on _source+ * type=term — exact equality on field (e.g. `level=ERROR`)+ * type=prefix — _source startsWith+ * type=phrase — quoted-substring+ * type=range — `field>=value` / `field<=value` (latency-like)+ * type=knn — fake nearest-vector: rank by string-similarity hash+ * type=semantic — similar to knn, ranks differently+ * type=hybrid — 0.6*match + 0.4*vector, RRF-style fusion+ * index='*' means all indices.+ *+ * filters: `{ level: 'ERROR' }` applied as post-filter (clickable facets).+ */+export function mockSearch({ q = '', type = 'match', index = '*', filters = {}, sort = { field: '_score', dir: 'desc' } } = {}) {+ const t0 = performance.now();+ const docs = corpus();+ const qLower = q.toLowerCase().trim();++ const passesIndex = (d) => index === '*' || d._index === index;+ const passesFilter = (d) => Object.entries(filters).every(([f, v]) => !v || d[f] === v);++ let pool = docs.filter((d) => passesIndex(d) && passesFilter(d));+ let matched;+ if (!qLower) {+ matched = pool.map((d) => ({ ...d, _score: 1 }));+ } else if (type === 'term') {+ // field=value syntax+ const m = qLower.match(/^([a-z_]+)\s*=\s*(.+)$/i);+ if (m) {+ const [, f, v] = m;+ matched = pool+ .filter((d) => String(d[f] ?? '').toLowerCase() === v.toLowerCase())+ .map((d) => ({ ...d, _score: 1 }));+ } else matched = [];+ } else if (type === 'prefix') {+ matched = pool+ .filter((d) => d._source.toLowerCase().startsWith(qLower))+ .map((d) => ({ ...d, _score: 1 - (d._source.length / 500) }));+ } else if (type === 'phrase') {+ const phrase = qLower.replace(/^"|"$/g, '');+ matched = pool+ .filter((d) => d._source.toLowerCase().includes(phrase))+ .map((d) => ({ ...d, _score: 2 + Math.random() * 0.5 }));+ } else if (type === 'range') {+ const m = qLower.match(/^([a-z_]+)\s*(>=|<=|>|<)\s*(\d+(?:\.\d+)?)$/i);+ if (m) {+ const [, f, op, v] = m;+ const n = Number(v);+ matched = pool+ .filter((d) => {+ const src = d._source;+ const rx = new RegExp(f + '=(\\d+(?:\\.\\d+)?)', 'i');+ const mm = src.match(rx);+ if (!mm) return false;+ const x = Number(mm[1]);+ return op === '>=' ? x >= n : op === '<=' ? x <= n : op === '>' ? x > n : x < n;+ })+ .map((d) => ({ ...d, _score: 1 }));+ } else matched = [];+ } else if (type === 'knn' || type === 'semantic') {+ // Fake vector distance: bytewise hash diff against query+ const qHash = Array.from(qLower).reduce((a, c) => (a + c.charCodeAt(0)) % 997, 0);+ matched = pool.map((d) => {+ const dh = Array.from(d._source.toLowerCase()).reduce((a, c) => (a + c.charCodeAt(0)) % 997, 0);+ const dist = Math.abs(qHash - dh) / 997;+ return { ...d, _score: 1 - dist };+ }).filter((d) => d._score > 0.72);+ } else if (type === 'hybrid') {+ // 0.6*bm25 + 0.4*vector, RRF-style rank fusion+ const bmList = pool.filter((d) => d._source.toLowerCase().includes(qLower))+ .map((d, i) => ({ id: d._id, rank: i + 1, base: d }));+ const qHash = Array.from(qLower).reduce((a, c) => (a + c.charCodeAt(0)) % 997, 0);+ const knnList = pool.map((d) => {+ const dh = Array.from(d._source.toLowerCase()).reduce((a, c) => (a + c.charCodeAt(0)) % 997, 0);+ return { id: d._id, score: 1 - Math.abs(qHash - dh) / 997, base: d };+ }).sort((a, b) => b.score - a.score).slice(0, 80).map((d, i) => ({ ...d, rank: i + 1 }));+ const mix = new Map();+ for (const r of bmList) mix.set(r.id, { base: r.base, s: 0.6 / (60 + r.rank) });+ for (const r of knnList) {+ const cur = mix.get(r.id);+ const add = 0.4 / (60 + r.rank);+ if (cur) cur.s += add;+ else mix.set(r.id, { base: r.base, s: add });+ }+ matched = Array.from(mix.values()).sort((a, b) => b.s - a.s).map((r) => ({ ...r.base, _score: r.s * 1000 }));+ } else {+ // default: match+ matched = pool.filter((d) => d._source.toLowerCase().includes(qLower))+ .map((d) => {+ const idx = d._source.toLowerCase().indexOf(qLower);+ const score = 2 + (1 - idx / d._source.length) * 2;+ return { ...d, _score: score };+ });+ }++ // Sort honors caller's request. Defaults to _score desc. GH#696/GH#737.+ const sortField = sort?.field || '_score';+ const sortDir = sort?.dir === 'asc' ? 1 : -1;+ matched.sort((a, b) => {+ const av = a[sortField];+ const bv = b[sortField];+ if (av == null && bv == null) return 0;+ if (av == null) return 1;+ if (bv == null) return -1;+ if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * sortDir;+ return String(av).localeCompare(String(bv)) * sortDir;+ });+ const hits = matched.slice(0, 25);+ const took = Math.max(1, Math.round(performance.now() - t0 + (0.5 + Math.random() * 3.5)));+ // Facets computed from matched pool (post-query, pre-filter)+ const count = (field) => {+ const m = new Map();+ for (const d of matched) m.set(d[field], (m.get(d[field]) || 0) + 1);+ return Array.from(m.entries()).sort((a, b) => b[1] - a[1]).slice(0, 8)+ .map(([value, c]) => ({ label: value, value, count: c }));+ };+ // Histogram: buckets by the hour of d._ts+ const buckets = Array.from({ length: 24 }, () => 0);+ for (const d of matched) {+ const h = parseInt(d._ts.slice(0, 2), 10) || 0;+ buckets[h] += 1;+ }+ return {+ hits,+ total: matched.length,+ tookMs: took,+ maxScore: hits.length ? hits[0]._score : null,+ facets: { level: count('level'), service: count('service'), host: count('host'), _index: count('_index') },+ histogram: buckets,+ };+}++// ==========================================================+// ANOMALY DETECTION — client-side z-score over a mock stream+// ==========================================================+/**+ * Rolling-window anomaly detection. Pure client-side z-score+ * because the engine's native anomaly pipeline is stubbed.+ * Returns value series + upper/lower bands + outlier indices+ * with attribution over N features.+ */+const buildAnomalyDetect = (rand, range) => {+ const n = points(range);+ // Primary signal: query latency with injected spikes+ const base = 420 + rand() * 90;+ const values = Array.from({ length: n }, (_, i) => {+ const diurnal = Math.cos(((i / n) * 24 - 14) / 24 * 2 * Math.PI);+ return Math.max(10, base * (1 + 0.22 * diurnal) + (rand() - 0.5) * 28);+ });+ // Inject anomalies+ const injected = [];+ const numAnom = 5 + Math.floor(rand() * 3);+ for (let k = 0; k < numAnom; k++) {+ const idx = Math.floor(rand() * n);+ const mag = 2.8 + rand() * 3;+ values[idx] = values[idx] * mag;+ injected.push(idx);+ }++ // Rolling window stats for bands+ const W = Math.max(6, Math.floor(n / 12));+ const upper = new Array(n);+ const lower = new Array(n);+ for (let i = 0; i < n; i++) {+ const lo = Math.max(0, i - W), hi = Math.min(n - 1, i + W);+ let s = 0, s2 = 0, c = 0;+ for (let j = lo; j <= hi; j++) { s += values[j]; s2 += values[j] * values[j]; c++; }+ const mean = s / c;+ const std = Math.sqrt(Math.max(0, s2 / c - mean * mean));+ upper[i] = mean + 2.5 * std;+ lower[i] = Math.max(0, mean - 2.5 * std);+ }++ // Compute z-scores — anomalies are indices exceeding 2.5σ+ const anomalies = [];+ for (let i = 0; i < n; i++) {+ if (values[i] > upper[i] || values[i] < lower[i]) {+ const score = (values[i] - (upper[i] + lower[i]) / 2) / ((upper[i] - lower[i]) / 2 || 1);+ anomalies.push({ idx: i, score: Math.abs(score), value: values[i] });+ }+ }+ anomalies.sort((a, b) => b.score - a.score);++ // Feature attribution for top anomaly+ const topFeatures = [+ { label: 'query_latency_p95', value: 3.8 },+ { label: 'upstream_timeout', value: 2.9 },+ { label: 'cache_miss_rate', value: 2.1 },+ { label: 'flush_duration', value: 1.8 },+ { label: 'gc_pause', value: 0.7 },+ { label: 'cpu_saturation', value: 0.5 },+ ];++ // Top anomalous signals over the period+ const topSignals = [+ { label: 'api-gateway /checkout p95', value: anomalies[0]?.score || 0 },+ { label: 'billing-svc query latency', value: 4.1 },+ { label: 'auth-svc failed logins', value: 3.6 },+ { label: 'search-svc wal_lag_ms', value: 2.9 },+ { label: 'embed-proxy cost surge', value: 2.4 },+ { label: 'vector-index p99 latency', value: 2.0 },+ { label: 'agent-memory dedup dip', value: 1.7 },+ ];++ return {+ metrics: {+ detected: { value: anomalies.length, formatted: String(anomalies.length), delta: (rand() - 0.6) * 18 },+ covered: { value: 14, formatted: '14', hint: 'signals scored · z·score' },+ falsePos: { value: 1.2, formatted: '1.2', delta: (rand() - 0.5) * 0.6 },+ recall: { value: 92, formatted: '92', hint: 'vs. hand labels' },+ },+ series: {+ values, upper, lower, anomalies: anomalies.slice(0, 12),+ startLabel: rangeLabels(range)[0], endLabel: rangeLabels(range)[1],+ },+ topFeatures,+ topSignals,+ injected,+ };+};++// ==========================================================+// INGEST PIPELINE — engine internals, matches Prometheus metrics+// ==========================================================+const buildIngest = (rand, range) => {+ const n = points(range);+ const docsIn = diurnal(n, 68000, { rand, amplitude: 0.6, peakHour: 15 });+ const bytesIn = docsIn.map((d) => d * (1.1 + rand() * 0.6) * 1024);+ const walLag = docsIn.map(() => 2 + rand() * 22);+ const flushMs = docsIn.map(() => 180 + rand() * 220);+ const mergeMs = docsIn.map(() => 420 + rand() * 900);+ const memBytes = docsIn.map(() => 1.8 * 1024 * 1024 * 1024 + rand() * 800 * 1024 * 1024);++ const idxLatP50 = docsIn.map(() => 0.6 + rand() * 0.3);+ const idxLatP95 = docsIn.map(() => 2.1 + rand() * 0.9);+ const idxLatP99 = docsIn.map(() => 6.4 + rand() * 2.8);++ const topIndices = pareto(+ ['logs-prod','logs-stage','traces','docs','metrics','events',+ 'agent-memory','embeddings','alerts','audit'],+ Math.round(sumOf(docsIn)), { alpha: 0.85, rand }+ );++ const perField = [+ { label: '@timestamp', value: 98, encoding: 'Δ-of-Δ' },+ { label: 'service', value: 91, encoding: 'DICT' },+ { label: 'level', value: 96, encoding: 'DICT' },+ { label: 'host', value: 88, encoding: 'DICT' },+ { label: 'message', value: 61, encoding: 'ZSTD+TMPL' },+ { label: 'trace_id', value: 28, encoding: 'UVARINT' },+ { label: 'latency_ms', value: 72, encoding: 'FOR+RLE' },+ { label: 'status', value: 94, encoding: 'DICT' },+ { label: 'bytes_out', value: 58, encoding: 'FOR' },+ ];++ const pipelineFlow = [+ { label: 'HTTP PARSE', value: 100 },+ { label: 'FIELD MAP', value: 98 },+ { label: 'PIPELINE · redact', value: 97 },+ { label: 'WAL APPEND', value: 97 },+ { label: 'MEMTABLE', value: 97 },+ { label: 'FLUSH → SEGMENT', value: 92 },+ { label: 'MERGE', value: 61 },+ ];++ return {+ metrics: {+ docsRate: { value: docsIn[docsIn.length - 1], formatted: compact.format(docsIn[docsIn.length - 1]), delta: (rand() - 0.3) * 8, unit: 'docs/s' },+ bytesRate: { value: bytesIn[bytesIn.length - 1], formatted: (bytesIn[bytesIn.length - 1] / 1024 / 1024).toFixed(1), unit: 'MB/s' },+ walLag: { value: walLag[walLag.length - 1], formatted: walLag[walLag.length - 1].toFixed(1), unit: 'ms', delta: (rand() - 0.55) * 12 },+ segments: { value: 184, formatted: '184', hint: '3 indices · 12 shards' },+ mem: { value: (memBytes[memBytes.length - 1] / 1024 / 1024 / 1024).toFixed(2), formatted: (memBytes[memBytes.length - 1] / 1024 / 1024 / 1024).toFixed(2), unit: 'GB' },+ ratio: { value: 4.8, formatted: '4.8', unit: '×', hint: 'vs. raw JSON' },+ },+ series: {+ docsIn, bytesIn, walLag, flushMs, mergeMs, memBytes,+ idxLatP50, idxLatP95, idxLatP99,+ startLabel: rangeLabels(range)[0], endLabel: rangeLabels(range)[1],+ },+ topIndices,+ perField,+ pipelineFlow,+ };+};++// ==========================================================+// SEARCH DASHBOARD — static context data (histogram, facets)+// only used when no query has been submitted yet.+// ==========================================================+const buildSearchDash = (rand, range) => {+ const n = points(range);+ const queries = diurnal(n, 1200, { rand, peakHour: 14 });+ const took_p50 = queries.map(() => 2 + rand() * 1.4);+ const took_p95 = queries.map(() => 8 + rand() * 3.2);+ return {+ metrics: {+ qps: { value: queries[queries.length - 1], formatted: compact.format(queries[queries.length - 1]), delta: (rand() - 0.4) * 5 },+ p95: { value: took_p95[took_p95.length - 1], formatted: took_p95[took_p95.length - 1].toFixed(1), delta: (rand() - 0.6) * 6 },+ totalDocs: { value: 52_400_000, formatted: '52.4M', hint: '6 indices · 32 shards' },+ uniqueTerms: { value: 18_900_000, formatted: '18.9M', hint: 'exact cardinality ✓' },+ },+ series: { queries, took_p50, took_p95, startLabel: rangeLabels(range)[0], endLabel: rangeLabels(range)[1] },+ };+};++// ---------- filter application ----------------------------+// The real backend will compile `filters` into an ES filter clause.+// Here we approximate the behaviour so click-to-filter actually+// changes the shape: if a filter matches a label inside a top-N or+// Dist, we keep only buckets whose labels case-insensitively include+// the filter value. Series and metrics get a proportional shrink.+//+// A filter value can be a scalar OR an array — array = OR semantics,+// matching GH#3693 ("Multi-select (OR) dashboard filtering").+function filterCount(filters) {+ let n = 0;+ for (const v of Object.values(filters || {})) {+ n += Array.isArray(v) ? v.length : 1;+ }+ return n;+}+function filterRatio(filters) {+ const n = filterCount(filters);+ if (!n) return 1;+ // Each active filter shrinks things ~35%, clamped at 10%.+ // Multi-value (OR) filters shrink less because they match more.+ const fields = Object.keys(filters || {}).length;+ return Math.max(0.1, Math.pow(0.65, fields));+}++function applyFilters(data, filters) {+ if (!filters || !Object.keys(filters).length) return data;+ const r = filterRatio(filters);+ const values = [];+ for (const v of Object.values(filters)) {+ if (Array.isArray(v)) for (const x of v) values.push(String(x).toLowerCase());+ else values.push(String(v).toLowerCase());+ }+ const keep = (label) => {+ const s = String(label || '').toLowerCase();+ return values.some((v) => s.includes(v));+ };++ const walk = (node) => {+ if (Array.isArray(node)) {+ // Array of {label,value} buckets → narrow to matches when any+ // label matches a filter value. Otherwise rescale proportionally.+ if (node.length && typeof node[0] === 'object' && node[0] && 'label' in node[0] && 'value' in node[0]) {+ const hits = node.filter((b) => keep(b.label));+ if (hits.length) return hits.map((b) => ({ ...b, value: Math.max(1, Math.round(b.value * r * 1.2)) }));+ return node.map((b) => ({ ...b, value: Math.max(0, Math.round(b.value * r)) }));+ }+ // Numeric series → scale+ if (node.length && typeof node[0] === 'number') return node.map((v) => v * r);+ return node.map(walk);+ }+ if (node && typeof node === 'object') {+ const out = {};+ for (const k of Object.keys(node)) {+ const v = node[k];+ // Scale well-known metric shapes+ if (v && typeof v === 'object' && 'value' in v && 'formatted' in v && typeof v.value === 'number') {+ const scaled = Math.round(v.value * r);+ out[k] = { ...v, value: scaled, formatted: formatLike(v.formatted, scaled) };+ } else {+ out[k] = walk(v);+ }+ }+ return out;+ }+ return node;+ };+ return walk(data);+}++// Best-effort reformat of a metric's display string after scaling+// the numeric value. Handles compact (1.2K), percent (42), and+// currency ($1,230) forms.+function formatLike(prev, n) {+ const s = String(prev);+ if (s.startsWith('$')) return '$' + Math.round(n).toLocaleString('en');+ if (/^[\d.]+[KMB]$/.test(s)) return compact.format(n);+ if (/^\d+$/.test(s)) return String(Math.round(n));+ return compact.format(n);+}++// ---------- public entry point ----------------------------+// CUSTOM ranges resolve to the nearest bucket shape the mock knows+// so charts still render. The real backend will respect from/to as+// absolute ISO timestamps. We pick a bucket based on the span:+// < 2h → 1H shape+// < 36h → 24H shape+// < 10d → 7D shape+// < 45d → 30D shape+// else → 90D shape+function bucketForCustom(customRange) {+ if (!customRange || !customRange.from || !customRange.to) return '24H';+ const a = new Date(customRange.from).getTime();+ const b = new Date(customRange.to).getTime();+ if (!isFinite(a) || !isFinite(b) || b <= a) return '24H';+ const hrs = (b - a) / 3_600_000;+ if (hrs < 2) return '1H';+ if (hrs < 36) return '24H';+ if (hrs < 240) return '7D';+ if (hrs < 1080) return '30D';+ return '90D';+}++export function mock(dashId, range = '24H', ctx = {}) {+ const { cluster = '', filters = {}, customRange = null } = ctx;+ const effectiveRange = range === 'CUSTOM' ? bucketForCustom(customRange) : range;+ // Include cluster + filter keys + custom-range bounds in the seed so+ // switching filters visibly re-shuffles the numbers.+ const customKey = customRange ? (customRange.from || '') + '/' + (customRange.to || '') : '';+ const seedKey = dashId + '|' + effectiveRange + '|' + cluster + '|' + Object.keys(filters).sort().join(',') + '|' + customKey;+ const seedRand = rng(hashStr(seedKey));+ seedRand.range = effectiveRange;+ let out;+ switch (dashId) {+ case 'ai-overview': out = buildAiOverview(seedRand, effectiveRange); break;+ case 'rag-quality': out = buildRagQuality(seedRand, effectiveRange); break;+ case 'vector-index': out = buildVectorIndex(seedRand, effectiveRange); break;+ case 'agent-memory': out = buildAgentMemory(seedRand, effectiveRange); break;+ case 'search-discover': out = buildSearchDash(seedRand, effectiveRange); break;+ case 'anomaly-detect': out = buildAnomalyDetect(seedRand, effectiveRange); break;+ case 'ingest-pipeline': out = buildIngest(seedRand, effectiveRange); break;+ case 'logs-overview': out = buildLogsOverview(seedRand, effectiveRange); break;+ case 'system': out = buildSystem(seedRand, effectiveRange); break;+ default: out = buildAiOverview(seedRand, effectiveRange);+ }+ return applyFilters(out, filters);+}diff --git a/xerj-ux/src/data/query.js b/xerj-ux/src/data/query.jsnew file mode 100644index 000000000..8df6ca438--- /dev/null+++ b/xerj-ux/src/data/query.js@@ -0,0 +1,136 @@+// ============================================================+// Xerj Console — query gateway+//+// All dashboard data flows through this one entry point. It picks+// the active backend (default: xerj), tries a live call, and+// falls back to the in-memory mock when the live call fails or+// returns null (no adapter for this dashboard yet).+//+// This file is the only place in the playground that touches HTTP.+// Dashboards stay backend-agnostic — they receive a shaped `data`+// object and never see fetch().+// ============================================================++import { mock as mockData } from './mock.js';+import {+ activeBackend,+ activeBackendId,+ backendBaseUrl,+ BACKENDS,+} from './backends/index.js';++/** Last-known status for the nav pill. Updated on every query. */+let _lastSourceKind = 'pending';+let _lastSourceLabel = 'STARTING UP';++/** Function form (preferred). Returns the live status string. */+export function dataSourceStatus() {+ return _lastSourceLabel;+}++export function dataSourceKind() {+ return _lastSourceKind;+}++/**+ * Fetch shaped data for a dashboard.+ *+ * ctx.dashId: dashboard id from the registry+ * ctx.range: '1H' | '24H' | '7D' | '30D' | '90D' | 'CUSTOM'+ * ctx.cluster: cluster id (defaults to active cluster)+ * ctx.filters: { [field]: value | [values] }+ * ctx.search: per-dashboard freeform state (q, type, index, …)+ * ctx.signal: AbortSignal — backends that honour it cancel in flight+ *+ * Returns `{ data, meta }` where meta carries timing, the active+ * backend, and `fetchedAt` for the nav status line.+ */+export async function query(ctx = {}) {+ const {+ dashId,+ range = '24H',+ customRange = null,+ cluster = '',+ filters = {},+ search = {},+ signal,+ } = typeof ctx === 'string' ? { dashId: ctx } : ctx;++ const t0 = perfNow();+ const backend = activeBackend();+ const backendId = activeBackendId();+ const baseUrl = backendBaseUrl(backendId);++ // Try the live backend. A return of `null` means the backend+ // recognises the dashId but has no live adapter yet — we fall+ // through to mock without flipping the status pill to red.+ let data = null;+ let liveError = null;+ if (backend && typeof backend.search === 'function') {+ try {+ data = await backend.search(baseUrl, dashId, { range, customRange, cluster, filters, search }, signal);+ } catch (e) {+ liveError = String(e);+ }+ }++ if (data == null) {+ // Fallback to mock.+ data = mockData(dashId, range, { cluster, filters, customRange });+ _lastSourceKind = backendId === 'mock' ? 'mock' : 'fallback';+ _lastSourceLabel = backendId === 'mock'+ ? 'MOCK DATA'+ : `${BACKENDS[backendId]?.meta?.label || backendId}: MOCK FALLBACK`;+ } else if (data.error) {+ // The backend ran but returned an error envelope. Surface it to+ // the dashboard but keep the live source label so the user can+ // see "the backend is up but this query failed."+ _lastSourceKind = 'live-error';+ _lastSourceLabel = `${BACKENDS[backendId]?.meta?.label || backendId}: ${String(data.error).slice(0, 80)}`;+ } else {+ _lastSourceKind = 'live';+ _lastSourceLabel = `LIVE · ${BACKENDS[backendId]?.meta?.label || backendId} · ${baseUrl || ''}`;+ }++ const t1 = perfNow();+ return {+ data,+ meta: {+ dashId,+ range,+ customRange,+ cluster,+ filters,+ search,+ fetchedAt: new Date().toISOString(),+ durationMs: Math.round((t1 - t0) * 10) / 10,+ backend: backendId,+ backendLabel: BACKENDS[backendId]?.meta?.label || backendId,+ baseUrl,+ sourceKind: _lastSourceKind,+ liveError,+ },+ };+}++/** Probe the active backend. Used by the nav to flip the status+ * pill from amber → green when the engine becomes reachable. */+export async function probeActiveBackend(signal) {+ const backend = activeBackend();+ const backendId = activeBackendId();+ const baseUrl = backendBaseUrl(backendId);+ if (!backend || typeof backend.probe !== 'function') return false;+ try {+ return await backend.probe(baseUrl, signal);+ } catch (_e) {+ return false;+ }+}++function perfNow() {+ return typeof performance !== 'undefined' ? performance.now() : Date.now();+}++/** Initial value (overwritten at runtime). Kept as a default export+ * for any old `import { DATA_SOURCE_KIND }` call sites. */+export const DATA_SOURCE_KIND = 'pending';diff --git a/xerj-ux/src/ux/chart-types.js b/xerj-ux/src/ux/chart-types.jsnew file mode 100644index 000000000..1fe43a965--- /dev/null+++ b/xerj-ux/src/ux/chart-types.js@@ -0,0 +1,356 @@+// ============================================================+// XERJ.ai — Chart type registry+//+// The master catalog of visualization types, used by:+// 1. The edit-mode ADD picker (lists every type).+// 2. User-added panels (render demo data via this registry).+//+// Each entry: { id, name, cols, render(data) }. `render` may+// consume the current dashboard's data object OR fall back to+// canned demo data so an added panel always previews nicely+// regardless of the active dashboard.+// ============================================================++import { Num, fmt } from './text.js';+import { Spark, Series, Dist, Heatmap, Multiples } from './charts.js';+import { VBar, Hist, Gauge, Scatter, Stacked, Treemap } from './charts-ext.js';+import { EmbedSpace, Ribbon3D, ChordArcs, ParallelCoords, AttentionMap, FlowBand } from './charts-ai.js';+import { Table, Markdown } from './tables.js';+import { TopN, Events } from './layout.js';++// ---------- demo data (deterministic) ---------------------+const demoSeries = Array.from({ length: 48 }, (_, i) =>+ 50 + Math.sin(i / 5.5) * 22 + Math.cos(i / 3.2) * 9 + ((i * 37) % 7)+);+const demoItems = [+ { label: 'alpha', value: 4230 },+ { label: 'beta', value: 3180 },+ { label: 'gamma', value: 2564 },+ { label: 'delta', value: 1923 },+ { label: 'epsilon', value: 1340 },+ { label: 'zeta', value: 912 },+ { label: 'eta', value: 680 },+ { label: 'theta', value: 445 },+];+const demoSegments = [+ { label: '2XX', value: 9620 },+ { label: '3XX', value: 410 },+ { label: '4XX', value: 190 },+ { label: '5XX', value: 48 },+];+const demoTree = [+ { label: 'root', value: 13000, children: [+ { label: 'api-gateway', value: 5100, children: [+ { label: '/v2/search', value: 2400 },+ { label: '/v2/cart', value: 1800 },+ { label: '/v2/catalog', value: 900 },+ ]},+ { label: 'auth-service', value: 2400 },+ { label: 'billing', value: 1600 },+ { label: 'checkout', value: 1400 },+ ]},+];++// ---------- registry --------------------------------------+export const chartTypes = {++ metric: {+ name: 'METRIC',+ cols: 4,+ describe: 'A single headline number with optional spark and delta.',+ render: () => Num({+ value: '42.0K', unit: 'demo',+ spark: Spark(demoSeries, { w: 160, h: 30 }),+ delta: 3.1, emphasis: true,+ }),+ },++ gauge: {+ name: 'GAUGE',+ cols: 4,+ describe: 'Single value on a bounded 1px track.',+ render: () => Gauge({ value: 73, min: 0, max: 100, unit: '%', label: 'demo' }),+ },++ line: {+ name: 'LINE',+ cols: 12,+ describe: 'Full-width time series. Replaces both Line and Area.',+ render: () => Series(demoSeries, { h: 140, labels: ['START', 'NOW'], unit: 'u/s' }),+ },++ spark: {+ name: 'SPARK',+ cols: 3,+ describe: 'Inline 1px sparkline with latest value.',+ render: () => Num({+ value: fmt(demoSeries[demoSeries.length - 1]),+ unit: 'u/s',+ spark: Spark(demoSeries, { w: 200, h: 36 }),+ emphasis: false,+ }),+ },++ bar: {+ name: 'BAR',+ cols: 6,+ describe: 'Vertical 1px-line bar chart.',+ render: () => VBar({+ items: demoSeries.slice(0, 24).map((v, i) => ({ label: String(i).padStart(2, '0'), value: Math.round(v) })),+ h: 140,+ unit: 'u',+ }),+ },++ histogram: {+ name: 'HISTOGRAM',+ cols: 12,+ describe: 'Column histogram of counts across buckets.',+ render: () => Hist({+ items: Array.from({ length: 32 }, (_, i) => ({+ label: String(i),+ value: Math.round(Math.exp(-Math.pow((i - 16) / 5, 2)) * 1000 + (i % 3) * 30),+ })),+ h: 160, unit: 'count',+ }),+ },++ dist: {+ name: 'DIST',+ cols: 12,+ describe: 'Distribution bar. Replaces pie/donut.',+ render: () => Dist({ segments: demoSegments, width: 1200 }),+ },++ stacked: {+ name: 'STACKED',+ cols: 12,+ describe: 'Horizontal stacked bars, one row per series.',+ render: () => Stacked({+ rows: [+ { label: 'US', segments: demoSegments },+ { label: 'DE', segments: demoSegments.map((s) => ({ ...s, value: s.value * 0.6 })) },+ { label: 'JP', segments: demoSegments.map((s) => ({ ...s, value: s.value * 0.45 })) },+ { label: 'BR', segments: demoSegments.map((s) => ({ ...s, value: s.value * 0.3 })) },+ ],+ }),+ },++ topn: {+ name: 'TOP-N',+ cols: 6,+ describe: 'Ranked list with aligned 1px bars. Replaces horizontal bar.',+ render: () => TopN({ items: demoItems, total: demoItems.reduce((a, i) => a + i.value, 0), n: 8 }),+ },++ treemap: {+ name: 'TREEMAP',+ cols: 6,+ describe: 'Nested hierarchy of ranked items.',+ render: () => Treemap({ items: demoTree }),+ },++ heatmap: {+ name: 'HEATMAP',+ cols: 12,+ describe: 'Character-intensity grid. Rows × columns of numbers whose opacity encodes magnitude.',+ render: () => Heatmap({+ rows: ['A','B','C','D','E','F','G'],+ cols: ['00','02','04','06','08','10','12','14','16','18','20','22'],+ matrix: Array.from({ length: 7 }, (_, r) =>+ Array.from({ length: 12 }, (_, c) => {+ const phase = Math.cos(((c * 2 - 14) / 24) * 2 * Math.PI);+ return Math.round(80 + 60 * phase + r * 5 + ((r + c * 7) % 9));+ })),+ cellFmt: (v) => String(v),+ }),+ },++ multiples: {+ name: 'MULTIPLES',+ cols: 12,+ describe: 'Grid of small sparklines, one per dimension.',+ render: () => Multiples({+ items: Array.from({ length: 8 }, (_, i) => ({+ label: 'SERIES ' + String.fromCharCode(65 + i),+ values: demoSeries.map((v) => v + (i * 3) + Math.sin(i) * 5),+ value: String(Math.round(50 + i * 2)),+ })),+ w: 180, h: 22,+ }),+ },++ scatter: {+ name: 'SCATTER',+ cols: 6,+ describe: 'X/Y point cloud using `·` characters as data points.',+ render: () => Scatter({+ points: Array.from({ length: 80 }, () => {+ const t = Math.random();+ return [20 + t * 80 + (Math.random() - 0.5) * 20, 10 + t * 70 + (Math.random() - 0.5) * 25];+ }),+ xLabel: 'LATENCY', yLabel: 'THROUGHPUT', h: 220,+ }),+ },++ table: {+ name: 'TABLE',+ cols: 6,+ describe: 'Text data table, no borders, tabular numbers.',+ render: () => Table({+ columns: ['NAME', 'COUNT', 'PCT', 'TREND'],+ rows: demoItems.map((it, i) => [+ it.label,+ fmt(it.value),+ ((it.value / demoItems.reduce((a, x) => a + x.value, 0)) * 100).toFixed(1) + '%',+ i % 2 ? '▲ 3.1' : '▼ 1.4',+ ]),+ align: ['left', 'right', 'right', 'right'],+ }),+ },++ events: {+ name: 'EVENTS',+ cols: 12,+ describe: 'Recent event tail — time, severity, message.',+ render: () => Events({ items: [+ { at: '23:14:02.081', sev: 'err', msg: 'demo · upstream timed out (connect) while connecting to upstream' },+ { at: '23:13:51.602', sev: 'warn', msg: 'demo · slow query 842 ms SELECT * FROM orders WHERE ...' },+ { at: '23:13:04.114', sev: 'info', msg: 'demo · batch 238 committed · 14,402 docs · 112 ms' },+ { at: '23:12:48.771', sev: 'warn', msg: 'demo · rate limit approaching 85% for tenant=acme' },+ { at: '23:12:09.033', sev: 'info', msg: 'demo · segment merged · 3→1 · 412 MB → 386 MB' },+ ]}),+ },++ markdown: {+ name: 'TEXT',+ cols: 6,+ describe: 'Free-form prose panel with very light markdown.',+ render: () => Markdown(+`## NOTES++This is a **text** panel. Use it for *annotations*, playbooks,+SLO definitions, on-call runbooks — anything that the reader+needs to see next to the data.++Inline \`code\` renders in accent, which is the one place prose+borrows the accent color.`+ ),+ },++ // ---- AI / RAG primitives -------------------------------++ embedspace: {+ name: 'EMBED-SPACE',+ cols: 12,+ describe: 'Embedding projection with 1px cluster hulls.',+ render: () => {+ const mk = (cx, cy, r, label, n) => {+ const pts = Array.from({ length: n }, () => {+ const a = Math.random() * Math.PI * 2;+ const rr = Math.sqrt(Math.random()) * r;+ return [cx + Math.cos(a) * rr, cy + Math.sin(a) * rr];+ });+ return { label, points: pts, centroid: [cx, cy] };+ };+ return EmbedSpace({+ clusters: [+ mk(22, 70, 10, 'code', 120),+ mk(58, 38, 12, 'docs', 180),+ mk(82, 66, 8, 'runbook', 80),+ mk(40, 80, 9, 'tickets', 110),+ mk(28, 22, 12, 'chat', 160),+ ],+ h: 360,+ });+ },+ },++ ribbon3d: {+ name: '3D RIBBON',+ cols: 12,+ describe: 'Axonometric stacked 1px time series. The "3D" chart.',+ render: () => {+ const series = Array.from({ length: 5 }, (_, i) => ({+ label: 'SERIES ' + String.fromCharCode(65 + i),+ values: Array.from({ length: 48 }, (_, j) =>+ 40 + i * 9 + Math.sin(j / 5 + i) * 15 + Math.cos(j / 8) * 6+ ),+ }));+ return Ribbon3D({ series, h: 260, depth: 14 });+ },+ },++ chord: {+ name: 'CHORD FLOW',+ cols: 12,+ describe: '1px Bézier arcs from sources to targets.',+ render: () => {+ const sources = Array.from({ length: 6 }, (_, i) => ({ id: 's' + i, label: 'query ' + (i + 1) }));+ const targets = Array.from({ length: 8 }, (_, i) => ({ id: 't' + i, label: 'doc/chunk ' + (i + 1) }));+ const flows = [];+ for (const s of sources) {+ const k = 2 + Math.floor(Math.random() * 3);+ for (let i = 0; i < k; i++) {+ flows.push({ from: s.id, to: 't' + Math.floor(Math.random() * 8), weight: Math.random() });+ }+ }+ return ChordArcs({ sources, targets, flows, h: 360 });+ },+ },++ pcoords: {+ name: 'PARALLEL-COORDS',+ cols: 12,+ describe: 'Multi-dimensional rows as 1px polylines across N axes.',+ render: () => ParallelCoords({+ dims: [{ name: 'LAT' }, { name: 'TOK' }, { name: 'COST' }, { name: 'RECALL' }, { name: 'GROUND' }],+ rows: Array.from({ length: 60 }, () => [+ 200 + Math.random() * 1500,+ 800 + Math.random() * 20000,+ 0.01 + Math.random() * 0.2,+ 80 + Math.random() * 18,+ 70 + Math.random() * 28,+ ]),+ h: 260,+ }),+ },++ attention: {+ name: 'ATTENTION-MAP',+ cols: 12,+ describe: 'Inline text with per-token opacity = attention weight.',+ render: () => AttentionMap({+ tokens: ('The XERJ.ai cluster reset requires draining the WAL and flushing all memtables before restart . Lost writes in the fsync tail are unrecoverable .').split(' ').map((t) => ({+ text: t,+ weight: /(cluster|reset|drain|WAL|flush|memtables|restart|unrecoverable)/i.test(t)+ ? 0.7 + Math.random() * 0.3+ : 0.08 + Math.random() * 0.22,+ })),+ }),+ },++ flowband: {+ name: 'FLOW BAND',+ cols: 12,+ describe: 'Single-row stacked flow allocation with labeled ticks.',+ render: () => FlowBand({+ segments: [+ { label: 'SYS PROMPT', value: 1200 },+ { label: 'CONTEXT', value: 8400 },+ { label: 'COMPLETION', value: 640 },+ ],+ unit: 'tok',+ }),+ },++};++/** Ordered list for the ADD picker. Reads left to right. AI first. */+export const chartTypeList = [+ // AI / RAG+ 'embedspace','ribbon3d','chord','pcoords','attention','flowband',+ // Classic+ 'metric','gauge','spark','line','bar','histogram','dist','stacked',+ 'topn','treemap','heatmap','multiples','scatter','table','events','markdown',+].map((id) => ({ id, ...chartTypes[id] }));diff --git a/xerj-ux/src/ux/charts-ai.js b/xerj-ux/src/ux/charts-ai.jsnew file mode 100644index 000000000..0a9aba1ae--- /dev/null+++ b/xerj-ux/src/ux/charts-ai.js@@ -0,0 +1,351 @@+// ============================================================+// XERJ.ai — AI / RAG visualization primitives+//+// Typography-first takes on the viz types people reach for when+// building AI dashboards: embedding spaces, attention maps, RAG+// retrieval flow, multi-dim parallel coordinates, and axonometric+// "3D" ribbon plots. All strokes are 1px.+// ============================================================++import { esc, fmt } from './text.js';++const minMax = (xs) => {+ let mn = Infinity, mx = -Infinity;+ for (const x of xs) { if (x < mn) mn = x; if (x > mx) mx = x; }+ return [mn === Infinity ? 0 : mn, mx === -Infinity ? 0 : mx];+};++// Andrew's monotone chain — O(n log n) convex hull.+function convexHull(points) {+ if (points.length < 3) return points.slice();+ const pts = points.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);+ const cross = (O, A, B) => (A[0] - O[0]) * (B[1] - O[1]) - (A[1] - O[1]) * (B[0] - O[0]);+ const lower = [];+ for (const p of pts) {+ while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();+ lower.push(p);+ }+ const upper = [];+ for (let i = pts.length - 1; i >= 0; i--) {+ const p = pts[i];+ while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();+ upper.push(p);+ }+ upper.pop(); lower.pop();+ return lower.concat(upper);+}++// ==============================================================+// EmbedSpace — 2D projection of embeddings, 1px cluster hulls+// ==============================================================+/**+ * The iconic AI visualization: a 2D projection of high-dimensional+ * embeddings, colored (here: opacity'd) by cluster, with 1px convex+ * hulls and centroid labels.+ *+ * clusters: [{ label, points: [[x,y], ...], centroid: [x,y] }]+ * h: svg viewBox height+ * highlight: optional [x,y] — rendered as a crosshair (e.g. the+ * current query's projected embedding)+ */+export const EmbedSpace = ({ clusters = [], h = 360, highlight = null } = {}) => {+ if (!clusters.length) return '';+ const W = 1200;+ const allPts = clusters.flatMap((c) => c.points);+ if (!allPts.length) return '';+ const [xmn, xmx] = minMax(allPts.map((p) => p[0]));+ const [ymn, ymx] = minMax(allPts.map((p) => p[1]));+ const xr = xmx - xmn || 1;+ const yr = ymx - ymn || 1;+ const pad = 40;+ const px = (x) => pad + ((x - xmn) / xr) * (W - pad * 2);+ const py = (y) => pad + (1 - (y - ymn) / yr) * (h - pad * 2);++ const dots = clusters.flatMap((c, ci) => {+ const op = Math.max(0.35, 1 - ci * 0.09);+ return c.points.map(([x, y]) =>+ `<text x="${px(x).toFixed(1)}" y="${py(y).toFixed(1)}" fill="currentColor" opacity="${op.toFixed(2)}" font-family="var(--font-data)" font-size="14" text-anchor="middle" dominant-baseline="middle">·</text>`+ );+ }).join('');++ const hulls = clusters.map((c, ci) => {+ if (c.points.length < 3) return '';+ const h2 = convexHull(c.points);+ if (h2.length < 3) return '';+ const closed = h2.concat([h2[0]]);+ const pts = closed.map(([x, y]) => `${px(x).toFixed(1)},${py(y).toFixed(1)}`).join(' ');+ const op = Math.max(0.2, 0.55 - ci * 0.07);+ return `<polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="${op.toFixed(2)}"/>`;+ }).join('');++ const labels = clusters.map((c) => {+ const [cx, cy] = c.centroid || c.points[0];+ return `<text x="${px(cx).toFixed(1)}" y="${(py(cy) - 14).toFixed(1)}" fill="currentColor" font-family="var(--font-prose)" font-size="11" font-weight="700" letter-spacing="1.5" text-anchor="middle">${esc((c.label || '').toUpperCase())}</text>`;+ }).join('');++ const hl = highlight ? `+ <line x1="${px(highlight[0]).toFixed(1)}" y1="0" x2="${px(highlight[0]).toFixed(1)}" y2="${h}" stroke="var(--z-accent)" stroke-width="1" stroke-opacity="0.5"/>+ <line x1="0" y1="${py(highlight[1]).toFixed(1)}" x2="${W}" y2="${py(highlight[1]).toFixed(1)}" stroke="var(--z-accent)" stroke-width="1" stroke-opacity="0.5"/>+ <text x="${px(highlight[0]).toFixed(1)}" y="${py(highlight[1]).toFixed(1)}" fill="var(--z-accent)" font-family="var(--font-data)" font-size="18" text-anchor="middle" dominant-baseline="middle">×</text>+ <text x="${(px(highlight[0]) + 8).toFixed(1)}" y="${(py(highlight[1]) - 8).toFixed(1)}" fill="var(--z-accent)" font-family="var(--font-data)" font-size="11" letter-spacing="0.08em">QUERY</text>+ ` : '';++ return `+ <svg class="chart" viewBox="0 0 ${W} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px;">+ ${hulls}+ ${dots}+ ${labels}+ ${hl}+ </svg>+ <div class="series-legend">+ <span class="mono" style="color:var(--z-mute);">UMAP · <span style="color:var(--z-ink);">${allPts.length}</span> embeddings · <span style="color:var(--z-ink);">${clusters.length}</span> clusters</span>+ </div>`;+};++// ==============================================================+// Ribbon3D — axonometric stacked 1px time series+// ==============================================================+/**+ * Multiple time series rendered with per-series x/y offsets to+ * create an axonometric "3D" effect. Every line is still a 1px+ * polyline — no fills, no perspective tricks, no lighting.+ *+ * series: [{ label, values }]+ * h: intrinsic svg height+ * depth: pixel offset per ribbon in the depth axis+ */+export const Ribbon3D = ({ series = [], h = 260, depth = 14 } = {}) => {+ if (!series.length) return '';+ const W = 1200;+ const [mn, mx] = minMax(series.flatMap((s) => s.values));+ const range = mx - mn || 1;+ const n = series.length;+ const innerW = W - (n - 1) * depth - 120;+ const innerH = h - (n - 1) * depth - 40;++ const bodies = series.map((s, i) => {+ const offX = 110 + (n - 1 - i) * depth;+ const offY = 20 + (n - 1 - i) * depth;+ const pts = s.values.map((v, j) => {+ const x = offX + (j / (s.values.length - 1)) * innerW;+ const y = offY + innerH - ((v - mn) / range) * innerH;+ return `${x.toFixed(1)},${y.toFixed(1)}`;+ }).join(' ');+ const op = Math.max(0.32, 1 - i * 0.14);+ const labelX = offX - 6;+ const labelY = offY + innerH * 0.5;+ const label = `<text x="${labelX.toFixed(1)}" y="${labelY.toFixed(1)}" fill="currentColor" opacity="${op.toFixed(2)}" font-family="var(--font-data)" font-size="11" text-anchor="end" dominant-baseline="middle">${esc(s.label)}</text>`;+ const endVal = `<text x="${(offX + innerW + 6).toFixed(1)}" y="${((offY + innerH - ((s.values[s.values.length-1] - mn) / range) * innerH)).toFixed(1)}" fill="currentColor" opacity="${op.toFixed(2)}" font-family="var(--font-data)" font-size="11" dominant-baseline="middle">${esc(fmt(s.values[s.values.length - 1]))}</text>`;+ return `<polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="${op.toFixed(2)}"/>${label}${endVal}`;+ }).join('');++ return `+ <svg class="chart" viewBox="0 0 ${W} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px;">+ ${bodies}+ </svg>+ <div class="series-legend">+ <span class="mono" style="color:var(--z-mute);">axonometric · ${n} series · min <span style="color:var(--z-ink);">${fmt(mn)}</span> · max <span style="color:var(--z-ink);">${fmt(mx)}</span></span>+ </div>`;+};++// ==============================================================+// ChordArcs — 1px Bézier arcs from sources to targets+// ==============================================================+/**+ * Flow between two ordered sets. Perfect for RAG:+ * sources = queries, targets = chunks/citations, flows = retrievals.+ *+ * sources: [{ id, label }]+ * targets: [{ id, label }]+ * flows: [{ from: sourceId, to: targetId, weight }]+ */+export const ChordArcs = ({ sources = [], targets = [], flows = [], h = 420, unit = '' } = {}) => {+ if (!sources.length || !targets.length || !flows.length) return '';+ const W = 1200;+ const pad = 20;+ const innerH = h - pad * 2;+ const srcY = (id) => {+ const i = sources.findIndex((s) => s.id === id);+ return pad + ((i + 0.5) / sources.length) * innerH;+ };+ const tgtY = (id) => {+ const i = targets.findIndex((t) => t.id === id);+ return pad + ((i + 0.5) / targets.length) * innerH;+ };+ const leftX = 220;+ const rightX = W - 220;+ const maxW = Math.max(...flows.map((f) => f.weight)) || 1;++ const arcs = flows.map((f) => {+ const y1 = srcY(f.from);+ const y2 = tgtY(f.to);+ if (y1 == null || y2 == null) return '';+ const cx1 = leftX + (rightX - leftX) * 0.38;+ const cx2 = leftX + (rightX - leftX) * 0.62;+ const op = Math.max(0.1, Math.min(0.9, f.weight / maxW * 0.85));+ return `<path d="M ${leftX},${y1.toFixed(1)} C ${cx1.toFixed(1)},${y1.toFixed(1)} ${cx2.toFixed(1)},${y2.toFixed(1)} ${rightX},${y2.toFixed(1)}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="${op.toFixed(2)}"/>`;+ }).join('');++ const srcLabels = sources.map((s) => `+ <text x="${(leftX - 12).toFixed(1)}" y="${srcY(s.id).toFixed(1)}" fill="currentColor" font-family="var(--font-data)" font-size="11" text-anchor="end" dominant-baseline="middle">${esc(s.label)}</text>+ `).join('');++ const tgtLabels = targets.map((t) => `+ <text x="${(rightX + 12).toFixed(1)}" y="${tgtY(t.id).toFixed(1)}" fill="currentColor" font-family="var(--font-data)" font-size="11" dominant-baseline="middle">${esc(t.label)}</text>+ `).join('');++ const srcHead = `<text x="${(leftX - 12).toFixed(1)}" y="${(pad - 8).toFixed(1)}" fill="currentColor" opacity="0.6" font-family="var(--font-prose)" font-size="11" font-weight="600" letter-spacing="2" text-transform="uppercase" text-anchor="end">SOURCE</text>`;+ const tgtHead = `<text x="${(rightX + 12).toFixed(1)}" y="${(pad - 8).toFixed(1)}" fill="currentColor" opacity="0.6" font-family="var(--font-prose)" font-size="11" font-weight="600" letter-spacing="2" text-transform="uppercase">TARGET</text>`;++ return `+ <svg class="chart" viewBox="0 0 ${W} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px; overflow:visible;">+ ${arcs}+ ${srcLabels}+ ${tgtLabels}+ ${srcHead}+ ${tgtHead}+ </svg>+ <div class="series-legend">+ <span class="mono" style="color:var(--z-mute);">${flows.length} flows · <span style="color:var(--z-ink);">${sources.length}</span>→<span style="color:var(--z-ink);">${targets.length}</span>${unit ? ' · ' + esc(unit) : ''}</span>+ </div>`;+};++// ==============================================================+// ParallelCoords — 1px parallel coordinate plot+// ==============================================================+/**+ * Multi-dimensional rows rendered as 1px polylines across N axes.+ * Standard ML tool. Every axis is a 1px vertical line. Stacked+ * rows form density patterns via accumulated opacity.+ *+ * dims: [{ name, min?, max? }]+ * rows: [[v0, v1, ..., vN]]+ */+export const ParallelCoords = ({ dims = [], rows = [], h = 260, highlight = null } = {}) => {+ if (!dims.length || !rows.length) return '';+ const W = 1200;+ const pad = 60;+ const top = 36, bot = 36;+ const colX = (i) => pad + (i / (dims.length - 1 || 1)) * (W - pad * 2);+ const extents = dims.map((d, i) => {+ if (d.min != null && d.max != null) return [d.min, d.max];+ const vals = rows.map((r) => r[i]).filter((v) => v != null);+ return minMax(vals);+ });++ const axes = dims.map((d, i) => {+ const x = colX(i).toFixed(1);+ return `<line x1="${x}" y1="${top}" x2="${x}" y2="${h - bot}" stroke="currentColor" stroke-width="1" stroke-opacity="0.2"/>`;+ }).join('');++ const polyline = (row, op) => {+ const pts = row.map((v, i) => {+ const [mn, mx] = extents[i];+ const frac = (v - mn) / (mx - mn || 1);+ const x = colX(i);+ const y = top + (1 - Math.max(0, Math.min(1, frac))) * (h - top - bot);+ return `${x.toFixed(1)},${y.toFixed(1)}`;+ }).join(' ');+ return `<polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="${op}"/>`;+ };+ const bodies = rows.map(() => polyline).map((fn, i) => fn(rows[i], '0.16')).join('');+ const hl = highlight ? polyline(highlight, '1').replace('stroke="currentColor"', 'stroke="var(--z-accent)"') : '';++ const labels = dims.map((d, i) => {+ const x = colX(i).toFixed(1);+ const [mn, mx] = extents[i];+ return `+ <text x="${x}" y="22" fill="currentColor" font-family="var(--font-prose)" font-size="11" font-weight="700" letter-spacing="1.5" text-anchor="middle">${esc(d.name.toUpperCase())}</text>+ <text x="${x}" y="${h - 16}" fill="currentColor" opacity="0.55" font-family="var(--font-data)" font-size="10" text-anchor="middle">${esc(fmt(mn))}</text>+ <text x="${x}" y="${h - 4}" fill="currentColor" opacity="0.55" font-family="var(--font-data)" font-size="10" text-anchor="middle">${esc(fmt(mx))}</text>+ `;+ }).join('');++ return `+ <svg class="chart" viewBox="0 0 ${W} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px;">+ ${axes}+ ${bodies}+ ${hl}+ ${labels}+ </svg>+ <div class="series-legend">+ <span class="mono" style="color:var(--z-mute);"><span style="color:var(--z-ink);">${rows.length}</span> rows · <span style="color:var(--z-ink);">${dims.length}</span> dimensions${highlight ? ' · <span style="color:var(--z-accent);">1 highlighted</span>' : ''}</span>+ </div>`;+};++// ==============================================================+// AttentionMap — inline text with per-token opacity+// ==============================================================+/**+ * A paragraph where each word's opacity equals its attention weight.+ * The paragraph IS the chart. For RAG, this is how you show which+ * retrieved tokens actually mattered to the answer.+ *+ * tokens: [{ text, weight }]+ * maxWeight: optional — normalized to this rather than observed max+ */+export const AttentionMap = ({ tokens = [], maxWeight = null } = {}) => {+ if (!tokens.length) return '';+ const mx = maxWeight ?? Math.max(...tokens.map((t) => t.weight));+ const spans = tokens.map((t) => {+ const op = Math.max(0.08, (t.weight / (mx || 1)));+ const hot = t.weight / mx > 0.82;+ const style = hot+ ? `color:var(--z-accent); opacity:${op.toFixed(2)};`+ : `opacity:${op.toFixed(2)};`;+ return `<span style="${style}">${esc(t.text)}</span>`;+ }).join(' ');+ const top = [...tokens].sort((a, b) => b.weight - a.weight).slice(0, 3);+ return `+ <div class="attention" style="font-family:var(--font-data); font-size:var(--fs-16); line-height:1.9; max-width:92ch;">${spans}</div>+ <div class="series-legend" style="margin-top:var(--sp-3);">+ <span class="mono" style="color:var(--z-mute);">peak attention on <span class="accent">${top.map((t) => esc(t.text)).join(' · ')}</span></span>+ </div>`;+};++// ==============================================================+// FlowBand — a single stacked horizontal allocation strip+// ==============================================================+/**+ * Budget allocation, token allocation, context-window breakdown.+ * One row, N segments, each labeled with absolute value directly+ * under the segment. Replaces "funnel" charts.+ */+export const FlowBand = ({ segments = [], width = 1200, unit = '' } = {}) => {+ if (!segments.length) return '';+ const total = segments.reduce((a, s) => a + s.value, 0) || 1;+ const H = 16;+ let x = 0;+ // SVG layer is just the horizontal band + tick divisions.+ const parts = segments.map((s, i) => {+ const w = (s.value / total) * width;+ const op = Math.max(0.28, 1 - i * 0.16);+ const line = w > 1+ ? `<line x1="${x.toFixed(1)}" y1="8" x2="${(x + w).toFixed(1)}" y2="8" stroke="currentColor" stroke-width="2" stroke-opacity="${op.toFixed(2)}"/>`+ : '';+ const tick = `<line x1="${x.toFixed(1)}" y1="2" x2="${x.toFixed(1)}" y2="14" stroke="currentColor" stroke-width="1" stroke-opacity="0.4"/>`;+ x += w;+ return tick + line;+ }).join('');+ const endTick = `<line x1="${width.toFixed(1)}" y1="2" x2="${width.toFixed(1)}" y2="14" stroke="currentColor" stroke-width="1" stroke-opacity="0.4"/>`;+ // HTML label layer — flex proportional to segment values. Tiny+ // segments collapse with ellipsis instead of overflowing into+ // neighboring labels. min-width:0 is required on every flex item+ // or the default min-width:auto prevents shrink below content.+ const labels = segments.map((s, i) => {+ const pct = ((s.value / total) * 100).toFixed(1);+ const op = Math.max(0.28, 1 - i * 0.16);+ return `+ <div class="fb-seg" style="flex:${s.value} 0 0; min-width:0; opacity:${op.toFixed(2)};">+ <div class="fb-label">${esc(s.label.toUpperCase())}</div>+ <div class="fb-value">${esc(fmt(s.value))}${unit ? ' ' + esc(unit) : ''} · ${pct}%</div>+ </div>`;+ }).join('');+ return `+ <div class="flowband-wrap">+ <svg class="chart flowband-svg" viewBox="0 0 ${width} ${H}" preserveAspectRatio="none" style="width:100%; height:${H}px; overflow:visible; display:block;">+ ${parts}${endTick}+ </svg>+ <div class="flowband-labels" style="display:flex; width:100%; margin-top:8px;">${labels}</div>+ </div>`;+};diff --git a/xerj-ux/src/ux/charts-ext.js b/xerj-ux/src/ux/charts-ext.jsnew file mode 100644index 000000000..db1f113b8--- /dev/null+++ b/xerj-ux/src/ux/charts-ext.js@@ -0,0 +1,202 @@+// ============================================================+// XERJ.ai — Chart primitives (extended set)+// Kibana-parity chart types in typography-first style.+// All stroke widths are 1px. Scatter uses text characters for+// data points — the only "point markers" we allow because the+// data IS the character.+// ============================================================++import { esc, fmt } from './text.js';++const minMax = (xs) => {+ let mn = Infinity, mx = -Infinity;+ for (const x of xs) { if (x < mn) mn = x; if (x > mx) mx = x; }+ return [mn === Infinity ? 0 : mn, mx === -Infinity ? 0 : mx];+};++// ----- VBar / Hist -------------------------------------------++/**+ * VBar — vertical 1px-line bar chart. Replaces Kibana "Bar" / "Histogram".+ *+ * items: [{ label, value }]+ * h: intrinsic viewBox height+ * unit: optional unit in the legend+ * labels: true → render label strip under the chart+ */+export const VBar = ({ items, h = 160, unit = '', labels = true } = {}) => {+ if (!items || !items.length) return '';+ const w = 1200;+ const values = items.map((i) => i.value);+ const [mn, mx] = minMax(values);+ const denom = mx || 1;+ const step = w / items.length;+ const lines = items.map((it, i) => {+ const x = ((i + 0.5) * step).toFixed(1);+ const y = (h - (it.value / denom) * h).toFixed(1);+ return `<line x1="${x}" y1="${h}" x2="${x}" y2="${y}" stroke="currentColor" stroke-width="1"/>`;+ }).join('');+ const first = items[0]?.label ?? '';+ const last = items[items.length - 1]?.label ?? '';+ const u = unit ? ' ' + esc(unit) : '';+ const legend = labels ? `+ <div class="series-legend">+ <span>${esc(first)}</span>+ <span class="mid">min <span class="mono" style="color:var(--z-ink);">${fmt(mn)}</span> · max <span class="mono" style="color:var(--z-ink);">${fmt(mx)}${u}</span></span>+ <span>${esc(last)}</span>+ </div>` : '';+ return `+ <div class="series-wrap">+ <svg class="chart" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px;">+ ${lines}+ </svg>+ ${legend}+ </div>`;+};++/** Hist — semantic alias for VBar (column histogram of counts). */+export const Hist = VBar;++// ----- Gauge -------------------------------------------------++/**+ * Gauge — a single value on a 1px track between min and max.+ *+ * value, min, max, unit+ * thresholds: optional [t1, t2, ...] — rendered as tiny 1px ticks+ * emphasis: true → value rendered in 56px accent (default)+ */+export const Gauge = ({+ value,+ min = 0,+ max = 100,+ unit = '',+ thresholds = [],+ emphasis = true,+ label = '',+} = {}) => {+ const w = 600, h = 14;+ const v = Math.max(min, Math.min(max, value));+ const frac = (v - min) / (max - min || 1);+ const x = (frac * w).toFixed(1);+ const ticks = thresholds.map((t) => {+ const tx = (((t - min) / (max - min || 1)) * w).toFixed(1);+ return `<line x1="${tx}" y1="0" x2="${tx}" y2="${h}" stroke="currentColor" stroke-width="1" stroke-opacity="0.4"/>`;+ }).join('');+ const valCls = emphasis ? 'num-big accent' : 'num-md';+ return `+ <div class="stack">+ <div class="row-flex" style="justify-content:space-between;">+ <div class="${valCls}">${esc(fmt(value))}<span class="num-unit">${esc(unit)}</span></div>+ ${label ? `<span class="hint">${esc(label)}</span>` : ''}+ </div>+ <svg class="chart" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px; margin-top:12px;">+ <line x1="0" y1="${h - 1}" x2="${w}" y2="${h - 1}" stroke="currentColor" stroke-width="1" stroke-opacity="0.18"/>+ <line x1="0" y1="${h - 1}" x2="${x}" y2="${h - 1}" stroke="currentColor" stroke-width="1"/>+ ${ticks}+ </svg>+ <div class="row-flex" style="justify-content:space-between; margin-top:6px; font-family:var(--font-data); font-size:var(--fs-11); color:var(--z-mute);">+ <span>${esc(fmt(min))}</span>+ <span>${esc(fmt(max))}${unit ? ' ' + esc(unit) : ''}</span>+ </div>+ </div>`;+};++// ----- Scatter -----------------------------------------------++/**+ * Scatter — x/y point cloud using single characters as data points.+ * Pure typography: each point is a `·` placed absolutely. The+ * character IS the datum, which is why scatter is the only chart+ * that has "point markers".+ *+ * points: [[x, y], ...]+ * xLabel, yLabel: text shown in the end legend+ */+export const Scatter = ({ points, h = 220, xLabel = 'X', yLabel = 'Y' } = {}) => {+ if (!points || !points.length) return '';+ const xs = points.map((p) => p[0]);+ const ys = points.map((p) => p[1]);+ const [xmn, xmx] = minMax(xs); const xr = xmx - xmn || 1;+ const [ymn, ymx] = minMax(ys); const yr = ymx - ymn || 1;+ const dots = points.map(([x, y]) => {+ const px = (((x - xmn) / xr) * 100).toFixed(2);+ const py = (((ymx - y) / yr) * 100).toFixed(2);+ return `<span style="position:absolute; left:${px}%; top:${py}%; transform:translate(-50%,-50%); font-family:var(--font-data); font-size:var(--fs-16); color:var(--z-ink); line-height:1; pointer-events:none;">·</span>`;+ }).join('');+ return `+ <div style="position:relative; width:100%; height:${h}px;">${dots}</div>+ <div class="series-legend">+ <span>${esc(xLabel)} <span class="mono" style="color:var(--z-ink);">${fmt(xmn)}..${fmt(xmx)}</span></span>+ <span class="mid"><span class="mono" style="color:var(--z-ink);">${points.length}</span> points</span>+ <span>${esc(yLabel)} <span class="mono" style="color:var(--z-ink);">${fmt(ymn)}..${fmt(ymx)}</span></span>+ </div>`;+};++// ----- Stacked -----------------------------------------------++/**+ * Stacked — horizontal stacked bars, one per row. Replaces Kibana+ * "Stacked bar". Each row's segments are distinguished by opacity.+ *+ * rows: [{ label, segments: [{ label, value }] }]+ */+export const Stacked = ({ rows, width = 1200, height = 10, showSegments = true } = {}) => {+ if (!rows || !rows.length) return '';+ const segmentLabels = showSegments ? rows[0].segments.map((s) => esc(s.label)).join(' · ') : '';+ const body = rows.map((row) => {+ const total = row.segments.reduce((a, s) => a + s.value, 0) || 1;+ let x = 0;+ const lines = row.segments.map((s, i) => {+ const segW = (s.value / total) * width;+ const op = Math.max(0.14, 1 - i * 0.16);+ const line = segW > 0.5+ ? `<line x1="${x.toFixed(1)}" y1="${(height - 1).toFixed(1)}" x2="${(x + segW).toFixed(1)}" y2="${(height - 1).toFixed(1)}" stroke="currentColor" stroke-width="1" stroke-opacity="${op.toFixed(2)}"/>`+ : '';+ x += segW;+ return line;+ }).join('');+ return `+ <div class="stk-row">+ <span class="row__label">${esc(row.label)}</span>+ <svg class="chart stk-bar" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" style="height:${height}px;">${lines}</svg>+ <span class="mono faint" style="text-align:right;">${fmt(total)}</span>+ </div>`;+ }).join('');+ const legend = segmentLabels ? `<div class="hint" style="margin-top:var(--sp-2);">${segmentLabels}</div>` : '';+ return `<div class="stacked">${body}</div>${legend}`;+};++// ----- Treemap (text hierarchy) ------------------------------++/**+ * Treemap — nested ranked list with indent and 1px bars. Replaces+ * Kibana "Treemap" (and arguably "Sunburst"). Accepts a tree of+ * { label, value, children? } nodes.+ */+export const Treemap = ({ items, depth = 0, parentTotal = null } = {}) => {+ if (!items || !items.length) return '';+ const total = parentTotal ?? (items.reduce((a, i) => a + i.value, 0) || 1);+ const max = Math.max(...items.map((i) => i.value));+ return items.map((it) => {+ const frac = it.value / max;+ const pct = ((it.value / total) * 100).toFixed(1);+ const x = (200 * frac).toFixed(1);+ const indent = '· '.repeat(depth);+ const kids = it.children && it.children.length+ ? Treemap({ items: it.children, depth: depth + 1, parentTotal: it.value })+ : '';+ return `+ <div class="row">+ <div class="row__label"><span class="faint">${indent}</span>${esc(it.label)}</div>+ <div class="row__val">${esc(fmt(it.value))}</div>+ <div class="row__bar">+ <svg class="chart" height="6" viewBox="0 0 200 6" preserveAspectRatio="none">+ <line x1="0" y1="5" x2="${x}" y2="5" stroke="currentColor" stroke-width="1" stroke-opacity="${(1 - depth * 0.2).toFixed(2)}"/>+ </svg>+ </div>+ <div class="row__pct">${pct}%</div>+ </div>+ ${kids}`;+ }).join('');+};diff --git a/xerj-ux/src/ux/charts-ops.js b/xerj-ux/src/ux/charts-ops.jsnew file mode 100644index 000000000..34711472a--- /dev/null+++ b/xerj-ux/src/ux/charts-ops.js@@ -0,0 +1,323 @@+// ============================================================+// XERJ.ai — Use-case primitives+//+// Shipping product features, not just pretty metrics:+// • SearchBox — interactive query console+// • QueryDSL — syntax-lit JSON of the query about to run+// • QueryPlanTree — recursive 1px-connector plan tree from+// `POST /v1/indices/:name/explain-plan`+// • Hits — result list with _score, _index, _id, _source+// • Facet — "click to filter" terms-agg row+// • AnomalyBand — 1px series with upper/lower normal band+// and ×-marked anomaly ticks+// • MetricTile — ultra-dense key/value tile for ops panels+// ============================================================++import { esc, fmt } from './text.js';++const minMax = (xs) => {+ let mn = Infinity, mx = -Infinity;+ for (const x of xs) { if (x < mn) mn = x; if (x > mx) mx = x; }+ return [mn === Infinity ? 0 : mn, mx === -Infinity ? 0 : mx];+};++// ============================================================+// SearchBox — the core of the SEARCH dashboard+// ============================================================+/**+ * Query console. Renders a typography-only "terminal":+ * [QUERY TYPE] [INDEX]+ * ▸ <input>____________________________________+ *+ * Events bubble:+ * [data-query-type] click → change query type+ * [data-search-input] Enter keyup → run search+ * [data-search-index] click → change index+ *+ * value, activeType, activeIndex come from app state.+ * types/indices drive the rows.+ */+export const SearchBox = ({+ value = '',+ types = ['match', 'term', 'range', 'prefix', 'phrase', 'knn', 'semantic', 'hybrid'],+ activeType = 'match',+ indices = ['*'],+ activeIndex = '*',+ filters = {},+ placeholder = "type a query · press Enter",+} = {}) => {+ // Filter pills row: shown only when at least one filter is active.+ // Each pill is a button with [data-facet-apply] which the existing app+ // click handler interprets as "toggle this filter off" (because clicking+ // a value that's already active removes it).+ const filterEntries = Object.entries(filters).filter(([, v]) => v != null && v !== '');+ const pillsRow = filterEntries.length ? `+ <div class="sbox-row sbox-pills">+ <span class="key" style="margin-right:12px;">FILTERS</span>+ ${filterEntries.map(([f, v]) =>+ `<button type="button" class="pill" data-facet-apply="${esc(f)}:${esc(v)}" title="Click to remove">+ <span class="pill-field">${esc(f)}</span><span class="pill-eq">=</span><span class="pill-val">${esc(v)}</span><span class="pill-x">✕</span>+ </button>`+ ).join('')}+ <button type="button" class="pill-clear" data-facet-clear>CLEAR ALL</button>+ </div>` : '';+ return `+<div class="sbox">+ <div class="sbox-row sbox-types">+ <span class="key" style="margin-right:12px;">QUERY</span>+ ${types.map((t) =>+ `<button type="button" data-query-type="${esc(t)}" class="${t === activeType ? 'active' : ''}">${esc(t.toUpperCase())}</button>`+ ).join('<span class="sep">·</span>')}+ <span class="spacer"></span>+ <span class="key" style="margin-right:12px;">INDEX</span>+ ${indices.map((i) =>+ `<button type="button" data-search-index="${esc(i)}" class="${i === activeIndex ? 'active' : ''}">${esc(i)}</button>`+ ).join('<span class="sep">·</span>')}+ </div>+ <div class="sbox-row sbox-input">+ <span class="prompt accent">▸</span>+ <input type="text" data-search-input value="${esc(value)}" placeholder="${esc(placeholder)}" autocomplete="off" spellcheck="false" aria-label="Search query"/>+ </div>+ ${pillsRow}+</div>`;+};++// ============================================================+// QueryDSL — the JSON about to be sent, with light syntax color+// ============================================================+/**+ * Shows the raw XERJ.ai query DSL that matches the current+ * SearchBox state. Keys are muted, strings are ink, numbers are+ * accent. No boxes, no frames.+ */+export const QueryDSL = (obj) => {+ const json = JSON.stringify(obj, null, 2);+ const out = esc(json)+ .replace(/"([^&]+?)"(\s*:)/g, '<span class="tok-key">"$1"</span>$2')+ .replace(/:\s*"([^&]*?)"/g, ': <span class="tok-str">"$1"</span>')+ .replace(/:\s*(-?\d+\.?\d*)/g, ': <span class="tok-num">$1</span>')+ .replace(/:\s*(true|false|null)\b/g, ': <span class="tok-kw">$1</span>');+ return `<pre class="qdsl mono">${out}</pre>`;+};++// ============================================================+// QueryPlanTree — what the planner picked, indented+// ============================================================+/**+ * Recursive render of a query plan tree. Each node has:+ * { op, field?, value?, estimate?, cost?, children? }+ * Indent is typographic, not graphic. Connectors are ASCII.+ */+export const QueryPlanTree = (node, depth = 0, last = true) => {+ if (!node) return '';+ const prefix = depth === 0 ? '' : (last ? '└─ ' : '├─ ');+ const indent = '<span class="faint mono">' + ('│ '.repeat(Math.max(0, depth - 1))) + prefix + '</span>';+ const est = node.estimate != null ? ` <span class="faint mono">est <span class="mono" style="color:var(--z-ink);">${fmt(node.estimate)}</span></span>` : '';+ const cost = node.cost != null ? ` <span class="faint mono">cost <span class="mono" style="color:var(--z-ink);">${fmt(node.cost)}</span></span>` : '';+ const field = node.field ? `<span class="mono" style="color:var(--z-ink);"> ${esc(node.field)}</span>` : '';+ const val = node.value != null ? `<span class="mono faint"> = ${esc(node.value)}</span>` : '';+ const selfRow = `<div class="plan-row">${indent}<span class="plan-op accent mono">${esc(node.op)}</span>${field}${val}${est}${cost}</div>`;+ const kids = (node.children || []);+ const childRows = kids.map((c, i) => QueryPlanTree(c, depth + 1, i === kids.length - 1)).join('');+ return selfRow + childRows;+};++// ============================================================+// Hits — search result list+// ============================================================+/**+ * Renders the hits returned by a search. Each row:+ * <index> <id> <score> <body>+ * Body is a one-line preview of _source. No frames.+ *+ * hits: [{ _index, _id, _score, _ts, _source }]+ * total,+ * tookMs — header line+ * sort: { field: '_score'|'_ts'|'_index'|'_id', dir: 'asc'|'desc' }+ * showTime: boolean — whether to render the _ts column (default true)+ * labels: { _index: 'INDEX', _id: 'ID', _score: 'SCORE', _ts: 'TIME' }+ * exportable: boolean — render the EXPORT CSV link in the header (default true)+ */+export const Hits = ({+ hits = [], total = 0, tookMs = 0, maxScore = null,+ sort = { field: '_score', dir: 'desc' },+ showTime = true,+ labels = { _index: 'INDEX', _id: 'ID', _score: 'SCORE', _ts: 'TIME' },+ exportable = true,+} = {}) => {+ const sortIndicator = (field) => {+ if (sort?.field !== field) return '';+ return sort.dir === 'asc' ? ' ▲' : ' ▼';+ };+ const colHeader = (field, label) =>+ `<button type="button" class="col-sort ${sort?.field === field ? 'active' : ''}" data-sort-field="${esc(field)}" data-sort-dir="${esc(sort?.field === field && sort.dir === 'desc' ? 'asc' : 'desc')}">${esc(label)}${sortIndicator(field)}</button>`;++ const header = `+ <div class="hits-meta">+ <span class="key">HITS</span>+ <span class="mono" style="margin-left:var(--sp-3);"><span class="accent" style="font-size:var(--fs-20); font-weight:700;">${fmt(total)}</span> <span class="faint">documents</span></span>+ <span class="mono" style="margin-left:var(--sp-3);"><span class="accent">${fmt(tookMs)}</span> <span class="faint">ms</span></span>+ ${maxScore != null ? `<span class="mono" style="margin-left:var(--sp-3);"><span class="faint">max_score</span> ${maxScore.toFixed(3)}</span>` : ''}+ <span style="flex:1;"></span>+ ${exportable ? `<button type="button" class="hits-action" data-export-csv title="GH#1992 · 372 reactions">↓ CSV</button>` : ''}+ <button type="button" class="hits-action" data-toggle-time aria-pressed="${showTime ? 'true' : 'false'}" title="GH#3319 · 44 reactions">${showTime ? 'HIDE TIME' : 'SHOW TIME'}</button>+ </div>`;++ if (!hits.length) {+ return header + `<div class="mono faint" style="padding:var(--sp-3) 0;">No matches. Try a broader query or a different query type.</div>`;+ }++ const colHead = `+ <div class="hit-head hit-headrow ${showTime ? '' : 'no-time'}">+ ${colHeader('_index', labels._index)}+ ${colHeader('_id', labels._id)}+ ${colHeader('_score', labels._score)}+ ${showTime ? colHeader('_ts', labels._ts) : ''}+ <span class="faint">${esc(labels._source || 'MESSAGE')}</span>+ </div>`;++ const rows = hits.map((h) => {+ const body = typeof h._source === 'string' ? h._source : JSON.stringify(h._source);+ return `+ <div class="hit">+ <div class="hit-head mono ${showTime ? '' : 'no-time'}">+ <button type="button" class="hit-cell-clickable" data-facet-apply="_index:${esc(h._index)}" title="Filter for this">${esc(h._index)}</button>+ <span class="faint">${esc(h._id)}</span>+ <span class="accent">${(h._score ?? 0).toFixed(3)}</span>+ ${showTime ? `<span class="faint">${esc(h._ts || '')}</span>` : ''}+ </div>+ <div class="hit-body mono">${esc(body)}</div>+ </div>`;+ }).join('');+ return header + colHead + `<div class="hits-list">${rows}</div>`;+};++// ============================================================+// Facet — a single terms-agg row as a clickable filter+// ============================================================+/**+ * One facet block: an eyebrow label + N rows where each row is+ * a click target `[data-facet-apply="field:value"]`.+ *+ * field: e.g. 'level'+ * items: [{ label, value, count }]+ * active: currently applied value (for styling)+ */+export const Facet = ({ field, items = [], active = null } = {}) => {+ if (!items.length) return '';+ const max = Math.max(...items.map((i) => i.count));+ const rows = items.map((i) => {+ const frac = i.count / (max || 1);+ const x = (180 * frac).toFixed(1);+ const on = i.value === active;+ return `+ <button type="button" class="facet-row ${on ? 'active' : ''}" data-facet-apply="${esc(field)}:${esc(i.value)}">+ <span class="facet-label">${esc(i.label)}</span>+ <span class="facet-count mono">${fmt(i.count)}</span>+ <svg class="chart facet-bar" height="5" viewBox="0 0 180 5" preserveAspectRatio="none">+ <line x1="0" y1="4" x2="${x}" y2="4" stroke="currentColor" stroke-width="1"/>+ </svg>+ </button>`;+ }).join('');+ return `<div class="facet"><div class="key" style="margin-bottom:6px;">${esc(field.toUpperCase())}</div>${rows}</div>`;+};++// ============================================================+// AnomalyBand — 1px line + rolling normal band + × marks+// ============================================================+/**+ * A time series with a rolling normal band computed upstream+ * (mean ± k*std). Anomalies are points outside the band; the+ * caller passes their indices.+ *+ * values, upper, lower: same length+ * anomalies: [{ idx, score }]+ * h: intrinsic SVG height+ * labels: ['START','END']+ */+export const AnomalyBand = ({+ values = [], upper = [], lower = [],+ anomalies = [], h = 200, labels = ['', ''], unit = '',+} = {}) => {+ if (!values.length) return '';+ const W = 1200;+ const all = values.concat(upper, lower);+ const [mn, mx] = minMax(all);+ const range = mx - mn || 1;+ const pad = 10;+ const py = (v) => pad + (h - pad * 2) - (((v - mn) / range) * (h - pad * 2));+ const px = (i, n) => ((i / (n - 1)) * W);+ const pts = (arr) => arr.map((v, i) => `${px(i, arr.length).toFixed(1)},${py(v).toFixed(1)}`).join(' ');+ const upperLine = upper.length ? `<polyline points="${pts(upper)}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="0.22"/>` : '';+ const lowerLine = lower.length ? `<polyline points="${pts(lower)}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="0.22"/>` : '';+ const valueLine = `<polyline points="${pts(values)}" fill="none" stroke="currentColor" stroke-width="1"/>`;+ const marks = anomalies.map(({ idx }) => {+ const x = px(idx, values.length).toFixed(1);+ const y = py(values[idx]).toFixed(1);+ return `+ <line x1="${x}" y1="${pad}" x2="${x}" y2="${h - pad}" stroke="var(--z-accent)" stroke-width="1" stroke-opacity="0.4"/>+ <text x="${x}" y="${(py(values[idx]) - 8).toFixed(1)}" fill="var(--z-accent)" font-family="var(--font-data)" font-size="14" text-anchor="middle">×</text>+ `;+ }).join('');+ const u = unit ? ' ' + esc(unit) : '';+ return `+ <svg class="chart" viewBox="0 0 ${W} ${h}" preserveAspectRatio="none" style="width:100%; height:${h}px;">+ ${upperLine}${lowerLine}${valueLine}${marks}+ </svg>+ <div class="series-legend">+ <span>${esc(labels[0] || '')} · <span class="mono" style="color:var(--z-ink);">${fmt(values[0])}${u}</span></span>+ <span class="mid">normal band · <span class="mono" style="color:var(--z-ink);">${fmt(Math.min(...lower))}..${fmt(Math.max(...upper))}${u}</span> · <span class="accent">${anomalies.length}</span> anomalies</span>+ <span><span class="mono" style="color:var(--z-ink);">${fmt(values[values.length - 1])}${u}</span> · ${esc(labels[1] || '')}</span>+ </div>`;+};++// ============================================================+// Citations — the link from a panel back to real user pain+// ============================================================+/**+ * Renders a row of citations attributing the dashboard to specific+ * user-feedback artifacts. Each entry comes from+ * `data/feedback-citations.js`, which is auto-generated from the+ * Kibana feedback corpus.+ *+ * items: [{ id, source, score, title, url }]+ */+export const Citations = ({ items = [], total = null } = {}) => {+ if (!items.length) {+ return `<div class="mono faint">No citations available — re-run <span class="accent">node user-feedback/kibana/pipeline/design-inputs.mjs</span></div>`;+ }+ const rows = items.map((c) => `+ <a class="cite" href="${esc(c.url)}" target="_blank" rel="noopener">+ <span class="cite-src mono faint">${esc((c.source || '').toUpperCase())}</span>+ <span class="cite-score mono accent">${c.score || 0}</span>+ <span class="cite-title">${esc(c.title || '— no title —')}</span>+ <span class="cite-arrow mono faint">↗</span>+ </a>+ `).join('');+ const meta = total != null+ ? `<div class="hint" style="margin-bottom:var(--sp-2);">drawn from <span class="mono accent">${total}</span> ranked artifacts in <span class="mono">user-feedback/kibana/themes/design-inputs.md</span></div>`+ : '';+ return meta + `<div class="cites">${rows}</div>`;+};++// ============================================================+// MetricTile — ultra-dense key/value row for ops dashboards+// ============================================================+/**+ * Not every metric deserves a 96px Num. MetricTile is a compact+ * row of label + value + optional spark/delta, six to a row.+ *+ * tiles: [{ label, value, unit?, spark?, delta?, deltaGood? }]+ */+export const MetricTile = ({ tiles = [] } = {}) => {+ const cells = tiles.map((t) => `+ <div class="mtile">+ <div class="mtile-head">+ <span class="key">${esc(t.label)}</span>+ ${t.delta != null ? `<span class="delta ${(t.deltaGood === 'down' ? (t.delta <= 0 ? 'good' : 'bad') : (t.delta >= 0 ? 'good' : 'bad'))}" style="font-size:var(--fs-11);">${t.delta >= 0 ? '▲' : '▼'} ${Math.abs(t.delta).toFixed(1)}%</span>` : ''}+ </div>+ <div class="mtile-val mono">${esc(t.value)}<span class="num-unit">${esc(t.unit || '')}</span></div>+ ${t.spark || ''}+ </div>`).join('');+ return `<div class="mtiles">${cells}</div>`;+};diff --git a/xerj-ux/src/ux/charts.js b/xerj-ux/src/ux/charts.jsnew file mode 100644index 000000000..82d52bb1a--- /dev/null+++ b/xerj-ux/src/ux/charts.js@@ -0,0 +1,171 @@+// ============================================================+// XERJ.ai — Chart primitives+// Every chart is 1px strokes or text. No fills, no dots, no+// axes, no grid, no legends. See UX_BOOK.md §3.+// ============================================================++import { esc, fmt } from './text.js';++const minMax = (xs) => {+ let mn = Infinity, mx = -Infinity;+ for (const x of xs) { if (x < mn) mn = x; if (x > mx) mx = x; }+ return [mn === Infinity ? 0 : mn, mx === -Infinity ? 0 : mx];+};++const buildPoints = (values, w, h) => {+ const [mn, mx] = minMax(values);+ const range = mx - mn || 1;+ const n = values.length;+ const step = n > 1 ? w / (n - 1) : w;+ let out = '';+ for (let i = 0; i < n; i++) {+ const x = (i * step).toFixed(2);+ const y = (h - ((values[i] - mn) / range) * h).toFixed(2);+ out += (i ? ' ' : '') + x + ',' + y;+ }+ return { pts: out, mn, mx };+};++// ----- Sparkline ---------------------------------------------++/**+ * Spark — a small inline 1px line chart. No axes, no dots, no fill.+ * Drop next to a Num for shape context.+ */+export const Spark = (values, { w = 140, h = 28, strokeOpacity = 1 } = {}) => {+ if (!values || values.length < 2) return '';+ const { pts } = buildPoints(values, w, h);+ return `<svg class="chart" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" aria-hidden="true">+ <polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1" stroke-opacity="${strokeOpacity}"/>+ </svg>`;+};++// ----- Full-width time series --------------------------------++/**+ * Series — a full-width 1px time line.+ * No axes. Endpoint labels and min/peak are annotated BELOW the curve,+ * never floating over it.+ *+ * values: number[]+ * h: intrinsic viewBox height (pixels); width stretches to container+ * labels: ['start label', 'end label']+ * unit: optional unit string shown with min/peak+ */+export const Series = (values, {+ h = 140,+ labels = ['', ''],+ unit = '',+} = {}) => {+ if (!values || values.length < 2) return '';+ const w = 1200;+ const { pts, mn, mx } = buildPoints(values, w, h);+ const u = unit ? ' ' + esc(unit) : '';+ return `+ <div class="series-wrap">+ <svg class="chart series" height="${h}" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">+ <polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1"/>+ </svg>+ <div class="series-legend">+ <span>${esc(labels[0] ?? '')} · <span class="mono" style="color:var(--z-ink);">${fmt(values[0])}${u}</span></span>+ <span class="mid">min <span class="mono" style="color:var(--z-ink);">${fmt(mn)}${u}</span> · peak <span class="mono" style="color:var(--z-ink);">${fmt(mx)}${u}</span></span>+ <span><span class="mono" style="color:var(--z-ink);">${fmt(values[values.length - 1])}${u}</span> · ${esc(labels[1] ?? '')}</span>+ </div>+ </div>`;+};++// ----- Distribution (replaces pies & donuts) -----------------++/**+ * Dist — a single horizontal 1px line broken into parts by stroke-opacity.+ * Below it, each segment renders as a labeled micro-metric.+ *+ * segments: [{ label, value }]+ * width: svg viewBox width+ */+export const Dist = ({ segments, width = 1200, height = 10 } = {}) => {+ if (!segments || !segments.length) return '';+ const total = segments.reduce((a, s) => a + s.value, 0) || 1;+ let x = 0;+ const lines = [];+ segments.forEach((s, i) => {+ const segW = (s.value / total) * width;+ const op = Math.max(0.12, 1 - i * 0.14);+ if (segW > 0.5) {+ lines.push(+ `<line x1="${x.toFixed(1)}" y1="${(height - 1).toFixed(1)}" x2="${(x + segW).toFixed(1)}" y2="${(height - 1).toFixed(1)}" stroke="currentColor" stroke-width="1" stroke-opacity="${op.toFixed(2)}"/>`+ );+ }+ x += segW;+ });+ const legend = segments.map((s, i) => {+ const pct = (100 * s.value / total).toFixed(1);+ return `+ <div class="stack" style="gap:6px;">+ <span class="key">${esc(s.label)}</span>+ <span class="mono" style="font-size:var(--fs-20); font-weight:700;">${fmt(s.value)}</span>+ <span class="mono faint" style="font-size:var(--fs-11);">${pct}%</span>+ </div>`;+ }).join('');+ return `+ <svg class="chart dist-bar" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none">${lines.join('')}</svg>+ <div class="dist-legend">${legend}</div>+ `;+};++// ----- Character-intensity heatmap ---------------------------++/**+ * Heatmap — a grid of NUMBERS whose text opacity encodes magnitude. The+ * data IS the visualization. No boxes, no cells, no colors.+ *+ * rows: string[] (row labels)+ * cols: string[] (col labels)+ * matrix: number[][] (rows × cols)+ * cellFmt: (v) => string — how to render each cell (default: compact)+ */+export const Heatmap = ({ rows, cols, matrix, cellFmt = (v) => fmt(v) } = {}) => {+ if (!matrix || !matrix.length) return '';+ const flat = matrix.flat();+ const [mn, mx] = minMax(flat);+ const range = mx - mn || 1;+ // Cell width = max rendered length + 1 space, so columns align.+ let maxLen = 0;+ for (const v of flat) {+ const l = String(cellFmt(v)).length;+ if (l > maxLen) maxLen = l;+ }+ const widthCh = Math.max(3, maxLen + 1);+ const header = `<div class="heatmap-row heatmap-head"><span class="row-label">\u00a0</span>${cols.map(c =>+ `<span style="display:inline-block; width:${widthCh}ch; text-align:right; color:var(--z-mute);">${esc(c)}</span>`+ ).join('')}</div>`;+ const body = matrix.map((row, i) => {+ const cells = row.map((v) => {+ const t = (v - mn) / range;+ const op = (0.16 + 0.84 * t).toFixed(2);+ return `<span style="display:inline-block; width:${widthCh}ch; text-align:right; opacity:${op};">${esc(cellFmt(v))}</span>`;+ }).join('');+ return `<div class="heatmap-row"><span class="row-label">${esc(rows[i] ?? '')}</span>${cells}</div>`;+ }).join('');+ return `<div class="heatmap">${header}${body}</div>`;+};++// ----- Small multiples ---------------------------------------++/**+ * Multiples — grid of labeled sparklines.+ * items: [{ label, values, value }]+ */+export const Multiples = ({ items, w = 160, h = 22 } = {}) => {+ if (!items || !items.length) return '';+ const cells = items.map(({ label, values, value }) => `+ <div class="mult">+ <div class="mult-head">+ <span class="name">${esc(label)}</span>+ <span class="val">${value != null ? esc(value) : ''}</span>+ </div>+ ${Spark(values, { w, h })}+ </div>+ `).join('');+ return `<div class="multiples">${cells}</div>`;+};diff --git a/xerj-ux/src/ux/chrome.js b/xerj-ux/src/ux/chrome.jsnew file mode 100644index 000000000..18f8d346b--- /dev/null+++ b/xerj-ux/src/ux/chrome.js@@ -0,0 +1,312 @@+// ============================================================+// XERJ.ai — Chrome: nav, scene header, time control, footer+// Pure text. Buttons are `<button>` for a11y but styled as text.+// ============================================================++import { esc } from './text.js';++/**+ * ThemeCtrl — text-only day/night toggle. Emits `[data-theme]` clicks+ * handled by the app router.+ */+export const ThemeCtrl = ({ active = 'night' } = {}) => `+<span class="theme" role="group" aria-label="Theme">+ <button type="button" data-theme-set="day" class="${active === 'day' ? 'active' : ''}" aria-pressed="${active === 'day'}">DAY</button>+ <span class="dash">·</span>+ <button type="button" data-theme-set="night" class="${active === 'night' ? 'active' : ''}" aria-pressed="${active === 'night'}">NIGHT</button>+</span>`;++export const MobileCtrl = ({ active = false } = {}) => `+<span class="mobile-ctrl" role="group" aria-label="Mobile preview">+ <button type="button" data-mobile-toggle class="${active ? 'active' : ''}" aria-pressed="${active}">MOBILE</button>+</span>`;++/**+ * EditCtrl — text-only edit-mode toggle. When active also shows RESET.+ */+export const EditCtrl = ({ active = false } = {}) => `+<span class="edit-ctrl" role="group" aria-label="Edit mode">+ <button type="button" data-edit-toggle class="${active ? 'active' : ''}" aria-pressed="${active}">EDIT</button>+ ${active ? `<span class="dash">·</span><button type="button" data-reset-layout>RESET</button>` : ''}+</span>`;++/**+ * Nav — the top bar. Two rows:+ * Row 1 (always): brand + primary sections + edit/theme/status+ * Row 2 (only when section='dashboards'): grouped dashboards list+ *+ * The secondary row is "folder tabs": each `group` is shown as a+ * label, and the ACTIVE group's members render inline next to it.+ * Other groups collapse to just their label — click them to switch+ * groups (lands on the group's first dashboard). This handles+ * screens too narrow to fit every dashboard on one line.+ *+ * sections: [{ id, label }] — primary product sections+ * activeSection: id+ * dashboards: [{ id, name, group }] — dashboards under the active section+ * groups: [{ id, label }] — ordered group list for the sub-nav+ * activeDash: id — currently-selected dashboard+ */+export const Nav = ({+ sections = [],+ activeSection = 'dashboards',+ dashboards = [],+ groups = [],+ activeDash = '',+ theme = 'night',+ edit = false,+ mobile = false,+ status = '',+} = {}) => {+ const primaryLinks = sections.map((s) => {+ const href = s.id === 'dashboards' ? '#/dashboards' : '#/' + s.id;+ return `<a href="${href}" data-section="${esc(s.id)}" class="${s.id === activeSection ? 'active' : ''}">${esc(s.label)}</a>`;+ }).join('');++ const showSecondary = activeSection === 'dashboards' && dashboards.length > 0;+ let secondary = '';+ if (showSecondary) {+ // If we have groups, bucket dashboards by group; otherwise fall+ // back to a flat list (backward compatibility with any future+ // dashboard that omits a group).+ const byGroup = {};+ for (const d of dashboards) {+ const g = d.group || 'other';+ (byGroup[g] = byGroup[g] || []).push(d);+ }+ // Determine the active group from the active dashboard.+ const activeDashObj = dashboards.find((d) => d.id === activeDash);+ const activeGroup = activeDashObj?.group || (groups[0]?.id || 'other');++ // Stable order: the `groups` registry. Any group that exists in+ // data but not in the registry is appended at the end.+ const orderedGroups = [];+ const seen = new Set();+ for (const g of groups) {+ if (byGroup[g.id]) { orderedGroups.push({ ...g, members: byGroup[g.id] }); seen.add(g.id); }+ }+ for (const gid of Object.keys(byGroup)) {+ if (!seen.has(gid)) orderedGroups.push({ id: gid, label: gid.toUpperCase(), members: byGroup[gid] });+ }++ const groupHtml = orderedGroups.map((g) => {+ const isActive = g.id === activeGroup;+ const members = isActive+ ? g.members.map((d) =>+ `<a href="#/dashboards/${esc(d.id)}" data-dash="${esc(d.id)}" class="${d.id === activeDash ? 'active' : ''}">${esc(d.name)}</a>`+ ).join('')+ : '';+ const firstId = g.members[0]?.id || '';+ const labelCls = 'group-label' + (isActive ? ' active' : '');+ return `+ <span class="group${isActive ? ' open' : ''}">+ <button type="button" class="${labelCls}" data-dash-group="${esc(g.id)}" data-dash-group-first="${esc(firstId)}" aria-expanded="${isActive}">${esc(g.label)}</button>+ ${isActive ? `<span class="members">${members}</span>` : ''}+ </span>`;+ }).join('');++ secondary = `<nav class="nav-sub" aria-label="Dashboards">${groupHtml}</nav>`;+ }++ return `+<nav class="nav" aria-label="Product">+ <span class="brand">XERJ CONSOLE</span>+ ${primaryLinks}+ <span class="spacer"></span>+ ${EditCtrl({ active: edit })}+ ${MobileCtrl({ active: mobile })}+ ${ThemeCtrl({ active: theme })}+ ${status ? `<span class="status">${esc(status)}</span>` : ''}+</nav>+${secondary}`;+};++/**+ * SceneHeader — the 96px scene title with kicker. One per view.+ * title: string+ * kicker: string (displayed above the title in small caps)+ * meta: optional array of strings rendered next to the kicker+ * editable: if true, the title becomes click-to-rename via contenteditable+ * dashId: the dashboard id (needed when editable=true so the rename+ * handler knows which dashboard to persist)+ */+export const SceneHeader = ({ title, kicker = '', meta = [], editable = false, dashId = '' } = {}) => {+ const bits = [kicker, ...meta].filter(Boolean);+ const kickerLine = bits.length+ ? `<div class="kicker"><span class="key">${bits.map(esc).join(+ '</span><span class="dash">·</span><span class="key">'+ )}</span></div>`+ : '';+ const editAttrs = editable+ ? ` contenteditable="true" spellcheck="false" data-rename-dash="${esc(dashId)}" title="Click to rename · Enter to save · Esc to cancel"`+ : '';+ return `+<header class="scene">+ ${kickerLine}+ <h1 class="h-scene${editable ? ' editable' : ''}"${editAttrs}>${esc(title)}</h1>+</header>`;+};++/**+ * TimeCtrl — inline range selector. Emits `[data-time]` click events+ * handled by the app router. Adds a CUSTOM slot that reveals two+ * datetime-local inputs for an absolute from/to range — a top-15+ * corpus ask that Kibana already supports and users expect.+ */+export const TimeCtrl = ({+ ranges = ['1H','24H','7D','30D','90D'],+ active = '24H',+ custom = { from: '', to: '' },+} = {}) => {+ const buttons = ranges.map((r) =>+ `<button type="button" data-time="${esc(r)}" class="${r === active ? 'active' : ''}" aria-pressed="${r === active}">${esc(r)}</button>`+ ).join('');+ const isCustom = active === 'CUSTOM';+ const customBtn = `<button type="button" data-time="CUSTOM" class="${isCustom ? 'active' : ''}" aria-pressed="${isCustom}">CUSTOM</button>`;+ const customInputs = isCustom ? `+ <span class="custom-range">+ <input type="datetime-local" data-time-from value="${esc(custom.from || '')}" aria-label="From" />+ <span class="dash">→</span>+ <input type="datetime-local" data-time-to value="${esc(custom.to || '')}" aria-label="To" />+ </span>` : '';+ return `+ <div class="time" role="group" aria-label="Time range">+ <span class="key">RANGE</span>+ ${buttons}+ ${customBtn}+ ${customInputs}+ </div>`;+};++/**+ * RefreshCtrl — auto-refresh interval picker (milliseconds). 0 = off.+ * Corpus evidence: auto-refresh is in the Kibana top-5 user asks —+ * users want live dashboards without a full page reload.+ */+export const RefreshCtrl = ({+ intervals = [+ { ms: 0, label: 'OFF' },+ { ms: 10_000, label: '10S' },+ { ms: 30_000, label: '30S' },+ { ms: 60_000, label: '1M' },+ { ms: 300_000, label: '5M' },+ ],+ active = 0,+} = {}) => `+<div class="refresh" role="group" aria-label="Auto-refresh">+ <span class="key">REFRESH</span>+ ${intervals.map((iv) =>+ `<button type="button" data-refresh="${iv.ms}" class="${iv.ms === active ? 'active' : ''}" aria-pressed="${iv.ms === active}">${esc(iv.label)}</button>`+ ).join('')}+</div>`;++/**+ * FilterBar — global filter pills row + KQL-lite search input.+ * Lives between the time control and the canvas on every dashboard.+ * Fixes the #1 Kibana authoring pain: filters are a dashboard-level+ * concept, not a per-panel one. Plus the GH#3693 ask for OR filters:+ * a field can hold an array of values rendered as `field : a | b`.+ *+ * filters: { [field]: value | value[] } — current dashboard filters+ * kql: the current text in the KQL input (preserved across renders)+ *+ * Pills emit:+ * [data-filter-remove="field:value"] — remove one value from field+ * [data-filter-clear] — clear everything+ * [data-kql-input] — the search input (Enter to run)+ */+export const FilterBar = ({ filters = {}, kql = '' } = {}) => {+ const entries = Object.entries(filters);+ const pills = entries.map(([field, value]) => {+ const values = Array.isArray(value) ? value : [value];+ const chips = values.map((v, i) => `+ ${i > 0 ? '<span class="or">OR</span>' : ''}+ <button type="button" class="chip" data-filter-remove="${esc(field)}:${esc(v)}" title="Remove ${esc(field)} = ${esc(v)}">+ <span class="value">${esc(v)}</span>+ <span class="x">✕</span>+ </button>+ `).join('');+ return `+ <span class="pill active">+ <span class="field">${esc(field)}</span>+ <span class="eq">:</span>+ ${chips}+ </span>`;+ }).join('');++ const hint = entries.length+ ? ''+ : `<span class="hint mono faint">TYPE <span class="mono">field:value</span> ABOVE · OR CLICK A LABEL IN A CHART</span>`;+ const clearBtn = entries.length+ ? `<button type="button" class="clear" data-filter-clear>CLEAR ALL</button>`+ : '';++ return `+ <div class="filter-bar${entries.length ? '' : ' empty'}" aria-label="Filters">+ <div class="kql">+ <span class="key">KQL</span>+ <input type="text" data-kql-input value="${esc(kql)}" placeholder="service:auth level:error "login failed"" spellcheck="false" autocomplete="off" />+ </div>+ <div class="pills">+ <span class="key">FILTER</span>+ ${pills}+ ${hint}+ ${clearBtn}+ </div>+ </div>`;+};++/**+ * SavedViews — a named snapshot of (dashId, time, cluster, filters).+ * Rendered as a one-line row below the filter bar on dashboards.+ * Kibana equivalent: saved searches / dashboard links. Top-5 corpus+ * ask — users want to pin a context they can jump back to.+ */+export const SavedViews = ({ views = [], dashId = '' } = {}) => {+ const mine = views.filter((v) => v.dashId === dashId);+ const saveBtn = `<button type="button" class="save" data-view-save>+ SAVE CURRENT VIEW</button>`;+ if (!mine.length) {+ return `+ <div class="saved-views empty" aria-label="Saved views">+ <span class="key">VIEWS</span>+ <span class="hint mono faint">NO SAVED VIEWS</span>+ ${saveBtn}+ </div>`;+ }+ const links = mine.map((v) => `+ <button type="button" class="view" data-view-apply="${esc(v.id)}" title="Apply view">${esc(v.name)}</button>+ <button type="button" class="x" data-view-delete="${esc(v.id)}" title="Delete view" aria-label="Delete view">✕</button>+ `).join('<span class="sep">·</span>');+ return `+ <div class="saved-views" aria-label="Saved views">+ <span class="key">VIEWS</span>+ ${links}+ ${saveBtn}+ </div>`;+};++/**+ * ClusterCtrl — dropdown-as-text cluster selector. Shown on dashboards+ * that hit cluster-scoped data. Emits `[data-cluster-set]`.+ */+export const ClusterCtrl = ({ clusters = [], active = '' } = {}) => {+ if (!clusters.length) return '';+ return `+ <div class="cluster-ctrl" role="group" aria-label="Cluster">+ <span class="key">CLUSTER</span>+ ${clusters.map((c) =>+ `<button type="button" data-cluster-set="${esc(c.id)}" class="${c.id === active ? 'active' : ''}" aria-pressed="${c.id === active}">${esc(c.name || c.id)}</button>`+ ).join('')}+ </div>`;+};++/** Footer — one line, mute, uppercase. No border. */+export const Footer = ({ version = 'v0.1' } = {}) => {+ const now = new Date().toISOString().slice(0, 16).replace('T', ' · ');+ return `+<footer class="footer">+ <span>XERJ CONSOLE · ${esc(version)}</span>+ <span>TYPE IS THE UI</span>+ <span>${esc(now)}</span>+</footer>`;+};diff --git a/xerj-ux/src/ux/layout.js b/xerj-ux/src/ux/layout.jsnew file mode 100644index 000000000..e3dae9959--- /dev/null+++ b/xerj-ux/src/ux/layout.js@@ -0,0 +1,93 @@+// ============================================================+// XERJ.ai — Layout primitives+// Panel, TopN. Nothing more. See UX_BOOK.md §3.+// ============================================================++import { esc, fmt } from './text.js';++/**+ * Panel — a slot in the 12-column canvas grid.+ * Renders NO box, NO border, NO background. The only chrome a panel+ * has is: an eyebrow line above the content, and its column span.+ *+ * eyebrow: small-caps label (the panel's identity)+ * title: optional section heading below the eyebrow+ * cols: 1..12 column span+ * children: string or string[]+ */+export const Panel = ({ eyebrow, title, cols = 6, children = '' } = {}) => {+ const body = Array.isArray(children) ? children.join('') : children;+ return `+<section class="panel" style="grid-column: span ${cols};">+ ${eyebrow ? `<div class="key">${esc(eyebrow)}</div>` : ''}+ ${title ? `<div class="h-section">${esc(title)}</div>` : ''}+ ${body}+</section>`;+};++/**+ * TopN — the ranked list. Replaces pies, donuts, treemaps, and most+ * bar charts. Every observability question starts with "top what?".+ *+ * items: [{ label, value }]+ * total: optional total for percentage column+ * n: limit (default 10)+ * valueFmt: function to render the value (default compact number)+ * barWidth: svg viewBox width for the 1px fill line (default 200)+ * scale: 'max' (relative to row max) | 'total' (relative to total)+ * filterField: if set, each row becomes click-to-filter on this field.+ * Clicking a row emits a `[data-filter-add]` event the+ * app router catches and turns into a global filter pill.+ */+export const TopN = ({+ items,+ total,+ n = 10,+ valueFmt = (v) => fmt(v),+ barWidth = 200,+ scale = 'max',+ filterField = '',+} = {}) => {+ if (!items || !items.length) return '<div class="faint mono">No data.</div>';+ const slice = items.slice(0, n);+ const max = Math.max(...slice.map((i) => i.value));+ const denom = scale === 'total' && total ? total : max;+ const out = slice.map((i) => {+ const frac = denom > 0 ? Math.max(0, Math.min(1, i.value / denom)) : 0;+ const pct = total ? ((100 * i.value) / total).toFixed(1) + '%' : '';+ const x = (frac * barWidth).toFixed(1);+ const clickable = filterField+ ? ` data-filter-add="${esc(filterField)}:${esc(i.label)}" role="button" title="Filter ${esc(filterField)} = ${esc(i.label)}"`+ : '';+ return `+ <div class="row${filterField ? ' clickable' : ''}"${clickable}>+ <div class="row__label">${esc(i.label)}</div>+ <div class="row__val">${esc(valueFmt(i.value))}</div>+ <div class="row__bar">+ <svg class="chart" height="6" viewBox="0 0 ${barWidth} 6" preserveAspectRatio="none">+ <line x1="0" y1="5" x2="${x}" y2="5" stroke="currentColor" stroke-width="1"/>+ </svg>+ </div>+ <div class="row__pct">${esc(pct)}</div>+ </div>`;+ }).join('');+ return out;+};++/**+ * Events — a text list of recent events. Three-column grid: time, severity,+ * message. No cells, no borders. Severity `err` lights the accent.+ *+ * items: [{ at: ISO or HH:mm:ss, sev: 'info'|'warn'|'err', msg: string }]+ */+export const Events = ({ items } = {}) => {+ if (!items || !items.length) return '<div class="faint mono">No events.</div>';+ const rows = items.map((e) => `+ <div class="ev">+ <span class="when">${esc(e.at)}</span>+ <span class="sev ${e.sev === 'err' ? 'err' : ''}">${esc((e.sev || '').toUpperCase())}</span>+ <span class="msg">${esc(e.msg)}</span>+ </div>+ `).join('');+ return `<div class="events">${rows}</div>`;+};diff --git a/xerj-ux/src/ux/tables.js b/xerj-ux/src/ux/tables.jsnew file mode 100644index 000000000..fec99a698--- /dev/null+++ b/xerj-ux/src/ux/tables.js@@ -0,0 +1,54 @@+// ============================================================+// XERJ.ai — Table + Markdown primitives+// Plain text, no borders, no zebra stripes, no cell backgrounds.+// ============================================================++import { esc } from './text.js';++/**+ * Table — borderless tabular data. Replaces Kibana "Data Table".+ *+ * columns: ['NAME', 'COUNT', ...]+ * rows: [[cell, cell, ...], ...]+ * align: ['left'|'right'|'center', ...] — per column+ */+export const Table = ({ columns, rows, align = [] } = {}) => {+ if (!columns || !columns.length) return '<div class="faint mono">No columns.</div>';+ const ta = (i) => align[i] || (i === 0 ? 'left' : 'right');+ const cols = columns.length;+ const headCells = columns.map((c, i) =>+ `<span style="text-align:${ta(i)}">${esc(c)}</span>`+ ).join('');+ const bodyRows = (rows || []).map((r) => {+ const cells = r.map((c, i) =>+ `<span style="text-align:${ta(i)}">${esc(c)}</span>`+ ).join('');+ return `<div class="tbl-row">${cells}</div>`;+ }).join('');+ return `+ <div class="tbl" style="--tbl-cols:${cols};">+ <div class="tbl-row tbl-head">${headCells}</div>+ ${bodyRows}+ </div>`;+};++/**+ * Markdown — very light markdown for annotation panels.+ * Supports: **bold**, *italic*, `code`, # heading, ## eyebrow, blank-line paragraphs.+ * No HTML injection — everything runs through `esc` first.+ */+export const Markdown = (text = '') => {+ if (!text) return '';+ const paragraphs = text.split(/\n\n+/).map((p) => {+ const t = p.trim();+ if (!t) return '';+ if (t.startsWith('# ')) return `<div class="h-section" style="margin-bottom:10px;">${esc(t.slice(2))}</div>`;+ if (t.startsWith('## ')) return `<div class="key" style="margin-bottom:8px;">${esc(t.slice(3))}</div>`;+ const e = esc(t)+ .replace(/\*\*(.+?)\*\*/g, '<strong style="color:var(--z-ink);">$1</strong>')+ .replace(/\*(.+?)\*/g, '<em>$1</em>')+ .replace(/`([^`]+)`/g, '<span class="mono accent">$1</span>');+ return `<p style="max-width:60ch; margin-bottom:10px;">${e}</p>`;+ }).filter(Boolean).join('');+ return `<div class="md" style="font-family:var(--font-prose); font-size:var(--fs-13); line-height:1.6; color:var(--z-mute);">${paragraphs}</div>`;+};diff --git a/xerj-ux/src/ux/text.js b/xerj-ux/src/ux/text.jsnew file mode 100644index 000000000..4521edeae--- /dev/null+++ b/xerj-ux/src/ux/text.js@@ -0,0 +1,121 @@+// ============================================================+// XERJ.ai — Text primitives+// Every component is a pure function returning an HTML string.+// No state, no events, no DOM access. See UX_BOOK.md §3.+// ============================================================++/** Escape user text for safe interpolation into template strings. */+export const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ }[c]));++/** Compact number formatter (4.82M, 12.3K, 0.83). */+const nf = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });+export const fmt = (v, { decimals } = {}) => {+ if (v == null || Number.isNaN(v)) return '—';+ if (decimals != null) return Number(v).toFixed(decimals);+ if (Math.abs(v) < 1) return Number(v).toFixed(2);+ if (Math.abs(v) < 100) return Number(v).toFixed(1);+ return nf.format(v);+};++/** Pad an integer string to a fixed width with thin spaces (looks tabular). */+export const num = (v) => new Intl.NumberFormat('en').format(v);++// ----- Eyebrow / headings ------------------------------------++/** Small-caps eyebrow label. The ONLY way to title a panel. */+export const Key = (text) => `<div class="key">${esc(text)}</div>`;++/** `role` ∈ 'scene' | 'section'. Scene is once per view. */+export const H = (role, text) => {+ const cls = role === 'scene' ? 'h-scene' : 'h-section';+ const tag = role === 'scene' ? 'h1' : 'h2';+ return `<${tag} class="${cls}">${esc(text)}</${tag}>`;+};++// ----- Delta indicator ---------------------------------------++/**+ * `▲ 12.3%` / `▼ 0.12%` — standalone delta.+ * `good: 'up' | 'down' | null` — which direction lights the accent.+ * If `good` is null, delta is always muted (neutral).+ */+export const Change = (pct, { good = 'up', unit = '%', fractionDigits = 1 } = {}) => {+ if (pct == null || Number.isNaN(pct)) return '';+ const up = pct >= 0;+ const arrow = up ? '▲' : '▼';+ const abs = Math.abs(pct).toFixed(fractionDigits);+ let klass = 'meh';+ if (good === 'up') klass = up ? 'good' : 'bad';+ else if (good === 'down') klass = up ? 'bad' : 'good';+ return `<span class="delta ${klass}">${arrow} ${abs}${esc(unit)}</span>`;+};++// ----- Headline metric ---------------------------------------++/**+ * Num — the point of every panel.+ * value: string or number (preformatted is fine)+ * unit: short unit like 'events', 'e/s', '%', 'ms'+ * spark: optional Spark(...) string rendered to the right+ * delta: signed percent, rendered with Change+ * deltaGood: 'up' | 'down' | null — which direction is "good"+ * hint: small mono hint rendered below ('at 14:23', etc.)+ * emphasis: true → 96/56px display + accent; false → 32px ink+ */+export const Num = ({+ value,+ unit = '',+ spark = '',+ delta = null,+ deltaGood = 'up',+ hint = '',+ emphasis = true,+} = {}) => {+ const valCls = emphasis ? 'num-big accent' : 'num-md';+ const unitSpan = unit ? `<span class="num-unit">${esc(unit)}</span>` : '';+ const deltaPart = delta != null ? Change(delta, { good: deltaGood }) : '';+ const hintPart = hint+ ? `<span class="hint">${esc(hint)}</span>`+ : '';+ const foot = (deltaPart || hintPart)+ ? `<div class="row-flex" style="margin-top:10px;">${deltaPart}${hintPart}</div>`+ : '';+ return `+ <div class="stack">+ <div class="row-flex">+ <div class="${valCls}">${esc(value)}${unitSpan}</div>+ ${spark}+ </div>+ ${foot}+ </div>`;+};++// ----- Horizontal-bar row (one line of a TopN) ---------------++/**+ * A single ranked row. Use `TopN` to render lists; this is exported so you+ * can hand-build a row in custom panels.+ */+export const HBar = ({ label, value, pct, frac, barWidth = 200 }) => {+ const f = Math.max(0, Math.min(1, frac ?? 0));+ const x = (f * barWidth).toFixed(1);+ return `+ <div class="row">+ <div class="row__label">${esc(label)}</div>+ <div class="row__val">${esc(value)}</div>+ <div class="row__bar">+ <svg class="chart" height="6" viewBox="0 0 ${barWidth} 6" preserveAspectRatio="none">+ <line x1="0" y1="5" x2="${x}" y2="5" stroke="currentColor" stroke-width="1"/>+ </svg>+ </div>+ <div class="row__pct">${pct != null ? esc(pct) : ''}</div>+ </div>`;+};++// ----- Inline key/value used in scene kicker ----------------++export const Kv = (k, v) =>+ `<span class="mono"><span class="faint">${esc(k)}</span> ${esc(v)}</span>`;diff --git a/xerj-ux/src/xerj-console-auth.js b/xerj-ux/src/xerj-console-auth.jsnew file mode 100644index 000000000..bf6a5e0fa--- /dev/null+++ b/xerj-ux/src/xerj-console-auth.js@@ -0,0 +1,92 @@+// Xerj Console auth API client.+//+// Tiny fetch wrapper for the /_xerj-console/api/v1/auth/* surface. Used by+// setup.html, login.html, and the SPA's auth guard. Never imports+// from the rest of the app so it stays loadable on the standalone+// auth pages without dragging the whole bundle in.++const API = '/_xerj-console/api/v1';++export async function api(method, path, body) {+ const init = {+ method,+ credentials: 'same-origin',+ headers: { 'accept': 'application/json' },+ };+ if (body !== undefined) {+ init.headers['content-type'] = 'application/json';+ init.body = JSON.stringify(body);+ }+ const r = await fetch(API + path, init);+ let payload = null;+ try { payload = await r.json(); } catch {}+ if (!r.ok) {+ const reason = payload && payload.error+ ? `${payload.error.type}: ${payload.error.reason}`+ : `HTTP ${r.status}`;+ throw new Error(reason);+ }+ return payload && payload.data !== undefined ? payload.data : payload;+}++// ─── Magic-link redemption ───────────────────────────────────────────────────++export async function redeemMagic(token) {+ return api('POST', '/auth/magic/redeem', { token });+}++// ─── Passkey enrolment ──────────────────────────────────────────────────────++export async function beginEnrol(enrollment_session_id, email, display_name) {+ return api('POST', '/auth/passkey/begin', {+ enrollment_session_id, email, display_name,+ });+}++export async function finishEnrol(+ enrollment_session_id, challenge_id, credential, name, email, display_name+) {+ return api('POST', '/auth/passkey/finish', {+ enrollment_session_id, challenge_id, credential, name, email, display_name,+ });+}++// ─── Login ──────────────────────────────────────────────────────────────────++export async function beginLogin(email) {+ return api('POST', '/auth/login/begin', { email });+}++export async function finishLogin(challenge_id, credential) {+ return api('POST', '/auth/login/finish', { challenge_id, credential });+}++export async function logout() {+ return api('POST', '/auth/logout');+}++export async function me() {+ return api('GET', '/me');+}++// ─── Base64url ↔ ArrayBuffer ────────────────────────────────────────────────+// WebAuthn's JSON wire format encodes binary fields as base64url-no-pad,+// but the browser's `navigator.credentials.create/get` API expects+// ArrayBuffer for `challenge`, `user.id`, credential `id`, etc. These+// helpers convert in both directions.++export function b64uToBuf(s) {+ const pad = '='.repeat((4 - (s.length % 4)) % 4);+ const b64 = (s + pad).replace(/-/g, '+').replace(/_/g, '/');+ const bin = atob(b64);+ const buf = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);+ return buf.buffer;+}++export function bufToB64u(buf) {+ const bytes = new Uint8Array(buf);+ let bin = '';+ for (let i = 0; i < bytes.byteLength; i++) bin += String.fromCharCode(bytes[i]);+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}diff --git a/xerj-ux/src/xerj-console-sync.js b/xerj-ux/src/xerj-console-sync.jsnew file mode 100644index 000000000..eee5ae3a6--- /dev/null+++ b/xerj-ux/src/xerj-console-sync.js@@ -0,0 +1,206 @@+// xerj-console-sync.js — durable persistence for the SPA.+//+// The existing SPA (`app.js`) reads and writes a handful of well-known+// keys under localStorage (`xerj.theme`, `xerj.time`, `xerj.views`,+// …). This module makes those values durable across browsers and+// machines by mirroring them to /_xerj-console/api/v1/prefs and+// /_xerj-console/api/v1/views.+//+// It is **non-invasive**: app.js is not modified. Instead we+//+// 1. on boot, **pull** the server-side values and write them into+// localStorage *before* app.js reads them at module load, and+// 2. periodically (every 1.5s) **push** any local changes back to+// the server, debounced so a slider drag does not spam writes.+//+// Both halves are best-effort. An unreachable backend (offline dev,+// hot-reload mid-flight, network blip) silently falls back to plain+// localStorage so the SPA never gets stuck.++import { api } from './xerj-console-auth.js';++// ── Keys we mirror as a single `/prefs` document. ────────────────────────────+// `xerj.search` is intentionally excluded — it's the search box's last+// query, which is per-tab ephemera, not "user prefs".+// `xerj.dashboards` IS included: it carries the user's dashboard+// metadata (renames, order, hidden flags, user-cloned dashboards),+// which the demo wants to persist across sessions and machines.+// Per-dashboard panel layouts (`xerj.layout.<id>`) and per-dashboard+// filters (`xerj.filters.<id>`) are aggregated into one `layouts` and+// `filters` map respectively, since the count is unbounded and the+// /prefs schema doesn't accept dynamic key prefixes.+const PREF_KEYS = [+ 'xerj.theme',+ 'xerj.time',+ 'xerj.timeFrom',+ 'xerj.timeTo',+ 'xerj.cluster',+ 'xerj.refresh',+ 'xerj.mobile',+ 'xerj.edit',+ 'xerj.dashboards',+];++const VIEWS_KEY = 'xerj.views';++// Aggregate per-dashboard keys under prefs.layouts and prefs.filters so+// the user's panel arrangement and saved filters travel with them.+const LAYOUT_PREFIX = 'xerj.layout.';+const FILTERS_PREFIX = 'xerj.filters.';++// ─── Pull (boot) ─────────────────────────────────────────────────────────────++/** Fetch /prefs and /views, seed localStorage. Idempotent. */+export async function pullAll() {+ await Promise.all([pullPrefs(), pullViews()]);+}++async function pullPrefs() {+ let server;+ try { server = await api('GET', '/prefs'); }+ catch (e) { console.warn('[xerj-console-sync] /prefs unreachable:', e.message); return; }+ if (!server || typeof server !== 'object') return;+ // Server doc shape mirrors a flat key/value map. Translate `theme`,+ // `time`, `cluster`… back into `xerj.theme`, `xerj.time`,+ // `xerj.cluster`… so the existing SPA reads pick them up.+ for (const fullKey of PREF_KEYS) {+ const short = fullKey.replace(/^xerj\./, '');+ if (server[short] !== undefined && server[short] !== null) {+ const val = typeof server[short] === 'string'+ ? server[short]+ : JSON.stringify(server[short]);+ // String-coerce numbers/bools to match the SPA's expectations+ // (most reads use raw `localStorage.getItem` which returns a string).+ try { localStorage.setItem(fullKey, val); } catch {}+ }+ }+ // Per-dashboard layouts: { dashId: '<JSON>' } → xerj.layout.<dashId>+ if (server.layouts && typeof server.layouts === 'object') {+ for (const [id, raw] of Object.entries(server.layouts)) {+ if (raw == null) continue;+ const v = typeof raw === 'string' ? raw : JSON.stringify(raw);+ try { localStorage.setItem(LAYOUT_PREFIX + id, v); } catch {}+ }+ }+ // Per-dashboard filters: same shape under prefs.filters.+ if (server.filters && typeof server.filters === 'object') {+ for (const [id, raw] of Object.entries(server.filters)) {+ if (raw == null) continue;+ const v = typeof raw === 'string' ? raw : JSON.stringify(raw);+ try { localStorage.setItem(FILTERS_PREFIX + id, v); } catch {}+ }+ }+}++async function pullViews() {+ let server;+ try { server = await api('GET', '/views'); }+ catch (e) { console.warn('[xerj-console-sync] /views unreachable:', e.message); return; }+ if (!server || !Array.isArray(server.views)) return;+ // app.js stores views as a flat array under `xerj.views`. Map the+ // server shape (which has `dashboard_id`, `time`, `filters`,+ // `updated_at`) into whatever the SPA expects — the SPA accepts any+ // serialisable view object so a thin pass-through works.+ try {+ localStorage.setItem(VIEWS_KEY, JSON.stringify(server.views));+ } catch {}+}++// ─── Push (debounced) ────────────────────────────────────────────────────────++let lastPushedPrefs = null;+let lastPushedViewsKey = '';+let pushTimer = null;++/** Start the periodic push tick. Idempotent. */+export function startPush() {+ if (pushTimer) return;+ // Initial state — taken AFTER pullAll so we don't immediately push+ // back what we just pulled.+ lastPushedPrefs = snapshotPrefs();+ lastPushedViewsKey = readViewsRaw();+ pushTimer = setInterval(() => { pushIfDirty().catch(() => {}); }, 1500);+}++function snapshotPrefs() {+ const out = {};+ for (const fullKey of PREF_KEYS) {+ const short = fullKey.replace(/^xerj\./, '');+ const v = localStorage.getItem(fullKey);+ if (v !== null) out[short] = v;+ }+ // Aggregate per-dashboard layouts + filters.+ const layouts = {};+ const filters = {};+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const k = localStorage.key(i);+ if (!k) continue;+ if (k.startsWith(LAYOUT_PREFIX)) {+ layouts[k.slice(LAYOUT_PREFIX.length)] = localStorage.getItem(k);+ } else if (k.startsWith(FILTERS_PREFIX)) {+ filters[k.slice(FILTERS_PREFIX.length)] = localStorage.getItem(k);+ }+ }+ } catch {}+ if (Object.keys(layouts).length) out.layouts = layouts;+ if (Object.keys(filters).length) out.filters = filters;+ return JSON.stringify(out);+}++function readViewsRaw() {+ return localStorage.getItem(VIEWS_KEY) || '';+}++async function pushIfDirty() {+ // Prefs+ const cur = snapshotPrefs();+ if (cur !== lastPushedPrefs) {+ try {+ await api('PUT', '/prefs', JSON.parse(cur));+ lastPushedPrefs = cur;+ } catch (e) {+ // Silently retry on the next tick; don't spam the console.+ }+ }+ // Views — naïve full-array sync. Cheap because the array is small+ // (low tens) and the SPA writes it as one JSON blob anyway. We+ // diff against the local raw to skip no-op pushes.+ const v = readViewsRaw();+ if (v !== lastPushedViewsKey) {+ lastPushedViewsKey = v;+ try {+ const arr = v ? JSON.parse(v) : [];+ // The /views surface is collection-style: figure out which views+ // are new vs deleted vs unchanged, then POST/DELETE accordingly.+ // For v1.0 we keep it dirt simple: re-create everything from+ // scratch. Acceptable because views are <10 per user; if this+ // ever bites, replace with a proper diff.+ const server = await api('GET', '/views').catch(() => ({ views: [] }));+ const serverIds = new Set((server.views || []).map(s => s.id));+ const localIds = new Set(arr.map(it => it.id).filter(Boolean));+ // Delete server-side views that no longer exist locally.+ for (const id of serverIds) {+ if (!localIds.has(id)) await api('DELETE', `/views/${encodeURIComponent(id)}`).catch(() => {});+ }+ // POST new ones.+ for (const item of arr) {+ if (item.id && serverIds.has(item.id)) continue;+ await api('POST', '/views', {+ dashboard_id: item.dashboard_id || item.dashboardId || 'default',+ name: item.name || 'Untitled',+ time: item.time || null,+ filters: item.filters || null,+ }).catch(() => {});+ }+ } catch {}+ }+}++// ─── Public bootstrapper ─────────────────────────────────────────────────────++/** One-shot: pull then start periodic push. Call once at SPA load. */+export async function init() {+ await pullAll();+ startPush();+}