Skip to content

armgit / xerj

Public Imported from GitHub
0

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

console: one knowledge surface — size, structure, relations, capabilities after indexing

xerj-org7702d433f4b8
diff --git a/engine/crates/xerj-console-api/src/data_sources.rs b/engine/crates/xerj-console-api/src/data_sources.rs
index 94269b443..b51b424e7 100644
--- a/engine/crates/xerj-console-api/src/data_sources.rs
+++ b/engine/crates/xerj-console-api/src/data_sources.rs
@@ -43,7 +43,7 @@ use crate::time::now_iso;
/// scope (absent guard = engine-internal work, allow). This proxy is
/// therefore its own boundary and must refuse the namespace itself — with
/// the same NotFound as a system index, so existence doesn't leak.
-fn is_hidden_index(name: &str) -> bool {
+pub(crate) fn is_hidden_index(name: &str) -> bool {
indices::is_system_index(name) || xerj_common::types::is_reserved_index(name)
}
@@ -153,6 +153,10 @@ pub async fn list_indices(
"docs": stats.doc_count,
"segments": stats.segment_count,
"fields": stats.field_count,
+ // On-disk store bytes, measured from the index's data dir —
+ // the same number /_cat/indices reports (es_compat's
+ // dir_size_bytes, mirrored in knowledge.rs for this crate).
+ "bytes": crate::knowledge::dir_size_bytes(idx.data_dir()),
"shards": 1,
"replicas": 0,
}));
diff --git a/engine/crates/xerj-console-api/src/graph.rs b/engine/crates/xerj-console-api/src/graph.rs
index 7cee0261d..3ef13eda7 100644
--- a/engine/crates/xerj-console-api/src/graph.rs
+++ b/engine/crates/xerj-console-api/src/graph.rs
@@ -93,7 +93,7 @@ use xerj_engine::Engine;
const GRAPH_CONTRACT: &str = "xerj-second-brain/1";
/// Reserved `_id` of the per-brain meta document (SECOND_BRAIN_SPEC §2.5).
-const BRAIN_META_ID: &str = "__xerj-brain-meta";
+pub(crate) const BRAIN_META_ID: &str = "__xerj-brain-meta";
/// Max returned edges for `ego` (same clamp as the data plane).
const MAX_EGO_LIMIT: usize = 1000;
@@ -113,7 +113,7 @@ const BRAINS_LISTED_CAP: usize = 256;
/// Edges index name for a brain (SECOND_BRAIN_SPEC §1) — same construction as
/// `xerj_api::authz::brain_edges_index`, which names the resource a
/// data-plane grant must hold.
-fn edges_index(brain: &str) -> String {
+pub(crate) fn edges_index(brain: &str) -> String {
format!("{RESERVED_INDEX_PREFIX}{brain}-edges")
}
@@ -129,7 +129,7 @@ fn default_nodes_index(brain: &str) -> String {
/// matching the existing deliberate duplication (`memory_api`,
/// `xerj_autoindex::detect`) — the console crate does not depend on
/// `xerj-api`, on purpose (see `lib.rs`).
-fn validate_brain(brain: &str) -> Result<(), String> {
+pub(crate) fn validate_brain(brain: &str) -> Result<(), String> {
if brain.is_empty() {
return Err("brain name must not be empty".into());
}
@@ -248,7 +248,7 @@ fn nodes_index_names(nodes_index: &str) -> impl Iterator<Item = &str> {
/// Resolve the nodes index for a brain: the meta doc's `nodes_index`, else
/// the `.xerj-memory-{brain}` default. Mirrors `graph_api::resolve_nodes_index`
/// (explicit-param override excluded — see module docs).
-async fn resolve_nodes_index(engine: &Engine, brain: &str, edges: &str) -> String {
+pub(crate) async fn resolve_nodes_index(engine: &Engine, brain: &str, edges: &str) -> String {
if let Some(src) = get_doc_source(engine, edges, BRAIN_META_ID)
.await
.ok()
diff --git a/engine/crates/xerj-console-api/src/knowledge.rs b/engine/crates/xerj-console-api/src/knowledge.rs
new file mode 100644
index 000000000..6e7ecb8fe
--- /dev/null
+++ b/engine/crates/xerj-console-api/src/knowledge.rs
@@ -0,0 +1,539 @@
+//! The knowledge surface — one payload that answers the three questions a
+//! person has the moment `xerj brain` / `xerj autoindex` finishes:
+//!
+//! ```text
+//! GET /_xerj-console/api/v1/knowledge
+//! ```
+//!
+//! 1. **How large is the corpus?** — whole-corpus totals (datasets, records,
+//! files, source bytes summed over the catalog's dataset docs) plus the
+//! live per-index doc counts and on-disk store bytes the engine reports.
+//! 2. **Which data is there?** — every catalog dataset with its full field
+//! list (type, semantic flag, null%, cardinality, example values), the
+//! formats and time span autoindex measured, the other user indices the
+//! catalog does not describe, and the cross-dataset relations autoindex
+//! actually inferred (key overlaps and time alignments — nothing is
+//! invented: a corpus with no correlations gets an empty list, not a
+//! guess).
+//! 3. **What can I do with this now?** — a capability strip computed from
+//! real facts on the node (catalog present, brains present), each entry
+//! carrying the real console route, CLI command, or HTTP endpoint it
+//! names. No capability is listed that this tree does not ship.
+//!
+//! This is the server side of the Console's Corpus home (the landing view).
+//! It exists as ONE endpoint rather than a client-side fan-out because the
+//! answer must be assertable: `tests/knowledge_surface.rs` pins that the
+//! payload carries the catalog's own numbers (doc counts, field specs,
+//! coverage), so the page cannot drift from what `xerj autoindex map`
+//! prints for agents.
+//!
+//! ## Sources, all in-process
+//!
+//! - the `autoindex-catalog` index (`doc_kind: dataset` / `correlation`
+//! docs), read through the engine's own index APIs — the same choice
+//! `xerj-api::ask_api` documents ("no `xerj-autoindex` crate dependency"),
+//! so the constant below *mirrors* `xerj_autoindex::catalog::CATALOG_INDEX`
+//! rather than importing it. Keep them in sync.
+//! - `Index::stats()` for live doc counts and `dir_size_bytes`-equivalent
+//! walks of each index's `data_dir()` for on-disk store bytes (the same
+//! computation `/_cat/indices` and `/_disk_usage` perform).
+//! - the reserved `.xerj-memory-*-edges` brains, listed under the same
+//! operator-tier role gate as [`crate::graph::brains`] (a session that
+//! may not read brains gets an empty list, never a leak).
+//!
+//! Honesty stance: a missing catalog is the ordinary empty state (`catalog:
+//! false`, empty datasets), not an error; every count is either the
+//! catalog's own recorded number or the engine's live one, labelled by
+//! which; nothing on this surface is sample or illustrative data.
+
+use axum::{
+ extract::State,
+ response::Response,
+};
+use serde_json::{json, Map, Value};
+
+use crate::auth::sessions::AuthSession;
+use crate::error::{ConsoleApiError, ConsoleResult};
+use crate::graph;
+use crate::response::ok;
+use crate::state::ConsoleState;
+use xerj_common::types::RESERVED_INDEX_PREFIX;
+use xerj_engine::Engine;
+
+/// Mirror of `xerj_autoindex::catalog::CATALOG_INDEX` (see module docs for
+/// why this crate does not depend on `xerj-autoindex`).
+const CATALOG_INDEX: &str = "autoindex-catalog";
+
+/// Max dataset docs read from the catalog (one per dataset; the corpus
+/// prefix keeps ids distinct, real nodes hold a handful).
+const MAX_DATASETS: usize = 200;
+
+/// Max correlation docs read from the catalog.
+const MAX_RELATIONS: usize = 200;
+
+/// Example values kept per field (the catalog itself stores up to a handful;
+/// three is what a card usefully shows).
+const MAX_EXAMPLES: usize = 3;
+
+/// Characters kept from one example value — the same bound the terminal map
+/// applies (`catalog.rs#render_map` takes 40; the card also shows a type and
+/// coverage, so it gets a little less).
+const MAX_EXAMPLE_CHARS: usize = 40;
+
+/// One ES-shaped `_search` against one index, in-process (the `graph` and
+/// `data_sources` pattern). `Ok(None)` = the index does not exist.
+async fn search_docs(
+ engine: &Engine,
+ index: &str,
+ body: &Value,
+) -> ConsoleResult<Option<Vec<Value>>> {
+ let idx = match engine.get_index(index) {
+ Ok(i) => i,
+ Err(_) => return Ok(None),
+ };
+ let req = xerj_query::parser::parse_request(body)
+ .map_err(|e| ConsoleApiError::Internal(e.to_string()))?;
+ let r = idx
+ .search(&req)
+ .await
+ .map_err(|e| ConsoleApiError::Internal(e.to_string()))?;
+ Ok(Some(r.hits.into_iter().map(|h| h.source).collect()))
+}
+
+/// Strip control characters (raw document values can carry NULs; they would
+/// make the JSON payload read as binary). Same rule as the map renderer's
+/// `clean`.
+fn clean(s: &str) -> String {
+ s.chars()
+ .map(|c| {
+ if c.is_control() && c != '\n' && c != '\t' {
+ '\u{FFFD}'
+ } else {
+ c
+ }
+ })
+ .collect()
+}
+
+fn u64_of(v: Option<&Value>) -> u64 {
+ v.and_then(Value::as_u64).unwrap_or(0)
+}
+
+fn f64_of(v: Option<&Value>) -> f64 {
+ v.and_then(Value::as_f64).unwrap_or(0.0)
+}
+
+fn str_of(v: Option<&Value>) -> Option<String> {
+ v.and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+}
+
+fn strings_of(v: Option<&Value>) -> Vec<String> {
+ match v {
+ Some(Value::Array(a)) => a
+ .iter()
+ .filter_map(Value::as_str)
+ .map(clean)
+ .filter(|s| !s.is_empty())
+ .collect(),
+ Some(Value::String(s)) => vec![clean(s)],
+ _ => Vec::new(),
+ }
+}
+
+/// `fields_json` on a dataset doc is a JSON *string* holding the array of
+/// `xerj_autoindex::infer::FieldSpec` values (the frozen catalog mapping
+/// declares it `text`). Parse it and project each spec down to what a card
+/// renders: name, type, semantic flag, cardinality, null% and examples.
+/// Unknown/missing keys degrade to honest defaults — a spec without a
+/// `null_ratio` reads as "not measured" (`null`), never as 0%.
+fn parse_fields(fields_json: Option<&Value>) -> Vec<Value> {
+ let raw = match fields_json.and_then(Value::as_str) {
+ Some(s) => s,
+ None => return Vec::new(),
+ };
+ let specs = match serde_json::from_str::<Value>(raw) {
+ Ok(Value::Array(a)) => a,
+ _ => return Vec::new(),
+ };
+ let mut out = Vec::with_capacity(specs.len());
+ for spec in specs {
+ let obj = match spec.as_object() {
+ Some(o) => o,
+ None => continue,
+ };
+ let get = |k: &str| obj.get(k);
+ let Some(name) = str_of(get("name")) else {
+ continue;
+ };
+ let es_type = str_of(get("es_type")).unwrap_or_else(|| "object".into());
+ let date_enc = str_of(get("date_enc"));
+ let ty = match date_enc {
+ Some(enc) => format!("{es_type} ({enc})"),
+ None => es_type,
+ };
+ // FieldSpec.semantic is Option<String> (the embedder's label) — the
+ // card only needs "is this the semantic body field".
+ let semantic = get("semantic").and_then(Value::as_str).is_some();
+ let card = get("cardinality_est").and_then(Value::as_u64);
+ let overflow = get("cardinality_overflow").and_then(Value::as_bool).unwrap_or(false);
+ let examples = strings_of(get("examples"));
+ out.push(json!({
+ "name": name,
+ "type": ty,
+ "semantic": semantic,
+ // null when the spec carried no estimate — rendered as "—" not 0.
+ "cardinality": card,
+ "cardinality_overflow": overflow,
+ "null_ratio": get("null_ratio").and_then(Value::as_f64),
+ "coverage": get("coverage").and_then(Value::as_f64),
+ "examples": examples
+ .iter()
+ .take(MAX_EXAMPLES)
+ .map(|e| e.chars().take(MAX_EXAMPLE_CHARS).collect::<String>())
+ .collect::<Vec<_>>(),
+ }));
+ }
+ out
+}
+
+/// `sample_queries_json` is an array of JSON strings (each a ready-to-send
+/// query body). Parse each; unparseable entries are skipped, not guessed.
+fn parse_sample_queries(v: Option<&Value>) -> Vec<Value> {
+ let arr = match v.and_then(Value::as_array) {
+ Some(a) => a,
+ None => return Vec::new(),
+ };
+ arr.iter()
+ .filter_map(|q| {
+ let s = q.as_str()?;
+ serde_json::from_str::<Value>(s).ok()
+ })
+ .take(12)
+ .collect()
+}
+
+/// A dataset doc → the card payload. `live` carries the engine's current
+/// numbers for the index when it exists (None = the catalog describes an
+/// index this engine no longer holds — shown, labelled).
+fn dataset_card(doc: &Value, live: Option<(u64, u64)>) -> Value {
+ let g = |k: &str| doc.get(k);
+ json!({
+ "index": str_of(g("index_name")).unwrap_or_default(),
+ "slug": str_of(g("slug")),
+ "formats": strings_of(g("formats")),
+ "records": u64_of(g("record_count")),
+ "junk": u64_of(g("junk_records")),
+ "files": u64_of(g("file_count")),
+ "bytes": u64_of(g("bytes")),
+ "live_docs": live.map(|(docs, _)| docs),
+ "store_bytes": live.map(|(_, bytes)| bytes),
+ "time_field": str_of(g("time_field")),
+ "time_min": str_of(g("time_min")),
+ "time_max": str_of(g("time_max")),
+ "semantic_field": str_of(g("semantic_field")),
+ "fields": parse_fields(g("fields_json")),
+ "sample_queries": parse_sample_queries(g("sample_queries_json")),
+ "notes": strings_of(g("notes")),
+ "run_id": str_of(g("run_id")),
+ })
+}
+
+/// A correlation doc → one relation row. Only the two `corr_kind`s autoindex
+/// writes are understood; anything else is dropped (never reinterpreted).
+fn relation_row(doc: &Value) -> Option<Value> {
+ let g = |k: &str| doc.get(k);
+ let base = json!({
+ "a_dataset": str_of(g("a_dataset")),
+ "a_index": str_of(g("a_index")).unwrap_or_default(),
+ "a_field": str_of(g("a_field")).unwrap_or_default(),
+ "b_dataset": str_of(g("b_dataset")),
+ "b_index": str_of(g("b_index")).unwrap_or_default(),
+ "b_field": str_of(g("b_field")).unwrap_or_default(),
+ });
+ let mut obj = base.as_object()?.clone();
+ match g("corr_kind").and_then(Value::as_str) {
+ Some("key_overlap") => {
+ obj.insert("kind".into(), json!("key_overlap"));
+ obj.insert("grade".into(), json!(str_of(g("grade")).unwrap_or_default()));
+ obj.insert("overlap".into(), json!(u64_of(g("overlap"))));
+ obj.insert("containment".into(), json!(f64_of(g("containment"))));
+ obj.insert(
+ "confirmed_values".into(),
+ json!(g("confirmed_values").and_then(Value::as_u64)),
+ );
+ obj.insert(
+ "tested_values".into(),
+ json!(g("tested_values").and_then(Value::as_u64)),
+ );
+ obj.insert("examples".into(), json!(strings_of(g("examples"))));
+ }
+ Some("time_alignment") => {
+ obj.insert("kind".into(), json!("time_alignment"));
+ obj.insert("range_overlap".into(), json!(f64_of(g("range_overlap"))));
+ obj.insert("shared_buckets".into(), json!(u64_of(g("shared_buckets"))));
+ obj.insert("pearson_r".into(), json!(g("pearson_r").and_then(Value::as_f64)));
+ obj.insert(
+ "activity_correlated".into(),
+ json!(g("activity_correlated").and_then(Value::as_bool).unwrap_or(false)),
+ );
+ }
+ _ => return None,
+ }
+ Some(Value::Object(obj))
+}
+
+/// Recursive byte sum of a directory — the same computation `/_cat/indices`
+/// and `/_disk_usage` perform for `store.size` (`es_compat::dir_size_bytes`,
+/// mirrored here because it is private to `xerj-api`). Shared with the
+/// data-sources facade so both surfaces report the same number.
+pub(crate) fn dir_size_bytes(path: &std::path::Path) -> u64 {
+ let mut total = 0u64;
+ let Ok(read) = std::fs::read_dir(path) else {
+ return 0;
+ };
+ for entry in read.flatten() {
+ let Ok(meta) = std::fs::metadata(entry.path()) else {
+ continue;
+ };
+ if meta.is_dir() {
+ total += dir_size_bytes(&entry.path());
+ } else {
+ total += meta.len();
+ }
+ }
+ total
+}
+
+/// Live `(doc_count, store_bytes)` for one index, when the engine holds it.
+async fn live_stats(engine: &Engine, name: &str) -> Option<(u64, u64)> {
+ let idx = engine.get_index(name).ok()?;
+ let stats = idx.stats().await;
+ Some((stats.doc_count, dir_size_bytes(idx.data_dir())))
+}
+
+/// The brains this node holds, under the same operator-tier gate as
+/// `graph::brains` (see that module for the rule). Each row carries the
+/// brain's link count — real edge docs only: the §2.5 meta doc
+/// (`__xerj-brain-meta`) lives in the same index and is excluded, so the
+/// number is what a person would count, not the index's raw doc count.
+async fn brains_listing(engine: &Engine, may_read: bool) -> ConsoleResult<Vec<Value>> {
+ if !may_read {
+ return Ok(Vec::new());
+ }
+ let mut names: Vec<String> = engine
+ .index_name_list()
+ .into_iter()
+ .filter(|n| {
+ n.starts_with(RESERVED_INDEX_PREFIX)
+ && n.ends_with("-edges")
+ && n.len() > RESERVED_INDEX_PREFIX.len() + "-edges".len()
+ })
+ .map(|n| n[RESERVED_INDEX_PREFIX.len()..n.len() - "-edges".len()].to_string())
+ .filter(|b| graph::validate_brain(b).is_ok())
+ .collect();
+ names.sort();
+ let mut out = Vec::with_capacity(names.len());
+ for brain in names {
+ let edges = graph::edges_index(&brain);
+ // Count edge documents, excluding the meta doc. `search_docs`
+ // returns sources; a count query would be size-0, so count real
+ // hits (an edge index holds one doc per link — bounded by the
+ // graph contract, not by corpus size).
+ let edge_docs = search_docs(
+ engine,
+ &edges,
+ &json!({
+ "query": { "bool": { "must_not": [{ "ids": { "values": [graph::BRAIN_META_ID] } }] } },
+ "size": 10_000,
+ "track_total_hits": true,
+ }),
+ )
+ .await?;
+ let links = edge_docs.map(|d| d.len() as u64).unwrap_or(0);
+ let nodes_index = graph::resolve_nodes_index(engine, &brain, &edges).await;
+ out.push(json!({
+ "name": brain,
+ "nodes_index": nodes_index,
+ "links": links,
+ }));
+ }
+ Ok(out)
+}
+
+/// The capability strip. Every entry names a shipped surface — console route
+/// (`href`), CLI command (`command`), or HTTP endpoint (`endpoint`) — and
+/// availability is computed from facts on the node, not from a feature list.
+fn capabilities(catalog: bool, brains: &[Value]) -> Vec<Value> {
+ let mut caps = vec![
+ json!({
+ "id": "search",
+ "title": "Search it",
+ "blurb": "Seven query types — match, phrase, prefix, term, range, semantic, hybrid lexical+vector — with facets and a request preview.",
+ "href": "#/discover",
+ "kind": "console",
+ }),
+ json!({
+ "id": "read",
+ "title": "Read the documents",
+ "blurb": "Page through records with highlights and the per-record link list.",
+ "href": "#/reader",
+ "kind": "console",
+ }),
+ ];
+ if let Some(brain) = brains.first() {
+ let name = brain.get("name").and_then(Value::as_str).unwrap_or_default();
+ let links = brain.get("links").and_then(Value::as_u64).unwrap_or(0);
+ caps.push(json!({
+ "id": "graph",
+ "title": "See the links between documents",
+ "blurb": format!("Brain '{name}' holds {links} links over this corpus — the map, the evidence ledger, belief-time replay."),
+ "href": format!("#/dashboards/second-brain?brain={name}"),
+ "kind": "console",
+ }));
+ }
+ if catalog {
+ caps.push(json!({
+ "id": "ask",
+ "title": "Ask for a query, not a manual",
+ "blurb": "POST /_ask — prompt in, validated query DSL out (it routes by this catalog; unresolved phrases are refused by name).",
+ "endpoint": "POST /_ask",
+ "kind": "http",
+ }));
+ caps.push(json!({
+ "id": "map",
+ "title": "Print the data map",
+ "blurb": "The same field/coverage table this page shows, as markdown — for you or for an agent (MCP: xerj_map; `xerj mcp` exposes 13 tools).",
+ "command": "xerj autoindex map",
+ "kind": "cli",
+ }));
+ }
+ caps.push(json!({
+ "id": "decide",
+ "title": "Decide with it",
+ "blurb": "POST /_decide — the System One decide ladder (history vote by default; the local zero-shot head when the node arms it).",
+ "endpoint": "POST /_decide",
+ "kind": "http",
+ }));
+ caps.push(json!({
+ "id": "watch",
+ "title": "Keep it current",
+ "blurb": "Stay resident and reindex what changes — this page follows on reload.",
+ "command": "xerj autoindex <folder> --watch",
+ "kind": "cli",
+ }));
+ caps.push(json!({
+ "id": "share",
+ "title": "Share one index",
+ "blurb": "Read-only search over one index: a link, a passcode, an expiry.",
+ "command": "xerj share <index>",
+ "kind": "cli",
+ }));
+ caps
+}
+
+/// `GET /_xerj-console/api/v1/knowledge` — see the module docs.
+pub async fn knowledge(
+ State(state): State<ConsoleState>,
+ sess: AuthSession,
+) -> ConsoleResult<Response> {
+ // 1. The catalog: dataset docs + correlation docs. A missing catalog
+ // index is the ordinary empty state, not an error.
+ let dataset_docs = search_docs(
+ &state.engine,
+ CATALOG_INDEX,
+ &json!({ "query": { "term": { "doc_kind": "dataset" } }, "size": MAX_DATASETS }),
+ )
+ .await?
+ .unwrap_or_default();
+ let corr_docs = search_docs(
+ &state.engine,
+ CATALOG_INDEX,
+ &json!({ "query": { "term": { "doc_kind": "correlation" } }, "size": MAX_RELATIONS }),
+ )
+ .await?
+ .unwrap_or_default();
+ let catalog = !dataset_docs.is_empty();
+
+ // 2. Dataset cards, largest first (the terminal map's order), each with
+ // the engine's live numbers for its index.
+ let mut datasets: Vec<Value> = Vec::with_capacity(dataset_docs.len());
+ for doc in &dataset_docs {
+ if doc.get("doc_kind").and_then(Value::as_str) != Some("dataset") {
+ continue;
+ }
+ let index = str_of(doc.get("index_name")).unwrap_or_default();
+ let live = if index.is_empty() {
+ None
+ } else {
+ live_stats(&state.engine, &index).await
+ };
+ datasets.push(dataset_card(doc, live));
+ }
+ datasets.sort_by(|a, b| {
+ let rec = b["records"].as_u64().cmp(&a["records"].as_u64());
+ rec.then_with(|| a["index"].as_str().cmp(&b["index"].as_str()))
+ });
+
+ // 3. Other user indices the catalog does not describe (an engine filled
+ // some other way must not read as "nothing indexed"). Same hidden-set
+ // rule as the data-sources facade.
+ let catalog_indices: Vec<String> = datasets
+ .iter()
+ .filter_map(|d| d["index"].as_str().map(str::to_string))
+ .collect();
+ let mut others: Vec<Value> = Vec::new();
+ let mut live_docs_total: u64 = 0;
+ for name in state.engine.index_name_list() {
+ if crate::data_sources::is_hidden_index(&name) || name == CATALOG_INDEX {
+ continue;
+ }
+ let Some((docs, bytes)) = live_stats(&state.engine, &name).await else {
+ continue;
+ };
+ live_docs_total += docs;
+ if catalog_indices.contains(&name) {
+ continue;
+ }
+ others.push(json!({ "index": name, "docs": docs, "store_bytes": bytes }));
+ }
+ others.sort_by(|a, b| a["index"].as_str().cmp(&b["index"].as_str()));
+
+ // 4. Whole-corpus totals. `records`/`files`/`bytes` are the catalog's
+ // own last-run numbers (one run rewrites its dataset doc); `docs` is
+ // the engine's live count across every user index.
+ let sum = |k: &str| datasets.iter().map(|d| d[k].as_u64().unwrap_or(0)).sum::<u64>();
+ let totals = json!({
+ "datasets": datasets.len(),
+ "records": sum("records"),
+ "files": sum("files"),
+ "bytes": sum("bytes"),
+ "docs": live_docs_total,
+ "relations": corr_docs.len(),
+ });
+
+ // 5. Relations — only what autoindex actually inferred.
+ let mut relations: Vec<Value> = corr_docs.iter().filter_map(relation_row).collect();
+ relations.sort_by(|a, b| {
+ let rank = |v: &Value| match v["kind"].as_str() {
+ Some("key_overlap") => v["overlap"].as_u64().unwrap_or(0),
+ _ => 0,
+ };
+ rank(b).cmp(&rank(a))
+ });
+
+ // 6. Brains (operator tier) + the capability strip.
+ let brains = brains_listing(&state.engine, graph::may_read_brains(&sess.user)).await?;
+ let caps = capabilities(catalog, &brains);
+
+ let mut payload = Map::new();
+ payload.insert("catalog".into(), json!(catalog));
+ payload.insert("totals".into(), totals);
+ payload.insert("datasets".into(), Value::Array(datasets));
+ payload.insert("others".into(), Value::Array(others));
+ payload.insert("relations".into(), Value::Array(relations));
+ payload.insert("brains".into(), Value::Array(brains));
+ payload.insert("capabilities".into(), Value::Array(caps));
+ Ok(ok(Value::Object(payload), None))
+}
diff --git a/engine/crates/xerj-console-api/src/lib.rs b/engine/crates/xerj-console-api/src/lib.rs
index 2aebbc3cc..5a6168be0 100644
--- a/engine/crates/xerj-console-api/src/lib.rs
+++ b/engine/crates/xerj-console-api/src/lib.rs
@@ -54,6 +54,7 @@ pub mod data_sources;
pub mod error;
pub mod graph;
pub mod indices;
+pub mod knowledge;
pub mod prefs;
pub mod response;
pub mod router;
diff --git a/engine/crates/xerj-console-api/src/router.rs b/engine/crates/xerj-console-api/src/router.rs
index ccb2e5c68..dfc6a9bac 100644
--- a/engine/crates/xerj-console-api/src/router.rs
+++ b/engine/crates/xerj-console-api/src/router.rs
@@ -31,7 +31,7 @@ use axum::{
};
use crate::{
- auth, cluster, dashboards, data_sources, graph, prefs, spa, state::ConsoleState, views,
+ auth, cluster, dashboards, data_sources, graph, knowledge, prefs, spa, state::ConsoleState, views,
};
/// Build the full Xerj Console router. Mount at the root of an axum Router
@@ -146,6 +146,11 @@ pub fn xerj_console_router(state: ConsoleState) -> Router {
"/_xerj-console/api/v1/data-sources/connections/:id/indices/:name/search",
post(data_sources::search),
)
+ // ── API: the knowledge surface (session-authorized) ─
+ // One read that answers what a person asks the moment indexing
+ // finishes: how large, which data, what can I do now. See
+ // src/knowledge.rs.
+ .route("/_xerj-console/api/v1/knowledge", get(knowledge::knowledge))
// ── API: Second-Brain graph reads (session-authorized, issue #936) ─
// The data plane's /_graph/* routes stay credential-only; these are
// the console's own role-gated read paths over the same engine
@@ -198,6 +203,7 @@ pub fn known_routes() -> &'static [&'static str] {
"/_xerj-console/api/v1/data-sources/connections/:id/indices",
"/_xerj-console/api/v1/data-sources/connections/:id/indices/:name/fields",
"/_xerj-console/api/v1/data-sources/connections/:id/indices/:name/search",
+ "/_xerj-console/api/v1/knowledge",
"/_xerj-console/api/v1/graph/brains",
"/_xerj-console/api/v1/graph/:brain/ego",
"/_xerj-console/api/v1/graph/:brain/overview",
diff --git a/engine/crates/xerj-console-api/tests/knowledge_surface.rs b/engine/crates/xerj-console-api/tests/knowledge_surface.rs
new file mode 100644
index 000000000..e847a1bc8
--- /dev/null
+++ b/engine/crates/xerj-console-api/tests/knowledge_surface.rs
@@ -0,0 +1,508 @@
+//! The knowledge surface (`GET /_xerj-console/api/v1/knowledge`) serves the
+//! catalog's own facts (issue: "one knowledge surface after indexing").
+//!
+//! What a person must see the moment `xerj brain` finishes — how large the
+//! corpus is, which data is in it, what they can do with it — is computed
+//! server-side from the autoindex catalog and the live engine. These tests
+//! pin the PAYLOAD (never the styling):
+//!
+//! - catalog facts survive the round trip: record/file/byte counts, the
+//! full field list with types + null ratios + example values, the
+//! semantic field flag, the sample queries;
+//! - the engine's LIVE numbers are joined on: doc counts come from
+//! `Index::stats`, store bytes from the index's data dir (nonzero after a
+//! real write), an index the catalog does not describe still shows up
+//! under `others` (an engine filled another way must not read as empty);
+//! - relations are exactly what autoindex inferred — key overlaps with
+//! their overlap/grade, time alignments with their Pearson r — and a
+//! catalog with none yields `relations: []`, not a guess;
+//! - the capability strip is grounded: `map`/`ask` appear only when a
+//! catalog exists, the graph entry only for a role that may read brains
+//! AND only when a brain exists, and every entry names a real console
+//! route, CLI command, or endpoint;
+//! - a node with nothing indexed is the ordinary empty state (`catalog:
+//! false`), not an error;
+//! - the endpoint is session-authorized: no cookie is a 401.
+
+use axum::{body::Body, http::Request, Router};
+use http_body_util::BodyExt;
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use tower::ServiceExt;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_console_api::{
+ auth::{sessions, store},
+ state::ClusterMode,
+ xerj_console_router, ConsoleState,
+};
+use xerj_engine::Engine;
+
+const KNOWLEDGE_PATH: &str = "/_xerj-console/api/v1/knowledge";
+
+struct TestApp {
+ router: Router,
+ owner_cookie: String,
+ viewer_cookie: String,
+ _dir: TempDir,
+}
+
+async fn add_session_user(state: &ConsoleState, engine: &Engine, id: &str, role: &str) -> String {
+ let user = store::User {
+ id: id.to_string(),
+ email: format!("{id}@example.com"),
+ display_name: id.to_string(),
+ role: role.to_string(),
+ status: store::UserStatus::Active,
+ created_at: xerj_console_api::time::now_iso(),
+ last_seen_at: Some(xerj_console_api::time::now_iso()),
+ };
+ store::upsert_user(engine, &user).await.unwrap();
+ let (_s, signed) = sessions::mint_session(state, &user.id, "passkey", None, None)
+ .await
+ .unwrap();
+ format!("xerj_session={signed}")
+}
+
+fn schema(pairs: &[(&str, FieldType)]) -> Schema {
+ let mut s = Schema::empty();
+ for (name, t) in pairs {
+ s.add_field(FieldConfig::new(*name, *t)).expect("add field");
+ }
+ s
+}
+
+/// The catalog index's declared subset these tests read (the frozen mapping
+/// in `xerj_autoindex::catalog::catalog_mapping` has ~40 properties; the
+/// console only term-queries `doc_kind` and reads `_source`).
+fn catalog_schema() -> Schema {
+ schema(&[
+ ("doc_kind", FieldType::Keyword),
+ ("index_name", FieldType::Keyword),
+ ("slug", FieldType::Keyword),
+ ("formats", FieldType::Keyword),
+ ("record_count", FieldType::Long),
+ ("junk_records", FieldType::Long),
+ ("bytes", FieldType::Long),
+ ("file_count", FieldType::Long),
+ ("time_field", FieldType::Keyword),
+ ("time_min", FieldType::Date),
+ ("time_max", FieldType::Date),
+ ("semantic_field", FieldType::Keyword),
+ ("fields_json", FieldType::Text),
+ ("sample_queries_json", FieldType::Text),
+ ("run_id", FieldType::Keyword),
+ ("corr_kind", FieldType::Keyword),
+ ("a_dataset", FieldType::Keyword),
+ ("b_dataset", FieldType::Keyword),
+ ("a_index", FieldType::Keyword),
+ ("b_index", FieldType::Keyword),
+ ("a_field", FieldType::Keyword),
+ ("b_field", FieldType::Keyword),
+ ("grade", FieldType::Keyword),
+ ("overlap", FieldType::Long),
+ ("containment", FieldType::Double),
+ ("examples", FieldType::Keyword),
+ ])
+}
+
+/// The exact `FieldSpec` JSON autoindex serializes into `fields_json` (see
+/// `infer::FieldSpec` — `semantic` is the embedder's label and is skipped
+/// when absent, `null_ratio`/`coverage` are always present).
+fn fields_json() -> String {
+ json!([
+ {
+ "name": "email_from",
+ "es_type": "keyword",
+ "cardinality_est": 12,
+ "cardinality_overflow": false,
+ "null_ratio": 0.0,
+ "avg_len": 0.0,
+ "coverage": 1.0,
+ },
+ {
+ "name": "body",
+ "es_type": "semantic_text",
+ "semantic": "lexical-hash-384",
+ "cardinality_est": 91,
+ "cardinality_overflow": false,
+ "null_ratio": 0.0,
+ "avg_len": 412.5,
+ "coverage": 1.0,
+ "examples": ["term sheet attached"]
+ },
+ {
+ "name": "page",
+ "es_type": "long",
+ "cardinality_est": 4,
+ "cardinality_overflow": false,
+ "null_ratio": 0.75,
+ "avg_len": 0.0,
+ "coverage": 0.25,
+ "examples": ["1", "2"]
+ }
+ ])
+ .to_string()
+}
+
+/// Boot the console over a node `xerj brain` could have left behind:
+/// a catalog describing two datasets (one larger, one smaller), one
+/// key-overlap correlation, a brain over the first dataset, and one user
+/// index the catalog does NOT describe.
+async fn boot() -> TestApp {
+ let dir = TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(cfg).expect("engine");
+ let outcome = xerj_console_api::bootstrap::run(&engine, dir.path(), "http://localhost:9200")
+ .await
+ .unwrap();
+ let state = ConsoleState::new(
+ engine.clone(),
+ "local".into(),
+ outcome.master_key,
+ ClusterMode::Standalone,
+ );
+ let owner_cookie = add_session_user(&state, &engine, "owner-test", "owner").await;
+ let viewer_cookie = add_session_user(&state, &engine, "viewer-test", "viewer").await;
+
+ // The dataset indices the catalog describes — 3 real documents in
+ // ax-mail (the LIVE count the endpoint must join on), 1 in ax-pdfs.
+ engine
+ .create_index("ax-mail", schema(&[("body", FieldType::Text)]))
+ .expect("create ax-mail");
+ engine.get_index("ax-mail").unwrap()
+ .index_documents_batched(vec![
+ (Some("m1".into()), json!({"body": "term sheet attached"})),
+ (Some("m2".into()), json!({"body": "lunch on friday"})),
+ (Some("m3".into()), json!({"body": "re: contract"})),
+ ])
+ .await;
+ engine
+ .create_index("ax-pdfs", schema(&[("text", FieldType::Text)]))
+ .expect("create ax-pdfs");
+ engine.get_index("ax-pdfs").unwrap()
+ .index_documents_batched(vec![(
+ Some("p1".into()),
+ json!({"text": "invoice 2026-09"}),
+ )])
+ .await;
+
+ // An index the catalog does not describe — filled some other way, and
+ // still part of "what is on this node".
+ engine
+ .create_index("weblogs", schema(&[("message", FieldType::Text)]))
+ .expect("create weblogs");
+ engine.get_index("weblogs").unwrap()
+ .index_documents_batched(vec![(
+ Some("w1".into()),
+ json!({"message": "timeout on shard 2"}),
+ )])
+ .await;
+
+ // The catalog: two dataset docs + one key-overlap correlation.
+ engine
+ .create_index("autoindex-catalog", catalog_schema())
+ .expect("create catalog");
+ let catalog = engine.get_index("autoindex-catalog").unwrap();
+ catalog
+ .index_documents_batched(vec![
+ (
+ Some("ds:home:ax-mail".into()),
+ json!({
+ "doc_kind": "dataset",
+ "index_name": "ax-mail",
+ "slug": "mail",
+ "formats": ["eml"],
+ "record_count": 91,
+ "junk_records": 2,
+ "bytes": 482_133,
+ "file_count": 14,
+ "time_field": "email_date",
+ "time_min": "2026-01-05T00:00:00.000Z",
+ "time_max": "2026-09-19T00:00:00.000Z",
+ "semantic_field": "body",
+ "fields_json": fields_json(),
+ "sample_queries_json": [
+ r#"{"query":{"match":{"body":"term sheet"}},"size":3}"#
+ ],
+ "run_id": "run-1",
+ }),
+ ),
+ (
+ Some("ds:home:ax-pdfs".into()),
+ json!({
+ "doc_kind": "dataset",
+ "index_name": "ax-pdfs",
+ "slug": "pdfs",
+ "formats": ["pdf"],
+ "record_count": 14,
+ "junk_records": 0,
+ "bytes": 3_111_999,
+ "file_count": 4,
+ "semantic_field": "text",
+ "fields_json": json!([
+ {"name": "text", "es_type": "semantic_text", "semantic": "lexical-hash-384",
+ "cardinality_est": 14, "cardinality_overflow": false, "null_ratio": 0.0,
+ "avg_len": 1200.0, "coverage": 1.0, "examples": ["invoice 2026-09"]},
+ {"name": "page", "es_type": "long",
+ "cardinality_est": 9, "cardinality_overflow": false, "null_ratio": 0.1,
+ "avg_len": 0.0, "coverage": 0.9, "examples": ["1"]}
+ ]).to_string(),
+ "run_id": "run-1",
+ }),
+ ),
+ (
+ Some("corr:home:mail:pdfs:email_from:title".into()),
+ json!({
+ "doc_kind": "correlation",
+ "corr_kind": "key_overlap",
+ "a_dataset": "mail", "a_index": "ax-mail", "a_field": "email_from",
+ "b_dataset": "pdfs", "b_index": "ax-pdfs", "b_field": "title",
+ "overlap": 7, "containment": 0.58, "grade": "likely",
+ "examples": ["[email protected]"],
+ "confirmed_values": 7, "tested_values": 12,
+ }),
+ ),
+ ])
+ .await;
+
+ // One brain over ax-mail, with a meta doc naming its nodes index and
+ // two edges (the §2.5 shape `graph::brains` reads).
+ engine
+ .create_index(
+ ".xerj-memory-casefile-edges",
+ schema(&[
+ ("edge_id", FieldType::Keyword),
+ ("src", FieldType::Keyword),
+ ("dst", FieldType::Keyword),
+ ("type", FieldType::Keyword),
+ ]),
+ )
+ .expect("create edges index");
+ let edges = engine.get_index(".xerj-memory-casefile-edges").unwrap();
+ edges
+ .index_documents_batched(vec![
+ (
+ Some("__xerj-brain-meta".into()),
+ json!({ "meta_version": 1, "brain": "casefile", "nodes_index": "ax-mail" }),
+ ),
+ (
+ Some("e1".into()),
+ json!({ "edge_id": "e1", "src": "m1", "dst": "m2", "type": "same_dir" }),
+ ),
+ (
+ Some("e2".into()),
+ json!({ "edge_id": "e2", "src": "m1", "dst": "m3", "type": "mdlink" }),
+ ),
+ ])
+ .await;
+
+ let router = xerj_console_router(state);
+ TestApp {
+ router,
+ owner_cookie,
+ viewer_cookie,
+ _dir: dir,
+ }
+}
+
+/// A node with NOTHING indexed — no catalog, no user index.
+async fn boot_empty() -> TestApp {
+ let dir = TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(cfg).expect("engine");
+ let outcome = xerj_console_api::bootstrap::run(&engine, dir.path(), "http://localhost:9200")
+ .await
+ .unwrap();
+ let state = ConsoleState::new(
+ engine.clone(),
+ "local".into(),
+ outcome.master_key,
+ ClusterMode::Standalone,
+ );
+ let owner_cookie = add_session_user(&state, &engine, "owner-test", "owner").await;
+ let viewer_cookie = add_session_user(&state, &engine, "viewer-test", "viewer").await;
+ let router = xerj_console_router(state);
+ TestApp {
+ router,
+ owner_cookie,
+ viewer_cookie,
+ _dir: dir,
+ }
+}
+
+async fn get(app: &TestApp, cookie: Option<&str>) -> (axum::http::StatusCode, Value) {
+ let mut b = Request::builder().method("GET").uri(KNOWLEDGE_PATH);
+ if let Some(c) = cookie {
+ b = b.header("cookie", c);
+ }
+ let resp = app.router.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = resp.into_body().collect().await.unwrap().to_bytes();
+ let v: Value = serde_json::from_slice(&bytes).expect("json body");
+ (status, v)
+}
+
+fn data<'a>(v: &'a Value) -> &'a Value {
+ v.get("data").expect("console envelope {data}")
+}
+
+#[tokio::test]
+async fn no_session_is_a_401() {
+ let app = boot().await;
+ let (status, _) = get(&app, None).await;
+ assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn the_payload_carries_the_catalogs_own_facts() {
+ let app = boot().await;
+ let (status, v) = get(&app, Some(&app.owner_cookie)).await;
+ assert_eq!(status, axum::http::StatusCode::OK);
+ let d = data(&v);
+ // KNOWLEDGE_PRINT=1 cargo test knowledge_surface -- --nocapture
+ // prints the exact payload the handler served (the same fixture the
+ // node-test SPA suite renders) — the run book for PR bodies and for
+ // eyeballing a change, without booting a node and enrolling a passkey.
+ if std::env::var("KNOWLEDGE_PRINT").is_ok() {
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ }
+
+ // Gate 1 — how large. Totals are the catalog's own numbers…
+ let totals = d.get("totals").unwrap();
+ assert_eq!(totals["datasets"].as_u64(), Some(2));
+ assert_eq!(totals["records"].as_u64(), Some(91 + 14));
+ assert_eq!(totals["files"].as_u64(), Some(14 + 4));
+ assert_eq!(totals["bytes"].as_u64(), Some(482_133 + 3_111_999));
+ assert_eq!(totals["relations"].as_u64(), Some(1));
+
+ // …and the LIVE doc counts are joined on (3 real docs, not the catalog's 91).
+ let datasets = d["datasets"].as_array().unwrap();
+ assert_eq!(datasets.len(), 2);
+ assert_eq!(datasets[0]["index"].as_str(), Some("ax-mail"), "largest first");
+ assert_eq!(datasets[0]["live_docs"].as_u64(), Some(3));
+ assert_eq!(datasets[0]["records"].as_u64(), Some(91));
+ assert_eq!(datasets[1]["index"].as_str(), Some("ax-pdfs"));
+ assert_eq!(datasets[1]["live_docs"].as_u64(), Some(1));
+ // Store bytes are measured from the index's own data dir — real writes
+ // happened, so this is nonzero.
+ assert!(datasets[0]["store_bytes"].as_u64().unwrap_or(0) > 0);
+
+ // Gate 2 — which data. The FULL field list with the spec's facts.
+ let fields = datasets[0]["fields"].as_array().unwrap();
+ assert_eq!(fields.len(), 3, "no 8-field cap on the payload");
+ let by_name = |n: &str| {
+ fields
+ .iter()
+ .find(|f| f["name"].as_str() == Some(n))
+ .unwrap_or_else(|| panic!("field {n} missing: {fields:#?}"))
+ };
+ let from = by_name("email_from");
+ assert_eq!(from["type"].as_str(), Some("keyword"));
+ assert_eq!(from["null_ratio"].as_f64(), Some(0.0));
+ assert_eq!(from["cardinality"].as_u64(), Some(12));
+ assert_eq!(
+ from["examples"].as_array().unwrap()[0].as_str(),
+ );
+ let body = by_name("body");
+ assert_eq!(body["semantic"].as_bool(), Some(true), "the semantic_text field is flagged");
+ assert_eq!(body["type"].as_str(), Some("semantic_text"));
+ let page = by_name("page");
+ assert_eq!(page["null_ratio"].as_f64(), Some(0.75));
+ assert_eq!(page["coverage"].as_f64(), Some(0.25));
+ // the semantic field the run elected is surfaced as a dataset fact
+ assert_eq!(datasets[0]["semantic_field"].as_str(), Some("body"));
+ // the catalog's ready-to-send sample query round-trips as JSON
+ let sq = datasets[0]["sample_queries"].as_array().unwrap();
+ assert_eq!(sq[0]["query"]["match"]["body"].as_str(), Some("term sheet"));
+
+ // …and an index the catalog does not describe is still listed.
+ let others = d["others"].as_array().unwrap();
+ assert_eq!(others.len(), 1);
+ assert_eq!(others[0]["index"].as_str(), Some("weblogs"));
+ assert_eq!(others[0]["docs"].as_u64(), Some(1));
+}
+
+#[tokio::test]
+async fn relations_are_exactly_what_autoindex_inferred() {
+ let app = boot().await;
+ let (_, v) = get(&app, Some(&app.owner_cookie)).await;
+ let rels = data(&v)["relations"].as_array().unwrap();
+ assert_eq!(rels.len(), 1);
+ let r = &rels[0];
+ assert_eq!(r["kind"].as_str(), Some("key_overlap"));
+ assert_eq!(r["a_index"].as_str(), Some("ax-mail"));
+ assert_eq!(r["a_field"].as_str(), Some("email_from"));
+ assert_eq!(r["b_index"].as_str(), Some("ax-pdfs"));
+ assert_eq!(r["b_field"].as_str(), Some("title"));
+ assert_eq!(r["overlap"].as_u64(), Some(7));
+ assert_eq!(r["grade"].as_str(), Some("likely"));
+ assert_eq!(r["confirmed_values"].as_u64(), Some(7));
+ assert_eq!(r["tested_values"].as_u64(), Some(12));
+}
+
+#[tokio::test]
+async fn the_capability_strip_is_grounded_in_facts() {
+ let app = boot().await;
+ let (_, v) = get(&app, Some(&app.owner_cookie)).await;
+ let d = data(&v);
+ let caps = d["capabilities"].as_array().unwrap();
+ let ids: Vec<&str> = caps.iter().filter_map(|c| c["id"].as_str()).collect();
+ for must in ["search", "read", "graph", "ask", "map", "decide", "watch", "share"] {
+ assert!(ids.contains(&must), "missing capability {must}: {ids:?}");
+ }
+ // every entry names its real surface
+ for c in caps {
+ let named = ["href", "command", "endpoint"].iter().any(|k| c[*k].is_string());
+ assert!(named, "capability without a real surface: {c:#?}");
+ }
+ // a console route is an in-app hash route; nothing else can be an href
+ for c in caps {
+ if let Some(href) = c["href"].as_str() {
+ assert!(href.starts_with("#/"), "non-app href {href}");
+ }
+ }
+ // the owner's brain shows up, with its real link count
+ let brains = d["brains"].as_array().unwrap();
+ assert_eq!(brains.len(), 1);
+ assert_eq!(brains[0]["name"].as_str(), Some("casefile"));
+ assert_eq!(brains[0]["links"].as_u64(), Some(2));
+
+ // …and a role that may not read brains gets neither the brain nor the
+ // graph capability (no existence oracle, same rule as /graph/brains).
+ let (_, vv) = get(&app, Some(&app.viewer_cookie)).await;
+ let dv = data(&vv);
+ assert_eq!(dv["brains"].as_array().unwrap().len(), 0);
+ let vids: Vec<&str> = dv["capabilities"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|c| c["id"].as_str())
+ .collect();
+ assert!(!vids.contains(&"graph"), "viewer must not see the graph capability");
+}
+
+#[tokio::test]
+async fn nothing_indexed_is_the_empty_state_not_an_error() {
+ let app = boot_empty().await;
+ let (status, v) = get(&app, Some(&app.owner_cookie)).await;
+ assert_eq!(status, axum::http::StatusCode::OK);
+ let d = data(&v);
+ assert_eq!(d["catalog"].as_bool(), Some(false));
+ assert_eq!(d["datasets"].as_array().unwrap().len(), 0);
+ assert_eq!(d["others"].as_array().unwrap().len(), 0);
+ assert_eq!(d["totals"]["records"].as_u64(), Some(0));
+ let ids: Vec<&str> = d["capabilities"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|c| c["id"].as_str())
+ .collect();
+ assert!(!ids.contains(&"map"), "no catalog → no map/ask capability");
+ assert!(!ids.contains(&"ask"), "no catalog → no ask capability");
+ assert!(ids.contains(&"search"), "search is always real");
+}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 7c99f3881..1590c5000 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -329,7 +329,7 @@ fn help_text(feedback: bool) -> String {
log — searches, hit rate, latency (xerj gain --help)\n\
xerj brain <folder> one command: index a folder into a running, browsable\n\
second brain in your browser (see xerj brain --help)\n\
- xerj mcp [opts] Model Context Protocol stdio server: exposes 11 tools\n\
+ xerj mcp [opts] Model Context Protocol stdio server: exposes 13 tools\n\
(search, semantic, vector, hybrid, memory, second-brain,\n\
code-search) to any MCP client. Proxies to a node you\n\
already started — set XERJ_URL or --url (see xerj mcp --help)\n\
diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.css
index 8de8b993b..b7703ca81 100644
--- a/xerj-ux/assets/base.css
+++ b/xerj-ux/assets/base.css
@@ -2313,6 +2313,30 @@ button.sb-grouphead { width: 100%; }
.cp-empty p { margin: 8px 0; }
.cp-cmd { font-size: var(--fs-20); margin: var(--sp-2) 0; white-space: pre-wrap; }
+/* knowledge surface: field chips carry their measured facts, the rest of
+ the field list folds into a disclosure, relations and capabilities get
+ their own rows/strip (ux/corpus-render.js) */
+.cp-field__meta { margin-left: 6px; }
+.cp-field__ex { margin-left: 6px; color: var(--z-mute); }
+.cp-field--sem .cp-field__name { color: var(--z-accent); }
+.cp-fields__all { width: 100%; margin-top: 2px; }
+.cp-fields__all > summary { cursor: pointer; font-size: var(--fs-11); letter-spacing: var(--track-ui); color: var(--z-mute); }
+.cp-fields__all > summary:hover { color: var(--z-ink); }
+.cp-fields__all[open] > summary { color: var(--z-ink); margin-bottom: 6px; }
+.cp-rels { display: flex; flex-direction: column; gap: 10px; max-width: 100ch; }
+.cp-rel { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; font-size: var(--fs-13); }
+.cp-rel__pair { color: var(--z-ink); overflow-wrap: anywhere; }
+.cp-rel__why { color: var(--z-mute); }
+.cp-rel__ex { font-size: var(--fs-11); flex-basis: 100%; overflow-wrap: anywhere; }
+.cp-caps { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: var(--sp-3) var(--gap-x); }
+.cp-cap { border-top: 1px solid var(--z-faint); padding-top: 10px; min-width: 0; }
+.cp-cap__title { font-weight: 700; }
+.cp-cap__blurb { margin: 6px 0; color: var(--z-mute); font-size: var(--fs-13); line-height: 1.5; }
+.cp-cap__go { font-size: var(--fs-11); letter-spacing: var(--track-ui); }
+a.cp-cap__go { text-decoration: none; }
+a.cp-cap__go:hover { color: var(--z-accent); }
+.cp-cap--cli .cp-cap__go, .cp-cap--http .cp-cap__go { color: var(--z-ink); overflow-wrap: anywhere; }
+
/* reader */
.rd-search { display: flex; gap: var(--sp-2); align-items: center; border-bottom: 1px solid var(--z-faint); padding-bottom: 10px; margin-bottom: var(--sp-3); flex-wrap: wrap; }
.rd-q { flex: 1 1 320px; min-width: 0; background: transparent; border: 0; outline: 0; color: var(--z-ink); font-family: var(--font-data); font-size: var(--fs-16); padding: 6px 0; }
diff --git a/xerj-ux/src/app.js b/xerj-ux/src/app.js
index ccbee1777..95814dc1c 100644
--- a/xerj-ux/src/app.js
+++ b/xerj-ux/src/app.js
@@ -26,7 +26,7 @@ import { sbBrainsPresent } from './data/brains-probe.js';
import { dataFeaturesPresent, emptyDataFeatures } from './data/data-probe.js';
import { indexNames } from './data/schema.js';
import { mount } from './ux/safe-dom.js';
-import { renderCorpus } from './ux/corpus-render.js';
+import { renderCorpus, renderRelations, renderCapabilities } from './ux/corpus-render.js';
import { ReaderView, parseReaderRoute } from './ux/reader-view.js';
import { readerHref } from './ux/reader-render.js';
import { makeReaderApi } from './data/reader-api.js';
@@ -550,8 +550,9 @@ function parseRoute() {
}
// 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.
+// need. Async because the reads hit the console's data-sources facade
+// (data/data-sources.js — real-only; an unreachable engine yields
+// empty lists, never seeded rows).
async function buildSectionData(sectionId) {
if (sectionId === 'data') {
const clusters = await listClusters();
@@ -1228,6 +1229,13 @@ function mountSafePanels(dash, data) {
const st = data && data.status ? data : { status: 'error', error: (data && data.error) || 'the catalog returned nothing' };
mount(corpusEl, renderCorpus(st, { guest: false }));
}
+ // The knowledge surface's other two panels — the relations autoindex
+ // inferred and the capability strip. Same rule as the grid above: nodes
+ // only, and an honest empty state rather than an omission.
+ const relsEl = document.querySelector('[data-safe-mount="corpus-relations"]');
+ if (relsEl) mount(relsEl, renderRelations(data || {}));
+ const capsEl = document.querySelector('[data-safe-mount="corpus-capabilities"]');
+ if (capsEl) mount(capsEl, renderCapabilities(data || {}));
const readerEl = document.querySelector('[data-safe-mount="reader"]');
if (readerEl) {
readerView.attach(readerEl);
diff --git a/xerj-ux/src/dashboards/corpus.js b/xerj-ux/src/dashboards/corpus.js
index 886f259ab..a127113a4 100644
--- a/xerj-ux/src/dashboards/corpus.js
+++ b/xerj-ux/src/dashboards/corpus.js
@@ -1,22 +1,39 @@
// ============================================================
// Section — CORPUS (the home page after `xerj brain <folder>`)
//
-// One card per dataset the autoindex catalog records: what it is, how much,
-// what formats, its time span, the top fields with types, and the sample
-// queries autoindex wrote for it. On an engine with no datasets: the exact
-// one command to run. Data comes from `backends/xerj.js#liveCorpus` (the
-// `autoindex-catalog` index, live) and is listed in data/query.js#NEVER_MOCK:
-// this page shows what the engine reports, or an error — never a sample.
+// The knowledge surface. One read — GET /_xerj-console/api/v1/knowledge —
+// answers the three questions a person has the moment indexing finishes:
//
-// The panel below is a MOUNT POINT, not markup. Everything on a card can be
-// document-derived, so the shell (app.js#mountSafePanels) fills it with nodes
-// from ux/corpus-render.js through ux/safe-dom.js. No document string is ever
-// interpolated into the HTML this module returns.
+// HOW LARGE the scene meta line: datasets, records, source bytes
+// (whole-corpus totals, computed server-side)
+// WHICH DATA one card per dataset: live doc count and store bytes,
+// formats, time span, the FULL field list with types,
+// coverage, null% and example values, and the sample
+// queries autoindex wrote — plus any other index the
+// engine holds; then the cross-dataset relations
+// autoindex actually inferred (key overlaps, time
+// alignments — an empty list is shown as none, never
+// guessed)
+// WHAT NOW a capability strip grounded in real surfaces: console
+// routes, CLI commands, HTTP endpoints the node really
+// serves (the server computes availability from facts;
+// this module adds nothing)
+//
+// Data comes from `backends/xerj.js#liveCorpus` and is listed in
+// data/query.js#NEVER_MOCK: this page shows what the engine reports, or an
+// error — never a sample.
+//
+// The panels below are MOUNT POINTS, not markup. Everything on a card can
+// be document-derived, so the shell (app.js#mountSafePanels) fills them
+// with nodes from ux/corpus-render.js through ux/safe-dom.js. No document
+// string is ever interpolated into the HTML this module returns.
// ============================================================
-import { fmtCount } from '../data/catalog.js';
+import { fmtCount, fmtBytes } from '../data/catalog.js';
export const CORPUS_MOUNT = '<div data-safe-mount="corpus" class="cp-mount"></div>';
+export const RELATIONS_MOUNT = '<div data-safe-mount="corpus-relations" class="cp-mount"></div>';
+export const CAPABILITIES_MOUNT = '<div data-safe-mount="corpus-capabilities" class="cp-mount"></div>';
export const corpus = {
id: 'corpus',
@@ -26,21 +43,37 @@ export const corpus = {
const datasets = data?.datasets || [];
const summaries = data?.summaries || [];
const n = datasets.length + summaries.length;
- const total = datasets.reduce((acc, c) => acc + c.records, 0) + summaries.reduce((acc, c) => acc + c.records, 0);
+ const totals = data?.totals || null;
+ const hasKnowledge = !!totals;
+ // Gate 1 — how large. The catalog's own whole-corpus numbers when the
+ // knowledge endpoint served them; the cards' sums otherwise.
+ const total = totals
+ ? totals.records
+ : datasets.reduce((acc, c) => acc + c.records, 0) + summaries.reduce((acc, c) => acc + c.records, 0);
const meta = data?.status === 'error'
? ['CATALOG UNREADABLE']
- : (n ? [`${n} DATASET${n === 1 ? '' : 'S'}`, `${fmtCount(total)} RECORDS`] : ['EMPTY']);
+ : (n ? [
+ `${n} DATASET${n === 1 ? '' : 'S'}`,
+ `${fmtCount(total)} RECORDS`,
+ ...(totals && totals.bytes ? [fmtBytes(totals.bytes)] : []),
+ ] : ['EMPTY']);
+ const relations = data?.relations;
+ const capabilities = data?.capabilities || [];
return {
title: 'CORPUS',
kicker: 'WHAT IS INDEXED',
meta,
caption: n
- ? 'Everything xerj brain / xerj autoindex wrote to this engine, read live from the autoindex catalog, plus any other index it holds. Open a dataset in the Reader, or run one of the sample queries its catalog entry carries.'
+ ? 'Everything xerj brain / xerj autoindex wrote to this engine — size, structure, relations and what you can run against it — read live, plus any other index it holds. Open a dataset in the Reader, or run one of the sample queries its catalog entry carries.'
: '',
panels: [
{ id: 'datasets', eyebrow: n ? 'ONE CARD PER DATASET · LIVE FROM autoindex-catalog' : 'WHAT IS INDEXED', cols: 12, type: 'corpus',
render: () => CORPUS_MOUNT,
},
+ ...(hasKnowledge ? [{ id: 'relations', eyebrow: 'RELATIONS AUTOINDEX INFERRED BETWEEN DATASETS · NOTHING GUESSED', cols: 12, type: 'corpus',
+ render: () => RELATIONS_MOUNT }] : []),
+ ...(capabilities.length ? [{ id: 'capabilities', eyebrow: 'WHAT YOU CAN DO WITH THIS CORPUS · EVERY ENTRY IS A REAL ROUTE, COMMAND OR ENDPOINT', cols: 12, type: 'corpus',
+ render: () => CAPABILITIES_MOUNT }] : []),
],
};
},
diff --git a/xerj-ux/src/dashboards/data.js b/xerj-ux/src/dashboards/data.js
index b50d48923..3f0a92ec9 100644
--- a/xerj-ux/src/dashboards/data.js
+++ b/xerj-ux/src/dashboards/data.js
@@ -1,18 +1,19 @@
// ============================================================
// 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.
+// Index / field inventory of the built-in engine. Every row on this
+// page comes from a real endpoint the console serves:
+// GET /_xerj-console/api/v1/data-sources/connections
+// GET …/connections/built-in/indices (names, docs, store bytes)
+// GET …/connections/built-in/indices/:i/fields (names, types)
+// An unreachable engine yields empty tables and a line saying so — never
+// sample clusters or seeded index names (data/data-sources.js is
+// real-only). Sizes, per-dataset fields with coverage/examples and the
+// capability strip live on CORPUS, the knowledge surface; this page is
+// the flat inventory under it.
// ============================================================
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';
@@ -43,15 +44,18 @@ export const dataSection = {
const activeIndices = indicesByCluster[active] || [];
const focusIndex = data.focusIndex || activeIndices[0]?.name;
const fields = fieldsByIndex[focusIndex] || [];
+ const unreachable = !clusters.length;
return {
title: 'DATA',
- kicker: 'CLUSTERS · INDICES · FIELDS',
+ kicker: 'CONNECTIONS · 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.',
+ caption: unreachable
+ ? 'No data source could be read. This page lists only what the engine reports — sign in, or start the node, and reload.'
+ : 'What the engine actually has: one row per index (documents, on-disk store bytes) and each index\'s mapping. Per-dataset structure, coverage and examples live on CORPUS.',
panels: [
- { id: 'clusters', eyebrow: 'CLUSTERS · CLICK TO SET DEFAULT', cols: 12, type: 'clusters',
+ { id: 'clusters', eyebrow: 'CONNECTIONS · CLICK TO SET DEFAULT', cols: 12, type: 'clusters',
render: () => renderClusters(clusters, active),
},
@@ -59,52 +63,26 @@ export const dataSection = {
render: () => renderIndices(activeIndices, focusIndex),
},
- { id: 'fields', eyebrow: `FIELDS · ${focusIndex || '—'} · FROM /v1/indices/:name/_mapping`, cols: 6, type: 'fields',
+ { id: 'fields', eyebrow: `FIELDS · ${focusIndex || '—'} · FROM THE INDEX MAPPING`, cols: 6, type: 'fields',
render: () => renderFields(fields),
},
- { id: 'howTo', eyebrow: 'CONNECTING A NEW CLUSTER', cols: 12, type: 'markdown',
+ { id: 'howTo', eyebrow: 'WHERE THESE NUMBERS COME FROM', 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.
+`## One connection, read live
-\`\`\`
-POST /v1/clusters
-{
- "id": "prod-us",
- "name": "PROD-US",
- "url": "https://xerj-us-east-1.internal:8080",
- "auth": { "type": "bearer", "token": "$XERJ_TOKEN" }
-}
-\`\`\`
+This node has one data source — its built-in engine — listed by
+\`GET /_xerj-console/api/v1/data-sources/connections\`. Indices and fields
+come from the same facade. Doc counts and store bytes are the engine's own
+(\`Index::stats\` and the index's data directory), not estimates.
-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.`
+The default connection is stored in \`localStorage.xerj.cluster\`, visible
+under SETTINGS. The knowledge surface — sizes, per-dataset fields,
+relations, capabilities — is CORPUS, the section this inventory sits
+under.`
),
},
- { 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,
- }),
- },
-
],
};
},
@@ -113,7 +91,7 @@ binding.`
// ---------- renderers -----------------------------------
function renderClusters(clusters, active) {
- if (!clusters.length) return '<div class="mono faint">No clusters configured.</div>';
+ if (!clusters.length) return '<div class="mono faint">No data source readable. Sign in and reload — this page never shows a sample.</div>';
const rows = clusters.map((c) => {
const isActive = c.id === active;
const status = {
@@ -128,15 +106,15 @@ function renderClusters(clusters, active) {
<span class="mg-cluster-url mono faint">${esc(c.url)}</span>
<span class="mg-cluster-stat mono">${humanCount(c.indices)}&nbsp;idx</span>
<span class="mg-cluster-stat mono">${humanCount(c.docs)}&nbsp;docs</span>
- <span class="mg-cluster-ver mono faint">${esc(c.version)}</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'];
+ if (!indices.length) return '<div class="mono faint">No indices on this engine.</div>';
+ const cols = ['NAME', 'DOCS', 'SIZE', 'SHARDS'];
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 = [
@@ -144,7 +122,6 @@ function renderIndices(indices, focusIndex) {
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('');
@@ -153,15 +130,17 @@ function renderIndices(indices, focusIndex) {
function renderFields(fields) {
if (!fields.length) return '<div class="mono faint">No mapping for this index.</div>';
- const cols = ['FIELD', 'TYPE', 'CARDINALITY', 'ENCODING', 'RATIO'];
+ // FIELD and TYPE only: cardinality, encoding and compression ratio are
+ // not on this endpoint, and a column that guesses from the type is a
+ // claim about the on-disk format this page cannot make. The measured
+ // per-field facts (coverage, null%, examples) live on CORPUS, from the
+ // autoindex catalog.
+ const cols = ['FIELD', 'TYPE'];
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>
+ <span class="mono faint">${esc(f.type)}${f.semantic ? ' · semantic' : ''}</span>
</div>`).join('');
return `<div class="mg-fld-table">${headRow}${body}</div>`;
}
diff --git a/xerj-ux/src/dashboards/second-brain.js b/xerj-ux/src/dashboards/second-brain.js
index d74d04f3d..50310391f 100644
--- a/xerj-ux/src/dashboards/second-brain.js
+++ b/xerj-ux/src/dashboards/second-brain.js
@@ -51,7 +51,13 @@ export const secondBrain = {
// agent-asserted links may carry no quote, and structural links
// carry a rationale, not note text. The kicker must not claim
// more than the schema enforces (spec §7.1, amended 2026-07-30).
- kicker: 'WHAT YOUR NOTES BELIEVE · EVERY LINK SHOWS ITS EVIDENCE · REPLAYABLE AT ANY MOMENT',
+ // It says DOCUMENTS, not notes: the corpus is whatever was indexed
+ // (mail, PDFs, code), and this page is its graph layer — reached
+ // from CORPUS, not a separate "knowledge base".
+ kicker: 'THE LINKS BETWEEN YOUR DOCUMENTS · EVERY LINK SHOWS ITS EVIDENCE · REPLAYABLE AT ANY MOMENT',
+ // The caption ties this page back to the one knowledge surface: the
+ // corpus (sizes, fields, relations, capabilities) lives on CORPUS.
+ caption: 'The graph layer of the corpus CORPUS shows: links between the documents you indexed, each with its evidence. Sizes, fields and relations live on CORPUS.',
meta: [time, 'XERJ-GRAPH'],
// Eyebrows speak user words — link / believed / retired / taught.
// Schema vocabulary (edge, src/dst, as-of) stays in the API and
diff --git a/xerj-ux/src/data/backends/xerj.js b/xerj-ux/src/data/backends/xerj.js
index 5b44605e7..5eff51f9c 100644
--- a/xerj-ux/src/data/backends/xerj.js
+++ b/xerj-ux/src/data/backends/xerj.js
@@ -12,7 +12,7 @@
import { liveSecondBrain } from '../second-brain-api.js';
import { schemaForSearch, indexNamesStrict } from '../schema.js';
import { buildSearchBody } from '../search-body.js';
-import { CATALOG_INDEX, catalogQueryBody, parseCatalogHits } from '../catalog.js';
+import { CATALOG_INDEX, catalogQueryBody, parseCatalogHits, parseKnowledge } from '../catalog.js';
import { listUserIndices, INTERNAL_INDICES } from '../console-index-api.js';
// Aggregation materialisation bypass.
@@ -29,6 +29,11 @@ import { listUserIndices, INTERNAL_INDICES } from '../console-index-api.js';
// Track engine fix at: engine bug "agg materialisation cap".
const AGG_BYPASS_SIZE = 9999;
+/** The knowledge surface — one session-authenticated read, same origin as
+ * this SPA (the console API serves both). See knowledge.rs for the
+ * payload; data/catalog.js#parseKnowledge for its client shape. */
+const KNOWLEDGE_PATH = '/_xerj-console/api/v1/knowledge';
+
export const meta = {
id: 'xerj',
label: 'Xerj',
@@ -135,22 +140,54 @@ export async function search(baseUrl, dashId, ctx, signal) {
// ── corpus ──────────────────────────────────────────────────────────
//
-// The Corpus home: every dataset `xerj brain` / `xerj autoindex` recorded in
-// the `autoindex-catalog` index, plus any other user index the engine holds
-// (listed by name and document count, so an engine that was filled some other
-// way does not read as "nothing indexed"). NEVER returns null and never
-// throws: data/query.js treats null as "fall back to mock", and a fabricated
-// corpus is the one thing this page must not be able to show.
-async function liveCorpus(baseUrl, _ctx, signal) {
+// The Corpus home is the knowledge surface: ONE read —
+// GET /_xerj-console/api/v1/knowledge — that returns what a person asks the
+// moment `xerj brain` finishes: the whole-corpus totals, every dataset the
+// autoindex catalog records with its full field list, the relations
+// autoindex actually inferred between datasets, and a capability strip
+// grounded in real routes/commands/endpoints. Plus any other user index
+// the engine holds, so an engine that was filled some other way does not
+// read as "nothing indexed".
+//
+// NEVER returns null and never throws: data/query.js treats null as "fall
+// back to mock", and a fabricated corpus is the one thing this page must
+// not be able to show. A session that cannot read the endpoint (401/403)
+// or an unreachable console is returned as `{ status: 'error' }`.
+async function liveCorpus(_baseUrl, _ctx, signal) {
+ try {
+ const r = await fetch(KNOWLEDGE_PATH, {
+ signal,
+ credentials: 'same-origin',
+ headers: { accept: 'application/json' },
+ });
+ if (!r.ok) {
+ const err = new Error(`knowledge HTTP ${r.status}`);
+ err.status = r.status;
+ throw err;
+ }
+ return parseKnowledge(await r.json());
+ } catch (e) {
+ if (e && e.name === 'AbortError') throw e;
+ if (e && e.status === 404) return legacyLiveCorpus(signal); // engine older than the endpoint
+ // A fetch that never reached the engine is a bare TypeError ("Failed to
+ // fetch"): say what it means, as the Reader and the guest shell do.
+ const message = e instanceof TypeError ? 'engine unreachable' : String(e && e.message || e).slice(0, 200);
+ return { status: 'error', error: message, datasets: [], summaries: [], totals: null, relations: [], capabilities: [], brains: [] };
+ }
+}
+
+/** The pre-knowledge-endpoint path: the catalog index read directly plus
+ * the index list — same cards, no totals/relations/capabilities. Kept for
+ * engines built before the endpoint existed (the SPA and the binary ship
+ * together, so this is belt-and-braces, and the node tests still pin it). */
+async function legacyLiveCorpus(signal) {
let datasets = [];
let catalogError = null;
try {
- const resp = await rawSearch(baseUrl, CATALOG_INDEX, catalogQueryBody(), signal);
+ const resp = await rawSearch(null, CATALOG_INDEX, catalogQueryBody(), signal);
datasets = parseCatalogHits(resp?.hits?.hits || []);
} catch (e) {
// No catalog index yet (HTTP 404) is the ordinary empty state, not an error.
- // A fetch that never reached the engine is a bare TypeError ("Failed to
- // fetch"): say what it means, as the Reader and the guest shell do.
if (e instanceof TypeError) catalogError = 'engine unreachable';
else if (!/HTTP 404/.test(String(e))) catalogError = String(e && e.message || e).slice(0, 200);
}
@@ -165,7 +202,7 @@ async function liveCorpus(baseUrl, _ctx, signal) {
/* the catalog cards still stand on their own */
}
if (catalogError && !datasets.length && !others.length) return { status: 'error', error: catalogError, datasets: [], summaries: [] };
- return { status: 'ok', datasets, summaries: others, _live: true };
+ return { status: 'ok', datasets, summaries: others, totals: null, relations: [], capabilities: [], brains: [], _live: true };
}
// ── search-discover ────────────────────────────────────────────────
@@ -350,43 +387,32 @@ function bucketSize(range) {
// ── 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;
+// Real-only: the built-in connection, its indices and their mappings,
+// from the same facade the DATA section reads (data/data-sources.js —
+// see that module for why nothing here is ever seeded). The section
+// view builds its shape in app.js#buildSectionData; this adapter serves
+// any dashboard-form consumer of the same id.
+async function liveData(_baseUrl, _ctx, signal) {
+ const { listClusters, listIndices, listFields } = await import('../data-sources.js');
+ const clusters = await listClusters();
+ const indicesByCluster = {};
+ for (const c of clusters) {
+ indicesByCluster[c.id] = await listIndices(c.id);
}
- 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;
+ const active = clusters[0]?.id || 'local';
+ const fieldsByIndex = {};
+ for (const i of indicesByCluster[active] || []) {
+ fieldsByIndex[i.name] = await listFields(i.name);
}
- base._live = { indices: liveIndices };
- return base;
+ void signal;
+ return {
+ clusters,
+ indicesByCluster,
+ fieldsByIndex,
+ activeCluster: active,
+ focusIndex: (indicesByCluster[active] || [])[0]?.name || null,
+ _live: { indices: indicesByCluster[active] || [] },
+ };
}
// ─────────────────────────────────────────────────────────────────────
diff --git a/xerj-ux/src/data/catalog.js b/xerj-ux/src/data/catalog.js
index a57276fd0..a2f768681 100644
--- a/xerj-ux/src/data/catalog.js
+++ b/xerj-ux/src/data/catalog.js
@@ -30,7 +30,8 @@ function parseFields(fieldsJson) {
semantic: !!f.semantic,
coverage: Number.isFinite(Number(f.coverage)) ? Number(f.coverage) : 1,
cardinality: num(f.cardinality_est),
- examples: Array.isArray(f.examples) ? f.examples.slice(0, 2).map(str) : [],
+ nullRatio: Number.isFinite(Number(f.null_ratio)) ? Number(f.null_ratio) : null,
+ examples: Array.isArray(f.examples) ? f.examples.slice(0, 3).map(str) : [],
}));
}
@@ -99,6 +100,104 @@ export function topFields(card, n = 8) {
.slice(0, n);
}
+// ── the knowledge surface ───────────────────────────────────────────
+//
+// GET /_xerj-console/api/v1/knowledge is ONE read that answers the three
+// questions a person has the moment indexing finishes — how large, which
+// data, what can I do now. The server (xerj-console-api/src/knowledge.rs)
+// joins the catalog's own numbers with the engine's live ones and computes
+// the totals, the relations autoindex actually inferred, and a capability
+// strip grounded in real routes/commands/endpoints. parseKnowledge()
+// normalizes that payload into the SAME card shape parseCatalogHits
+// produces (plus the live facts), so the render layer has one shape
+// whatever served it.
+
+const knowledgeField = (f) => ({
+ name: str(f.name),
+ type: str(f.type || 'object'),
+ semantic: f.semantic === true,
+ coverage: Number.isFinite(Number(f.coverage)) ? Number(f.coverage) : null,
+ cardinality: Number.isFinite(Number(f.cardinality)) ? Number(f.cardinality) : null,
+ nullRatio: Number.isFinite(Number(f.null_ratio)) ? Number(f.null_ratio) : null,
+ examples: Array.isArray(f.examples) ? f.examples.slice(0, 3).map(str) : [],
+});
+
+const knowledgeDataset = (d) => ({
+ index: str(d.index),
+ slug: str(d.slug) || str(d.index).replace(/^ax-/, ''),
+ formats: Array.isArray(d.formats) ? d.formats.map(str) : [],
+ records: num(d.records),
+ junk: num(d.junk),
+ files: num(d.files),
+ bytes: num(d.bytes),
+ liveDocs: Number.isFinite(Number(d.live_docs)) ? Number(d.live_docs) : null,
+ storeBytes: Number.isFinite(Number(d.store_bytes)) ? Number(d.store_bytes) : null,
+ timeField: str(d.time_field) || null,
+ timeMin: str(d.time_min) || null,
+ timeMax: str(d.time_max) || null,
+ semanticField: str(d.semantic_field) || null,
+ fields: (Array.isArray(d.fields) ? d.fields : []).map(knowledgeField),
+ sampleQueries: parseSampleQueries(d.sample_queries),
+ notes: Array.isArray(d.notes) ? d.notes.map(str) : [],
+ runId: str(d.run_id) || null,
+});
+
+/** A key_overlap / time_alignment relation row, in display shape. */
+const knowledgeRelation = (r) => ({
+ kind: str(r.kind) === 'time_alignment' ? 'time_alignment' : 'key_overlap',
+ aIndex: str(r.a_index), aField: str(r.a_field), aDataset: str(r.a_dataset) || null,
+ bIndex: str(r.b_index), bField: str(r.b_field), bDataset: str(r.b_dataset) || null,
+ grade: str(r.grade),
+ overlap: num(r.overlap),
+ containment: Number.isFinite(Number(r.containment)) ? Number(r.containment) : null,
+ confirmed: Number.isFinite(Number(r.confirmed_values)) ? Number(r.confirmed_values) : null,
+ tested: Number.isFinite(Number(r.tested_values)) ? Number(r.tested_values) : null,
+ examples: Array.isArray(r.examples) ? r.examples.slice(0, 3).map(str) : [],
+ rangeOverlap: Number.isFinite(Number(r.range_overlap)) ? Number(r.range_overlap) : null,
+ sharedBuckets: Number.isFinite(Number(r.shared_buckets)) ? Number(r.shared_buckets) : null,
+ pearsonR: Number.isFinite(Number(r.pearson_r)) ? Number(r.pearson_r) : null,
+ activityCorrelated: r.activity_correlated === true,
+});
+
+/**
+ * The `{ data: … }` body of GET /_xerj-console/api/v1/knowledge → the
+ * corpus state the Corpus home renders: `datasets` (cards, same shape as
+ * parseCatalogHits + the engine's live doc counts and store bytes),
+ * `summaries` (indices the catalog does not describe), whole-corpus
+ * `totals`, `relations`, `capabilities` and `brains`. Pure; throws on
+ * nothing (a malformed payload degrades to empty lists, and the caller
+ * decides what an unreachable engine means).
+ */
+export function parseKnowledge(payload) {
+ const d = (payload && payload.data && typeof payload.data === 'object') ? payload.data : {};
+ const datasets = (Array.isArray(d.datasets) ? d.datasets : []).map(knowledgeDataset);
+ datasets.sort((a, b) => (b.records - a.records) || a.index.localeCompare(b.index));
+ const summaries = (Array.isArray(d.others) ? d.others : []).map((o) => ({
+ index: str(o.index),
+ records: num(o.docs),
+ storeBytes: Number.isFinite(Number(o.store_bytes)) ? Number(o.store_bytes) : null,
+ emails: 0, attachments: 0, formats: [],
+ }));
+ const t = d.totals || {};
+ const totals = {
+ datasets: num(t.datasets), records: num(t.records), files: num(t.files),
+ bytes: num(t.bytes), docs: num(t.docs), relations: num(t.relations),
+ catalog: d.catalog === true,
+ };
+ const relations = (Array.isArray(d.relations) ? d.relations : []).map(knowledgeRelation);
+ const capabilities = (Array.isArray(d.capabilities) ? d.capabilities : [])
+ .filter((c) => c && typeof c === 'object' && c.id)
+ .map((c) => ({
+ id: str(c.id), title: str(c.title), blurb: str(c.blurb),
+ href: str(c.href) || null, command: str(c.command) || null, endpoint: str(c.endpoint) || null,
+ kind: str(c.kind) || (c.href ? 'console' : 'cli'),
+ }));
+ const brains = (Array.isArray(d.brains) ? d.brains : []).map((b) => ({
+ name: str(b.name), links: num(b.links),
+ }));
+ return { status: 'ok', datasets, summaries, totals, relations, capabilities, brains, _live: true };
+}
+
function firstMatchText(clause) {
if (!clause || typeof clause !== 'object') return null;
if (clause.match) {
diff --git a/xerj-ux/src/data/data-sources.js b/xerj-ux/src/data/data-sources.js
index de7833a25..0aadbf529 100644
--- a/xerj-ux/src/data/data-sources.js
+++ b/xerj-ux/src/data/data-sources.js
@@ -1,109 +1,27 @@
// ============================================================
-// XERJ.ai — Data source catalog (mock)
+// XERJ Console — data source catalog (REAL ONLY)
//
-// 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 }
+// What the engine actually has, read through the console's own
+// session-authenticated facade:
+// GET /_xerj-console/api/v1/data-sources/connections → rows
+// GET /_xerj-console/api/v1/data-sources/connections/built-in/indices → { indices }
+// GET /_xerj-console/api/v1/data-sources/connections/built-in/indices/:i/fields
//
-// 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.
+// This module used to seed four fabricated clusters (prod-us with 840M
+// documents and the like) and fall back to mock index/field arrays when
+// the engine was unreachable — an inventory page that can show numbers
+// the engine never reported is worse than one that says "nothing
+// reachable", so the fabrications are gone: every row here is a row a
+// real endpoint returned, and a failure yields an empty list and the
+// section says so.
+//
+// The one-connection truth: a standalone node has exactly one data
+// source, the `built-in` engine. When HTTP-shaped connection adapters
+// land, more rows appear here from the same endpoint — nothing to
+// re-seed.
// ============================================================
-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.
+const XAPI = '/_xerj-console/api/v1';
function liveBaseUrl() {
if (typeof window !== 'undefined' && window.location && window.location.origin) {
@@ -112,231 +30,105 @@ function liveBaseUrl() {
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 getJson(path) {
+ const r = await fetch(path, { credentials: 'same-origin' });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+}
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; }
+ const body = await getJson(XAPI + '/data-sources/connections');
+ return body?.data?.connections || [];
+ } catch (_e) { return []; }
}
-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.
+/** The LOCAL row: this node's built-in engine, from the connections
+ * endpoint. `indices`/`docs` are left null — not 0, not a guess — until
+ * the indices endpoint is read (the DATA section fills them in). */
+async function localRow() {
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; }
+ const builtIn = conns.find((c) => c && c.id === 'built-in');
+ if (!builtIn) return null;
+ return {
+ id: 'local',
+ name: (builtIn.name || 'LOCAL').toUpperCase(),
+ url: liveBaseUrl(),
+ status: builtIn.status || 'green',
+ version: builtIn.version || null,
+ kind: builtIn.kind || null,
+ indices: null,
+ docs: 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; }
+ const body = await getJson(XAPI + '/data-sources/connections/built-in/indices');
+ const list = body?.data?.indices || [];
+ return list.map((it) => ({
+ name: it.name,
+ docs: Number(it.docs || 0),
+ // Real on-disk store bytes measured server-side from the index's data
+ // dir (the same number /_cat/indices reports). Not yet, never 0-by-
+ // construction.
+ bytes: Number.isFinite(Number(it.bytes)) ? Number(it.bytes) : null,
+ 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) {
+ return null;
+ }
}
async function liveFields(indexName) {
- // Xerj Console facade first.
try {
- const r = await fetch(
+ const body = await getJson(
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,
+ const list = body?.data?.fields || [];
+ // Only what the endpoint actually reports: name and type. Cardinality,
+ // encoding and compression ratio are NOT guessed from the type — the
+ // engine's per-field encodings are not on this facade, and a wrong
+ // label here would be a claim about the on-disk format.
+ return list.map((f) => ({
+ name: f.name,
+ type: f.type || 'object',
+ semantic: f.semantic === true,
}));
- } 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 '—';
+ } catch (_e) {
+ return null;
}
}
-/** 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). */
+/** List configured data sources. Real rows only; `[]` when the console
+ * facade cannot be read (the section shows why, not a sample). */
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;
+ const row = await localRow();
+ return row ? [row] : [];
}
+/** The cluster picker's synchronous row — the built-in engine, with no
+ * fabricated counts. Used before any fetch resolves; `null` counts mean
+ * "not read yet". */
export function listClustersSync() {
- return MOCK_CLUSTERS;
+ return [{ id: 'local', name: 'LOCAL', url: liveBaseUrl(), status: 'green', indices: null, docs: null }];
}
-/** 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 indices of the built-in engine. Real rows only; `[]` on failure. */
+export async function listIndices(_clusterId) {
+ const live = await liveIndices();
+ return live || [];
}
-/** List fields in an index. For live indices, fetch the mapping. */
+/** List fields of one index, from the engine's mapping. `[]` on failure. */
export async function listFields(indexName) {
- if (MOCK_FIELDS[indexName]) return MOCK_FIELDS[indexName];
const live = await liveFields(indexName);
return live || [];
}
diff --git a/xerj-ux/src/ux/corpus-render.js b/xerj-ux/src/ux/corpus-render.js
index bbbd280af..487f8839d 100644
--- a/xerj-ux/src/ux/corpus-render.js
+++ b/xerj-ux/src/ux/corpus-render.js
@@ -33,6 +33,44 @@ export function renderCorpusEmpty({ guest } = {}) {
const fact = (k, v) => h('span', { class: 'cp-fact' }, h('span', { class: 'faint' }, k), ' ', v);
+/** A field's measured facts, as text: coverage (null = not measured → "—"),
+ * null% when nonzero, cardinality when known. These are the catalog's own
+ * numbers — the same ones `xerj autoindex map` prints for agents. */
+function fieldMeta(f) {
+ const pct = (v) => (v == null ? '—' : `${Math.round(v * 100)}%`);
+ const parts = [pct(f.coverage)];
+ if (f.nullRatio != null && f.nullRatio > 0) parts.push(`${Math.round(f.nullRatio * 100)}% null`);
+ if (f.cardinality != null) parts.push(f.cardinality === 0 ? 'all same' : `${fmtCount(f.cardinality)} distinct`);
+ return parts.join(' · ');
+}
+
+/** One field chip. The example values are VISIBLE text (they were
+ * hover-only before, which on touch and on first read is "no examples at
+ * all"), and everything on the chip is data the catalog measured. */
+function fieldChip(f) {
+ const ex = f.examples && f.examples.length ? h('span', { class: 'cp-field__ex' }, ` e.g. ${f.examples.slice(0, 2).join(' · ')}`) : null;
+ return h('span', { class: `cp-field mono${f.semantic ? ' cp-field--sem' : ''}`, title: f.examples && f.examples.length ? f.examples.join(' · ') : '' },
+ h('span', { class: 'cp-field__name' }, f.name),
+ h('span', { class: 'cp-field__type' }, f.type),
+ h('span', { class: 'cp-field__meta faint' }, fieldMeta(f)),
+ ex);
+}
+
+/** The fields block: the ranked top fields as chips, then EVERY field in a
+ * disclosure when there are more. A corpus's structure is the one thing a
+ * person came to see — nothing is capped away. */
+function fieldsBlock(card) {
+ const all = card.fields || [];
+ if (!all.length) return null;
+ const top = topFields(card, 8);
+ const rest = all.filter((f) => !top.includes(f));
+ return h('div', { class: 'cp-fields' },
+ top.map(fieldChip),
+ rest.length ? h('details', { class: 'cp-fields__all' },
+ h('summary', null, `ALL ${all.length} FIELDS`),
+ h('div', { class: 'cp-fields' }, rest.map(fieldChip))) : null);
+}
+
function sampleButtons(card) {
const out = [];
for (const sq of card.sampleQueries || []) {
@@ -58,28 +96,27 @@ function sampleButtons(card) {
* 14-file corpus), so those facts are labelled as the last run's. */
const LAST_RUN = 'as of the last xerj brain / autoindex run over this dataset (autoindex-catalog)';
-/** One dataset card from a catalog entry (data/catalog.js#parseCatalogHits). */
+/** One dataset card from a catalog entry (data/catalog.js — parseCatalogHits
+ * or parseKnowledge; the latter also carries the engine's LIVE doc count and
+ * store bytes for the index, shown next to the run's own numbers). */
export function renderCorpusCard(card, { brain, discover = true } = {}) {
- const fields = topFields(card, 8);
const span = timeSpan(card);
const samples = sampleButtons(card);
return h('article', { class: 'cp-card', 'data-corpus-index': card.index },
h('div', { class: 'cp-card__head' },
h('div', null, h('div', { class: 'key' }, 'DATASET'), h('h2', { class: 'cp-card__name mono' }, card.index)),
h('div', { class: 'cp-card__nums mono' },
- h('span', null, h('b', { class: 'accent' }, fmtCount(card.records)), ' records'),
+ h('span', { title: card.liveDocs != null ? `${fmtCount(card.liveDocs)} documents in the index now` : LAST_RUN },
+ h('b', { class: 'accent' }, fmtCount(card.liveDocs != null ? card.liveDocs : card.records)), ' records'),
h('span', { title: LAST_RUN }, h('b', null, fmtCount(card.files)), ' files'),
- h('span', { title: LAST_RUN }, h('b', null, fmtBytes(card.bytes))),
+ h('span', { title: card.storeBytes != null ? `${fmtBytes(card.storeBytes)} on disk now` : LAST_RUN }, h('b', null, fmtBytes(card.bytes))),
h('span', { class: 'faint', title: LAST_RUN }, '· last run'))),
h('div', { class: 'cp-card__facts mono' },
card.formats.length ? fact('formats · last run', card.formats.join(', ')) : null,
span ? fact(card.timeField || 'time', span) : null,
card.semanticField ? fact('semantic_text field', card.semanticField) : h('span', { class: 'cp-fact faint', title: LAST_RUN }, 'no semantic_text field in the last run'),
card.junk ? fact('skipped as junk', fmtCount(card.junk)) : null),
- fields.length
- ? h('div', { class: 'cp-fields' }, fields.map((f) => h('span', { class: 'cp-field mono', title: f.examples.join(' · ') },
- h('span', { class: 'cp-field__name' }, f.name), h('span', { class: 'cp-field__type' }, f.type))))
- : null,
+ fieldsBlock(card),
h('div', { class: 'cp-actions' },
h('a', { class: 'text-btn', href: readerHref({ index: card.index, brain }) }, 'OPEN IN READER'),
discover ? h('a', { class: 'text-btn', href: '#/discover', 'data-corpus-browse': card.index }, 'BROWSE IN DISCOVER') : null),
@@ -128,3 +165,76 @@ export function renderCorpus(state = {}, { guest = false, brain } = {}) {
if (!cards.length) return renderCorpusEmpty({ guest });
return h('div', { class: 'cp-grid' }, cards);
}
+
+// ── relations ───────────────────────────────────────────────────────
+//
+// What autoindex CORRELATE actually inferred between two datasets — a key
+// overlap ("these two datasets share these values: a join exists") or a
+// time alignment ("they cover the same period and move together"). Only
+// inferred relations are ever listed; an empty list is shown as none,
+// never as a guess. The field names and the shared values are
+// document-derived, so this goes through safe-dom like everything else.
+
+const pct1 = (v) => (v == null ? null : `${Math.round(v * 100)}%`);
+
+function relationRow(r) {
+ const left = `${r.aIndex}.${r.aField}`;
+ const right = `${r.bIndex}.${r.bField}`;
+ if (r.kind === 'time_alignment') {
+ const bits = [
+ pct1(r.rangeOverlap) ? `ranges overlap ${pct1(r.rangeOverlap)}` : null,
+ r.sharedBuckets ? `${fmtCount(r.sharedBuckets)} shared time buckets` : null,
+ r.pearsonR != null ? `activity r=${r.pearsonR.toFixed(2)}${r.activityCorrelated ? ' · correlated' : ''}` : null,
+ ].filter(Boolean);
+ return h('div', { class: 'cp-rel' },
+ h('span', { class: 'cp-rel__pair mono' }, left, ' ⟷ ', right),
+ h('span', { class: 'cp-rel__why' }, bits.join(' · ') || 'time-aligned'));
+ }
+ const why = [
+ r.overlap ? `${fmtCount(r.overlap)} shared values` : null,
+ r.grade ? r.grade : null,
+ r.confirmed != null && r.tested != null ? `${fmtCount(r.confirmed)}/${fmtCount(r.tested)} confirmed by query` : null,
+ pct1(r.containment) ? `${pct1(r.containment)} containment` : null,
+ ].filter(Boolean).join(' · ');
+ return h('div', { class: 'cp-rel' },
+ h('span', { class: 'cp-rel__pair mono' }, left, ' ⟷ ', right),
+ h('span', { class: 'cp-rel__why' }, why || 'fields overlap'),
+ r.examples.length ? h('span', { class: 'cp-rel__ex faint mono' }, `e.g. ${r.examples.slice(0, 3).join(' · ')}`) : null);
+}
+
+/** The relations panel: one row per inferred cross-dataset relation. */
+export function renderRelations(state = {}) {
+ const rels = (state.relations || []).filter((r) => r && r.aIndex && r.bIndex);
+ if (!rels.length) {
+ return h('div', { class: 'cp-empty' },
+ h('p', null, 'No cross-dataset relations were inferred'),
+ h('p', { class: 'faint' }, 'Autoindex correlates key-like fields and time spans between datasets; a corpus with no shared keys or dates has none. Nothing is guessed here.'));
+ }
+ return h('div', { class: 'cp-rels' }, rels.map(relationRow));
+}
+
+// ── capabilities ────────────────────────────────────────────────────
+//
+// "What can I do with this now?" — one entry per REAL surface, each naming
+// the console route, CLI command or HTTP endpoint it refers to. The list is
+// computed server-side from facts on the node (catalog present, brains
+// present); the renderer only lays it out and never adds an entry of its
+// own — a capability this page claims that the engine does not have is the
+// one dishonesty the console cannot undo.
+
+function capabilityCard(c) {
+ const surface = c.href
+ ? h('a', { class: 'cp-cap__go mono', href: c.href }, c.href.replace(/^#\//, '').toUpperCase())
+ : h('span', { class: 'cp-cap__go mono' }, c.command || c.endpoint || '');
+ return h('div', { class: `cp-cap cp-cap--${c.kind}` },
+ h('div', { class: 'cp-cap__title' }, c.title),
+ h('p', { class: 'cp-cap__blurb' }, c.blurb),
+ surface);
+}
+
+/** The capability strip. */
+export function renderCapabilities(state = {}) {
+ const caps = (state.capabilities || []).filter((c) => c && c.title);
+ if (!caps.length) return null;
+ return h('div', { class: 'cp-caps' }, caps.map(capabilityCard));
+}
diff --git a/xerj-ux/src/ux/safe-dom.js b/xerj-ux/src/ux/safe-dom.js
index 8922c7ee5..a69f8e9ec 100644
--- a/xerj-ux/src/ux/safe-dom.js
+++ b/xerj-ux/src/ux/safe-dom.js
@@ -43,6 +43,10 @@ export const TAGS = new Set([
'pre', 'code', 'mark', 'article', 'section', 'header', 'footer', 'nav',
'button', 'b', 'strong', 'em', 'small', 'dl', 'dt', 'dd', 'br', 'hr',
'label', 'input', 'select', 'option', 'time',
+ // The only interactive element added for the knowledge surface: a
+ // disclosure. It collapses/expands content the browser itself — no
+ // script, no focus behaviour to get wrong, nothing loads.
+ 'details', 'summary',
]);
/** Attribute names a render function may set (plus `data-*` / `aria-*`). */
diff --git a/xerj-ux/test/fixtures/inert.mjs b/xerj-ux/test/fixtures/inert.mjs
index e1451b73c..7848cf7d3 100644
--- a/xerj-ux/test/fixtures/inert.mjs
+++ b/xerj-ux/test/fixtures/inert.mjs
@@ -3,8 +3,16 @@ import assert from 'node:assert/strict';
import { TAGS, attrAllowed, walk, textOf } from '../../src/ux/safe-dom.js';
/** Tags that load a resource, run script, or submit somewhere. None of them
- * is in TAGS; listed so a future "just add <img>" fails HERE with a reason. */
-export const FORBIDDEN_TAGS = ['script', 'img', 'svg', 'iframe', 'object', 'embed', 'style', 'link', 'meta', 'base', 'form', 'video', 'audio', 'source', 'math', 'template', 'frame', 'frameset', 'applet', 'textarea', 'details', 'animate', 'image'];
+ * is in TAGS; listed so a future "just add <img>" fails HERE with a reason.
+ *
+ * `<details>` is NOT here and IS in TAGS (knowledge surface, the ALL-FIELDS
+ * fold-out): it loads, runs and submits nothing — the only interaction is
+ * the browser's own disclosure toggle, and every `on*` attribute
+ * (ontoggle included) stays rejected by the closed ATTRS list, so a
+ * document cannot reach it. It was on this list as part of the original
+ * blanket "nothing interactive but <button>" rule, before anything needed
+ * a disclosure. */
+export const FORBIDDEN_TAGS = ['script', 'img', 'svg', 'iframe', 'object', 'embed', 'style', 'link', 'meta', 'base', 'form', 'video', 'audio', 'source', 'math', 'template', 'frame', 'frameset', 'applet', 'textarea', 'animate', 'image'];
export const FORBIDDEN_ATTRS = ['style', 'src', 'srcset', 'srcdoc', 'action', 'formaction', 'background', 'poster', 'ping', 'xlink:href', 'target', 'download', 'is', 'nonce', 'integrity', 'sandbox', 'allow'];
export function assertInert(tree, label = 'tree') {
diff --git a/xerj-ux/test/knowledge-surface.test.mjs b/xerj-ux/test/knowledge-surface.test.mjs
new file mode 100644
index 000000000..90a4a4f07
--- /dev/null
+++ b/xerj-ux/test/knowledge-surface.test.mjs
@@ -0,0 +1,174 @@
+// The knowledge surface — one read that answers, the moment indexing
+// finishes: how large the corpus is, which data is in it, and what can be
+// done with it. These tests pin the DATA (payload → cards/rows/strip),
+// never the styling. Run: node --test xerj-ux/test/
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+// renderCorpus and friends are pure safe-dom; set a fetch stub before the
+// imports that could touch the network.
+const calls = [];
+let respond = () => json(200, {});
+globalThis.fetch = async (url, init) => { calls.push(String(url)); return respond(String(url), init); };
+function json(status, body) {
+ return { status, ok: status >= 200 && status < 300, json: async () => body, text: async () => JSON.stringify(body) };
+}
+
+const { parseKnowledge } = await import('../src/data/catalog.js');
+const { renderCorpusCard, renderRelations, renderCapabilities } = await import('../src/ux/corpus-render.js');
+const { corpus } = await import('../src/dashboards/corpus.js');
+const { textOf, findAll } = await import('../src/ux/safe-dom.js');
+
+// A payload shaped like GET /_xerj-console/api/v1/knowledge (pinned
+// server-side by xerj-console-api/tests/knowledge_surface.rs — the same
+// fixture facts, so the two suites cannot drift).
+const PAYLOAD = () => ({ data: {
+ catalog: true,
+ totals: { datasets: 2, records: 105, files: 18, bytes: 3_594_132, docs: 4, relations: 2 },
+ datasets: [
+ {
+ index: 'ax-mail', slug: 'mail', formats: ['eml'], records: 91, junk: 2, files: 14,
+ bytes: 482_133, live_docs: 3, store_bytes: 190_000,
+ time_field: 'email_date', time_min: '2026-01-05T00:00:00.000Z', time_max: '2026-09-19T00:00:00.000Z',
+ semantic_field: 'body',
+ fields: [
+ { name: 'email_from', type: 'keyword', semantic: false, cardinality: 12, cardinality_overflow: false, null_ratio: 0.0, coverage: 1.0, examples: ['[email protected]', '[email protected]'] },
+ { name: 'body', type: 'semantic_text', semantic: true, cardinality: 91, cardinality_overflow: false, null_ratio: 0.0, coverage: 1.0, examples: ['term sheet attached'] },
+ { name: 'page', type: 'long', semantic: false, cardinality: 4, cardinality_overflow: false, null_ratio: 0.75, coverage: 0.25, examples: ['1', '2'] },
+ ],
+ sample_queries: ['{"query":{"match":{"body":"term sheet"}},"size":3}'],
+ notes: [], run_id: 'run-1',
+ },
+ { index: 'ax-pdfs', slug: 'pdfs', formats: ['pdf'], records: 14, junk: 0, files: 4, bytes: 3_111_999, live_docs: 1, store_bytes: 88_000, semantic_field: 'text', fields: [], sample_queries: [], notes: [], run_id: 'run-1' },
+ ],
+ others: [{ index: 'weblogs', docs: 1, store_bytes: 4_096 }],
+ relations: [
+ { kind: 'key_overlap', a_dataset: 'mail', a_index: 'ax-mail', a_field: 'email_from', b_dataset: 'pdfs', b_index: 'ax-pdfs', b_field: 'title', overlap: 7, containment: 0.58, grade: 'likely', confirmed_values: 7, tested_values: 12, examples: ['[email protected]'] },
+ { kind: 'time_alignment', a_index: 'ax-mail', a_field: 'email_date', b_index: 'ax-pdfs', b_field: 'title', range_overlap: 0.62, shared_buckets: 31, pearson_r: 0.71, activity_correlated: true },
+ ],
+ brains: [{ name: 'casefile', nodes_index: 'ax-mail', links: 2 }],
+ capabilities: [
+ { id: 'search', title: 'Search it', blurb: 'Seven query types.', href: '#/discover', kind: 'console' },
+ { id: 'read', title: 'Read the documents', blurb: 'Page through records.', href: '#/reader', kind: 'console' },
+ { id: 'graph', title: 'See the links', blurb: "Brain 'casefile' holds 2 links.", href: '#/dashboards/second-brain?brain=casefile', kind: 'console' },
+ { id: 'map', title: 'Print the data map', blurb: 'Markdown for agents.', command: 'xerj autoindex map', kind: 'cli' },
+ ],
+} });
+
+test('parseKnowledge: the payload → the corpus state, every gate answered', () => {
+ const st = parseKnowledge(PAYLOAD());
+ assert.equal(st.status, 'ok');
+ // gate 1 — size
+ assert.equal(st.totals.records, 105);
+ assert.equal(st.totals.bytes, 3_594_132);
+ assert.equal(st.totals.datasets, 2);
+ assert.equal(st.totals.catalog, true);
+ // gate 2 — data: datasets in card shape, largest first, with the LIVE counts
+ assert.equal(st.datasets[0].index, 'ax-mail');
+ assert.equal(st.datasets[0].liveDocs, 3);
+ assert.equal(st.datasets[0].storeBytes, 190_000);
+ assert.equal(st.datasets[0].fields[2].nullRatio, 0.75);
+ assert.deepEqual(st.summaries[0], { index: 'weblogs', records: 1, storeBytes: 4096, emails: 0, attachments: 0, formats: [] });
+ // gate 2b — relations, in display shape
+ assert.equal(st.relations[0].kind, 'key_overlap');
+ assert.equal(st.relations[0].confirmed, 7);
+ assert.equal(st.relations[1].kind, 'time_alignment');
+ assert.equal(st.relations[1].pearsonR, 0.71);
+ // gate 3 — capabilities + brains
+ assert.equal(st.capabilities.length, 4);
+ assert.equal(st.brains[0].links, 2);
+ // a malformed payload degrades to empty, never throws
+ const bad = parseKnowledge({ data: null });
+ assert.equal(bad.status, 'ok');
+ assert.deepEqual(bad.datasets, []);
+});
+
+test('a card shows the field facts the catalog measured — as text, not a hover hint', () => {
+ const st = parseKnowledge(PAYLOAD());
+ const card = renderCorpusCard(st.datasets[0], {});
+ const text = textOf(card);
+ // the example value is VISIBLE (it lived only in a title attribute before)
+ assert.match(text, /sam@acme\.example/);
+ // coverage and null% are the catalog's own numbers
+ assert.match(text, /75% null/);
+ assert.match(text, /25%/); // page coverage
+ assert.match(text, /12 distinct/); // email_from cardinality
+ // the LIVE count is the headline number, not the run's stale one
+ assert.match(text, /3 records/);
+ assert.doesNotMatch(text, /91 records/);
+});
+
+test('a dataset with more than eight fields folds the rest into an ALL FIELDS disclosure — nothing is capped away', () => {
+ const st = parseKnowledge(PAYLOAD());
+ const many = { ...st.datasets[0], fields: Array.from({ length: 11 }, (_, i) => ({ name: `f${i}`, type: 'keyword', semantic: false, coverage: 1, cardinality: null, nullRatio: null, examples: [] })) };
+ const card = renderCorpusCard(many, {});
+ const details = findAll(card, (n) => n.tag === 'details');
+ assert.equal(details.length, 1);
+ assert.match(textOf(details[0]), /ALL 11 FIELDS/);
+ // every field name is reachable in the payload the card renders
+ assert.match(textOf(card), /f10/);
+});
+
+test('renderRelations: what autoindex inferred — both kinds, and an honest none', () => {
+ const st = parseKnowledge(PAYLOAD());
+ const rows = renderRelations(st);
+ const text = textOf(rows);
+ assert.match(text, /ax-mail\.email_from\s+⟷\s+ax-pdfs\.title/);
+ assert.match(text, /7 shared values/);
+ assert.match(text, /likely/);
+ assert.match(text, /7\/12 confirmed by query/);
+ assert.match(text, /e\.g\. sam@acme\.example/);
+ assert.match(text, /ranges overlap 62%/);
+ assert.match(text, /activity r=0\.71 · correlated/);
+ // none inferred is stated, not papered over
+ assert.match(textOf(renderRelations({ relations: [] })), /No cross-dataset relations were inferred/);
+});
+
+test('renderCapabilities: every entry names its real surface; hrefs are in-app routes', () => {
+ const st = parseKnowledge(PAYLOAD());
+ const strip = renderCapabilities(st);
+ const cards = findAll(strip, (n) => (n.attrs.class || '').split(' ').includes('cp-cap'));
+ assert.equal(cards.length, 4);
+ const text = textOf(strip);
+ assert.match(text, /Search it/);
+ assert.match(text, /xerj autoindex map/); // the CLI command is shown verbatim
+ for (const c of cards) {
+ const a = findAll(c, (n) => n.tag === 'a')[0];
+ if (a) assert.match(a.attrs.href, /^#\//, 'a capability link is an in-app hash route');
+ }
+ // nothing to show → nothing claimed
+ assert.equal(renderCapabilities({ capabilities: [] }), null);
+});
+
+test('the CORPUS scene answers "how large" in its meta line and adds the two panels', () => {
+ const st = parseKnowledge(PAYLOAD());
+ const view = corpus.render({ data: st });
+ assert.ok(view.meta.some((m) => /105 RECORDS/.test(m)), view.meta.join(' | '));
+ assert.ok(view.meta.some((m) => /3\.6 MB|3\.4 MB/.test(m)), view.meta.join(' | '));
+ assert.deepEqual(view.panels.map((p) => p.id), ['datasets', 'relations', 'capabilities']);
+ // the legacy path (no totals) keeps the one panel it always had
+ const legacy = corpus.render({ data: { status: 'ok', datasets: st.datasets, summaries: [], totals: null, relations: [], capabilities: [] } });
+ assert.deepEqual(legacy.panels.map((p) => p.id), ['datasets']);
+ assert.ok(legacy.meta.some((m) => /105 RECORDS/.test(m)), `the cards' own records sum: ${legacy.meta.join(' | ')}`);
+});
+
+test('liveCorpus reads ONE endpoint and keeps the never-mock contract', async () => {
+ const { query, NEVER_MOCK } = await import('../src/data/query.js');
+ assert.ok(NEVER_MOCK.has('corpus'));
+ calls.length = 0;
+ respond = (url) => (url.endsWith('/api/v1/knowledge') ? json(200, PAYLOAD()) : json(404, {}));
+ const r = await query({ dashId: 'corpus' });
+ assert.equal(calls.length, 1, 'exactly one request: the knowledge surface');
+ assert.ok(calls[0].endsWith('/_xerj-console/api/v1/knowledge'));
+ assert.equal(r.data.datasets.length, 2);
+ assert.equal(r.data.relations.length, 2);
+ assert.equal(r.data.capabilities.length, 4);
+ // engine unreachable → an error and empty lists, never a sample
+ calls.length = 0;
+ respond = () => { throw new TypeError('Failed to fetch'); };
+ const err = await query({ dashId: 'corpus' });
+ assert.equal(err.meta.sourceKind, 'live-error');
+ assert.equal(err.data.status, 'error');
+ assert.deepEqual(err.data.datasets, []);
+ assert.deepEqual(err.data.relations, []);
+});