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.

merge: origin/main into second-brain

xerj-org1a54d7068653
diff --git a/docs/design/SECOND_BRAIN_SPEC.md b/docs/design/SECOND_BRAIN_SPEC.md
index 61a6deb89..7cb6cd2a7 100644
--- a/docs/design/SECOND_BRAIN_SPEC.md
+++ b/docs/design/SECOND_BRAIN_SPEC.md
@@ -964,22 +964,34 @@ export const secondBrain = {
name: 'Second Brain',
render: ({ data, time }) => ({
title: 'SECOND BRAIN',
- kicker: 'GRAPH MEMORY · EVIDENCE · TIME TRAVEL',
+ kicker: 'WHAT YOUR NOTES BELIEVE · EVERY LINK HAS A QUOTE · REPLAYABLE AT ANY MOMENT',
meta: [time, 'XERJ-GRAPH'],
panels: [
- { id: 'edgesLive', eyebrow: 'LIVE EDGES', cols: 3, type: 'metric', /* Num */ },
- { id: 'edgesTotal', eyebrow: 'TOTAL ASSERTED', cols: 3, type: 'metric', /* Num */ },
- { id: 'invalidated', eyebrow: 'INVALIDATED (KEPT)',cols: 3, type: 'metric', /* Num */ },
- { id: 'detectors', eyebrow: 'DETECTORS', cols: 3, type: 'metric', /* Num */ },
- { id: 'typeDist', eyebrow: 'EDGE TYPES', cols: 6, type: 'dist', /* Dist */ },
- { id: 'edgeTimeline', eyebrow: 'EDGES OVER TIME', cols: 6, type: 'series', /* Series */ },
- { id: 'ego', eyebrow: 'EGO · 1 HOP FROM SELECTED NODE', cols: 12, type: 'ego' },
- { id: 'hubs', eyebrow: 'HUBS · IN / OUT', cols: 6, type: 'topn', /* TopN */ },
+ { id: 'edgesLive', eyebrow: 'BELIEVED AT THIS MOMENT', cols: 3, type: 'metric' },
+ { id: 'edgesTotal', eyebrow: 'EVER ASSERTED', cols: 3, type: 'metric' },
+ { id: 'invalidated', eyebrow: 'RETIRED · KEPT FOR REPLAY', cols: 3, type: 'metric' },
+ { id: 'detectors', eyebrow: 'WHAT TAUGHT THIS BRAIN', cols: 3, type: 'metric' },
+ { id: 'typeDist', eyebrow: 'HOW NOTES CONNECT', cols: 6, type: 'dist', /* Dist */ },
+ { id: 'edgeTimeline', eyebrow: 'NEW LINKS PER DAY', cols: 6, type: 'series', /* Series */ },
+ { id: 'ego', eyebrow: 'THE LEDGER · ONE NOTE, EVERYTHING IT TOUCHES', cols: 12, type: 'ego' },
+ { id: 'hubs', eyebrow: 'CENTERS OF GRAVITY', cols: 6, type: 'topn' },
{ id: 'notShown', eyebrow: 'WHAT THIS VIEW DID NOT SHOW', cols: 6, type: 'honesty' },
],
}),
};
```
+
+Integrator edit (UX review, 2026-07-28): the ids/kinds/cols above are
+UNCHANGED from v1; only the human-visible titles moved to user words.
+LANGUAGE RULE (binding for every console surface of this feature): panel
+titles and labels say "link / believed since / retired / what taught
+this" — schema vocabulary (`edge`, `src`/`dst`, `valid_at`, `as_of`,
+`edge_id`) may appear only inside the evidence paper-trail (the raw
+developer view) and in API documentation. The four metric panels carry a
+visual value story, not bare counters: believed-vs-retired composition
+(the ONE two-series comparison — `--z-accent` vs the validated `--z-cmp`
+token, both segments directly labelled), cumulative growth spark,
+retired share, and per-detector count rows.
Import surface identical to vector-index.js (`Num` from `../ux/text.js`,
`Dist`/`Series` from `../ux/charts.js`, `TopN` from `../ux/layout.js`). Two
new panel renderers are UX-stream-owned: `ego` (node-link view of the §4.3
@@ -1011,9 +1023,9 @@ data = {
overview: /* EXACTLY the §4.4 response body */,
ego: /* EXACTLY the §4.3 response body for the currently selected node */,
metrics: { // derived by the data layer from `overview`, pre-formatted
- edgesLive: { formatted: '8', hint: 'visible at as-of' },
- edgesTotal: { formatted: '8', hint: 'incl. invalidated' },
- invalidated: { formatted: '0', hint: 'soft-deleted, kept for time travel' },
+ edgesLive: { formatted: '8', hint: 'held true right now' }, // as-of-aware: 'held true at <ts> UTC' when scrubbed
+ edgesTotal: { formatted: '8', hint: 'nothing is ever deleted' },
+ invalidated: { formatted: '0', hint: 'drag belief time left to revisit' },
detectors: { formatted: '2', hint: 'deterministic, versioned' },
},
series: { created: overview.created_over_time.map(b => b.count) },
@@ -1034,14 +1046,14 @@ DashboardSpec {
section: Some("dashboards"),
group: Some("ai"),
panels: vec![
- p("edgesLive", "metric", "LIVE EDGES", 3),
- p("edgesTotal", "metric", "TOTAL ASSERTED", 3),
- p("invalidated", "metric", "INVALIDATED (KEPT)", 3),
- p("detectors", "metric", "DETECTORS", 3),
- p("typeDist", "dist", "EDGE TYPES", 6),
- p("edgeTimeline", "series", "EDGES OVER TIME", 6),
- p("ego", "ego", "EGO · 1 HOP FROM SELECTED NODE", 12),
- p("hubs", "topn", "HUBS · IN / OUT", 6),
+ p("edgesLive", "metric", "BELIEVED AT THIS MOMENT", 3),
+ p("edgesTotal", "metric", "EVER ASSERTED", 3),
+ p("invalidated", "metric", "RETIRED · KEPT FOR REPLAY", 3),
+ p("detectors", "metric", "WHAT TAUGHT THIS BRAIN", 3),
+ p("typeDist", "dist", "HOW NOTES CONNECT", 6),
+ p("edgeTimeline", "series", "NEW LINKS PER DAY", 6),
+ p("ego", "ego", "THE LEDGER · ONE NOTE, EVERYTHING IT TOUCHES", 12),
+ p("hubs", "topn", "CENTERS OF GRAVITY", 6),
p("notShown", "honesty", "WHAT THIS VIEW DID NOT SHOW", 6),
],
},
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index f90b9c03e..41795af5d 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -81,6 +81,21 @@ impl Es {
Ok(resp.json().unwrap_or(Value::Null))
}
+ /// GET an arbitrary path and return only the HTTP status code.
+ ///
+ /// One attempt, no retry/backoff: `xerj brain` uses this to probe
+ /// whether a server is listening (`/health/ready`, auth-exempt) and
+ /// whether its credentials are accepted (`/`), and a liveness probe
+ /// that silently retried for ~16s would misreport "already running"
+ /// as "boot took 16s". A transport error means nothing answered.
+ pub fn get_status(&self, path: &str) -> Result<u16> {
+ let resp = self
+ .req(reqwest::Method::GET, path)
+ .send()
+ .with_context(|| format!("no response from {}{}", self.base, path))?;
+ Ok(resp.status().as_u16())
+ }
+
/// Retry wrapper: 429/5xx/transport → backoff 250ms..8s, 6 attempts.
fn with_retry<T>(
&self,
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 91831ffd9..b31d36752 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -413,7 +413,37 @@ fn alias_keys_to_reindex(
changed
}
+/// Default second-brain name for a corpus root: `sanitize_slug(basename)`
+/// (SECOND_BRAIN_SPEC §6.1), falling back to `"brain"` when the basename
+/// sanitizes to nothing (e.g. `/`). Public because `xerj brain` must know
+/// the SAME name this pipeline will use — the console URL it prints and
+/// opens embeds it — and two copies of this rule would drift.
+pub fn derive_brain_name(root: &Path) -> String {
+ let base = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
+ let name = base
+ .file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_default();
+ let slug = dataset::sanitize_slug(&name);
+ if slug.is_empty() {
+ "brain".into()
+ } else {
+ slug
+ }
+}
+
fn run_index(cfg: IndexCfg) -> Result<i32> {
+ run_index_report(cfg).map(|(code, _)| code)
+}
+
+/// `run_index` plus the machine-readable run summary — the same JSON the
+/// run writes to the catalog as `run:{run_id}` (datasets, `records_total`
+/// as *live* per-dataset counts, `graph.edges_written` etc.). `xerj brain`
+/// composes autoindex through this so it can be honest about what actually
+/// got indexed without re-querying or parsing stdout. The summary is
+/// `None` when the run ended before a plan produced one (empty folder,
+/// `--dry-run`).
+pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {
extract::pdf::configure_workers(cfg.pdf_workers);
extract::pdf::configure_timeout(cfg.pdf_timeout_secs);
use rayon::prelude::*;
@@ -430,7 +460,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
let discovered_files = walk::walk(&cfg.root, cfg.follow_symlinks)?;
if discovered_files.is_empty() {
println!("no files found under {}", cfg.root.display());
- return Ok(0);
+ return Ok((0, None));
}
let root_str = cfg
.root
@@ -724,7 +754,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
if cfg.dry_run {
println!("{}", serde_json::to_string_pretty(&plan)?);
eprintln!("(dry run — nothing indexed)");
- return Ok(0);
+ return Ok((0, None));
}
// ── create indices with explicit mappings ────────────────────────────
@@ -878,19 +908,7 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
} else {
let brain = match &cfg.brain {
Some(b) => b.clone(),
- None => {
- let base = cfg.root.canonicalize().unwrap_or_else(|_| cfg.root.clone());
- let name = base
- .file_name()
- .map(|s| s.to_string_lossy().to_string())
- .unwrap_or_default();
- let slug = dataset::sanitize_slug(&name);
- if slug.is_empty() {
- "brain".into()
- } else {
- slug
- }
- }
+ None => derive_brain_name(&cfg.root),
};
if let Err(reason) = detect::validate_brain(&brain) {
anyhow::bail!(
@@ -1791,11 +1809,12 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
cfg.url, cfg.prefix
);
}
- Ok(if junk_total_records > 0 || !all_junk.is_empty() {
+ let code = if junk_total_records > 0 || !all_junk.is_empty() {
3
} else {
0
- })
+ };
+ Ok((code, Some(run_doc)))
}
fn format_str(sn: Option<&Sniffed>) -> String {
diff --git a/engine/crates/xerj-console-api/src/seed.rs b/engine/crates/xerj-console-api/src/seed.rs
index a892dd935..8b0a08fde 100644
--- a/engine/crates/xerj-console-api/src/seed.rs
+++ b/engine/crates/xerj-console-api/src/seed.rs
@@ -284,15 +284,18 @@ fn seed_specs() -> Vec<DashboardSpec> {
name: "Second Brain",
section: Some("dashboards"),
group: Some("ai"),
+ // Titles mirror the SPA eyebrows 1:1 (§7.1) — user words
+ // only: "link / believed / retired / taught", never schema
+ // vocabulary (edge, src/dst, as-of) in a panel title.
panels: vec![
- p("edgesLive", "metric", "LIVE EDGES", 3),
- p("edgesTotal", "metric", "TOTAL ASSERTED", 3),
- p("invalidated", "metric", "INVALIDATED (KEPT)", 3),
- p("detectors", "metric", "DETECTORS", 3),
- p("typeDist", "dist", "EDGE TYPES", 6),
- p("edgeTimeline", "series", "EDGES OVER TIME", 6),
- p("ego", "ego", "EGO · 1 HOP FROM SELECTED NODE", 12),
- p("hubs", "topn", "HUBS · IN / OUT", 6),
+ p("edgesLive", "metric", "BELIEVED AT THIS MOMENT", 3),
+ p("edgesTotal", "metric", "EVER ASSERTED", 3),
+ p("invalidated", "metric", "RETIRED · KEPT FOR REPLAY", 3),
+ p("detectors", "metric", "WHAT TAUGHT THIS BRAIN", 3),
+ p("typeDist", "dist", "HOW NOTES CONNECT", 6),
+ p("edgeTimeline", "series", "NEW LINKS PER DAY", 6),
+ p("ego", "ego", "THE LEDGER · ONE NOTE, EVERYTHING IT TOUCHES", 12),
+ p("hubs", "topn", "CENTERS OF GRAVITY", 6),
p("notShown", "honesty", "WHAT THIS VIEW DID NOT SHOW", 6),
],
},
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
new file mode 100644
index 000000000..2d29c6bd5
--- /dev/null
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -0,0 +1,633 @@
+//! `xerj brain <folder>` — one command from a folder to a running, browsable
+//! second brain: boot (or attach to) the local server, run the autoindex
+//! pipeline with relationship detection on, then open the console's
+//! second-brain view — with the server's own one-time passkey-setup link on
+//! a first launch.
+//!
+//! Composition, not reimplementation:
+//! - indexing + link detection = `xerj_autoindex::run_index_report` — the
+//! exact `xerj autoindex` pipeline, graph detectors on (its default;
+//! SECOND_BRAIN_SPEC §6). Re-runs converge because detector edges take
+//! `valid_at` from source mtimes, so unchanged files re-emit identical
+//! `edge_id`s and bulk `index` overwrites in place.
+//! - console auth = the server's own first-launch bootstrap
+//! (`xerj-console-api::bootstrap`), which mints a single-use 30-minute
+//! setup link and prints it in the startup banner. This command only
+//! *relays* that link from the freshly-booted server's log — it never
+//! mints credentials or invents an auth path of its own.
+//! - the server is the ordinary `xerj` binary (`current_exe()`), spawned
+//! detached (own process group, output to `<data-dir>/server.log`) so
+//! the brain outlives this command.
+
+use anyhow::{bail, Context, Result};
+use serde_json::{json, Value};
+use std::io::Write as _;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use xerj_autoindex::cli::IndexCfg;
+use xerj_autoindex::esclient::Es;
+use xerj_autoindex::{detect, walk};
+
+/// How long a freshly-spawned server gets to answer `/health/ready`.
+/// Fresh data dirs are ready in ~1s; a large existing dir replays WAL first.
+const BOOT_TIMEOUT: Duration = Duration::from_secs(120);
+const BOOT_POLL: Duration = Duration::from_millis(150);
+
+pub fn run_cli() -> i32 {
+ let args: Vec<String> = std::env::args().skip(2).collect();
+ let cfg = match parse(args) {
+ Ok(Some(cfg)) => cfg,
+ Ok(None) => {
+ print_help();
+ return 0;
+ }
+ Err(e) => {
+ eprintln!("error: {e}\n");
+ print_help();
+ return 2;
+ }
+ };
+ match run(cfg) {
+ Ok(code) => code,
+ Err(e) => {
+ eprintln!("error: {e:#}");
+ 1
+ }
+ }
+}
+
+pub fn print_help() {
+ println!(
+ "xerj brain — turn a folder into a running, browsable second brain, in one command\n\
+ \n\
+ Point it at a folder. xerj starts its local server (or attaches to a running\n\
+ one), indexes every readable file, detects the links between them (wikilinks,\n\
+ relative links, section order, shared folders), and opens your knowledge in\n\
+ the browser. Safe to re-run any time — re-runs converge, nothing duplicates.\n\
+ \n\
+ USAGE:\n\
+ xerj brain <folder> [OPTIONS]\n\
+ \n\
+ OPTIONS:\n\
+ --brain <NAME> brain name (default: the folder's name; part of the URL)\n\
+ --url <U> server to use (default http://localhost:9200); a server\n\
+ is booted only for a localhost URL nothing listens on\n\
+ --data-dir <PATH> where a newly-booted server keeps its data and log\n\
+ (default ~/.xerj/brain)\n\
+ --api-key <K> API key for an already-running secured server\n\
+ (or env XERJ_API_KEY; a server booted by this command\n\
+ needs neither — its key is read from <data-dir>/admin.key)\n\
+ --fresh ignore the resume journal, re-walk everything\n\
+ (ids stay idempotent; converges to the same brain)\n\
+ --no-open print the links but do not open a browser\n\
+ --help, -h this help\n\
+ \n\
+ EXIT CODES: 0 ready; 3 ready-with-junk (unreadable files recorded, never\n\
+ fatal); 1 nothing indexable / server failure; 2 usage\n"
+ );
+}
+
+pub struct BrainCfg {
+ pub root: PathBuf,
+ pub brain: Option<String>,
+ pub url: String,
+ pub data_dir: Option<PathBuf>,
+ pub api_key: Option<String>,
+ pub fresh: bool,
+ pub no_open: bool,
+}
+
+fn parse(args: Vec<String>) -> Result<Option<BrainCfg>, String> {
+ let mut it = args.into_iter();
+ let mut root: Option<PathBuf> = None;
+ let mut brain: Option<String> = None;
+ let mut url = "http://localhost:9200".to_string();
+ let mut data_dir: Option<PathBuf> = None;
+ let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());
+ let mut fresh = false;
+ let mut no_open = false;
+
+ while let Some(arg) = it.next() {
+ match arg.as_str() {
+ "--brain" => {
+ let name = it.next().ok_or("--brain needs a value")?;
+ detect::validate_brain(&name)
+ .map_err(|reason| format!("--brain {name}: {reason}"))?;
+ brain = Some(name);
+ }
+ "--url" => url = it.next().ok_or("--url needs a value")?,
+ "--data-dir" => {
+ data_dir = Some(PathBuf::from(it.next().ok_or("--data-dir needs a value")?))
+ }
+ "--api-key" => api_key = it.next(),
+ "--fresh" => fresh = true,
+ "--no-open" => no_open = true,
+ "--help" | "-h" => return Ok(None),
+ other if !other.starts_with('-') && root.is_none() => root = Some(PathBuf::from(other)),
+ other => return Err(format!("unknown argument: {other}")),
+ }
+ }
+
+ let Some(root) = root else {
+ return Ok(None); // no folder → help, like `xerj autoindex`
+ };
+ Ok(Some(BrainCfg {
+ root,
+ brain,
+ url: url.trim_end_matches('/').to_string(),
+ data_dir,
+ api_key,
+ fresh,
+ no_open,
+ }))
+}
+
+fn default_data_dir() -> PathBuf {
+ let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
+ Path::new(&home).join(".xerj").join("brain")
+}
+
+/// (host, port) out of an `http://host[:port]` URL. Only plain-http local
+/// URLs are boot candidates; anything else is attach-only.
+fn parse_http_url(url: &str) -> Result<(String, u16)> {
+ let rest = url
+ .strip_prefix("http://")
+ .with_context(|| format!("--url must start with http:// (got {url}); https servers can only be attached to, and need the full URL"))?;
+ let hostport = rest.split('/').next().unwrap_or(rest);
+ if let Some((host, port)) = hostport.rsplit_once(':') {
+ let port: u16 = port
+ .parse()
+ .with_context(|| format!("invalid port in --url {url}"))?;
+ Ok((host.to_string(), port))
+ } else {
+ Ok((hostport.to_string(), 9200))
+ }
+}
+
+fn is_local_host(host: &str) -> bool {
+ matches!(host, "localhost" | "127.0.0.1" | "[::1]" | "::1")
+}
+
+fn run(cfg: BrainCfg) -> Result<i32> {
+ let t0 = Instant::now();
+
+ // ── the folder first: no server side effects for an empty ask ────────
+ if !cfg.root.exists() {
+ bail!("{} does not exist", cfg.root.display());
+ }
+ let files = walk::walk(&cfg.root, false)?;
+ if files.is_empty() {
+ eprintln!(
+ "xerj brain: no files under {} — nothing to build a brain from.\n\
+ point it at a folder with notes or documents in it (markdown, text,\n\
+ html, pdf, docx, csv, json …), e.g. `xerj brain ~/notes`.",
+ cfg.root.display()
+ );
+ return Ok(1);
+ }
+ let total_mb = files.iter().map(|f| f.size).sum::<u64>() >> 20;
+ let brain = match &cfg.brain {
+ Some(b) => b.clone(),
+ None => {
+ let derived = xerj_autoindex::derive_brain_name(&cfg.root);
+ detect::validate_brain(&derived).map_err(|reason| {
+ anyhow::anyhow!(
+ "folder name '{derived}' is not usable as a brain name ({reason}) — \
+ pass one with --brain <name>"
+ )
+ })?;
+ derived
+ }
+ };
+ eprintln!(
+ "brain '{brain}': {} files ({total_mb} MB) under {}",
+ files.len(),
+ cfg.root.display()
+ );
+
+ // ── server: attach if something answers, boot if nothing does ────────
+ let (host, port) = parse_http_url(&cfg.url)?;
+ let data_dir = cfg.data_dir.clone().unwrap_or_else(default_data_dir);
+ let probe = Es::new(&cfg.url, None)?;
+ let mut setup_link: Option<String> = None;
+ match probe.get_status("/health/ready") {
+ Ok(200) => {
+ eprintln!("attached to the running xerj server at {}", cfg.url);
+ }
+ Ok(status) => bail!(
+ "something is listening at {} but it does not look like xerj \
+ (GET /health/ready → HTTP {status}). Stop it, or point --url at your xerj server",
+ cfg.url
+ ),
+ Err(_) => {
+ if !is_local_host(&host) {
+ bail!(
+ "no server answers at {} and this command only boots servers on \
+ localhost — start xerj on that host, then re-run",
+ cfg.url
+ );
+ }
+ let booted = boot_server(&data_dir, port)?;
+ eprintln!(
+ "booted xerj server (pid {}) — data: {}, log: {}",
+ booted.pid,
+ data_dir.display(),
+ booted.log_path.display()
+ );
+ wait_ready(&probe, &booted)?;
+ // First launch on an empty data dir: the server's bootstrap
+ // banner (xerj-console-api::bootstrap) carries the single-use
+ // passkey-setup link. Relay it. Absent on an already-enrolled
+ // data dir — then the console's normal passkey login applies.
+ setup_link = find_setup_link(&booted.log_path);
+ }
+ }
+
+ // ── credentials: the server's own admin key, never a new auth path ───
+ let api_key = cfg.api_key.clone().or_else(|| {
+ let path = data_dir.join("admin.key");
+ std::fs::read_to_string(path)
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ });
+ let es = Es::new(&cfg.url, api_key.clone())?;
+ match es.get_status("/") {
+ Ok(200) => {}
+ Ok(401) | Ok(403) => bail!(
+ "the server at {} rejected our credentials. Pass --api-key <key> (or set \
+ XERJ_API_KEY); for a server this command booted, the key lives at {}",
+ cfg.url,
+ data_dir.join("admin.key").display()
+ ),
+ Ok(status) => bail!("unexpected HTTP {status} from GET {}/", cfg.url),
+ Err(e) => return Err(e.context(format!("server at {} stopped answering", cfg.url))),
+ }
+
+ // ── index: the autoindex pipeline, graph detection on ────────────────
+ let (code, run_doc) = xerj_autoindex::run_index_report(index_cfg(&cfg, &brain, api_key))?;
+
+ let records_total = run_doc
+ .as_ref()
+ .and_then(|d| d.get("records_total"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0);
+ if records_total == 0 {
+ eprintln!(
+ "\nxerj brain: nothing indexable under {} — {} files seen, 0 records live.\n\
+ autoindex reads text, markdown, html, pdf, docx, csv, json/ndjson, xml,\n\
+ yaml, logs and sql dumps; unreadable files are junk-filed, never guessed.\n\
+ point it at the folder where your notes actually live.",
+ cfg.root.display(),
+ files.len()
+ );
+ return Ok(1);
+ }
+
+ // Live edge count straight from the edges index (same probe as
+ // `autoindex map`): honest across resumed re-runs, where per-run
+ // counters would read 0 on an already-converged corpus.
+ let edges_index = detect::edges_index_name(&brain);
+ let live_edges = es
+ .search(
+ &edges_index,
+ &json!({
+ "size": 0,
+ "track_total_hits": true,
+ "query": {"bool": {
+ "filter": [{"exists": {"field": "src"}}],
+ "must_not": [{"exists": {"field": "invalid_at"}}]
+ }}
+ }),
+ )
+ .ok()
+ .and_then(|v| v.pointer("/hits/total/value").and_then(Value::as_u64))
+ .unwrap_or(0);
+
+ let console_url = format!("{}/_xerj-console/#/second-brain?brain={brain}", cfg.url);
+ // `next` rides the setup link's fragment; the setup page redirects into
+ // this hash route after passkey enrollment. `brain` is a validated slug
+ // ([a-z0-9-]), so only the literal `?`/`=` need escaping.
+ let setup_link = setup_link.map(|l| format!("{l}&next=second-brain%3Fbrain%3D{brain}"));
+
+ if live_edges == 0 {
+ println!(
+ "\nyour second brain indexed, but no links were found — {} files, {} records, 0 links",
+ files.len(),
+ records_total
+ );
+ println!(
+ " notes connect through [[wikilinks]], relative markdown/html links, and\n\
+ \x20 shared folders (2+ files in one directory chain together); a single\n\
+ \x20 isolated file has nothing to link to. The console still shows your\n\
+ \x20 documents and will pick up links on the next run:"
+ );
+ println!(" → {console_url}");
+ if let Some(link) = &setup_link {
+ println!(" one-time passkey setup (open once, valid 30 min):");
+ println!(" → {link}");
+ }
+ return Ok(code);
+ }
+
+ println!(
+ "\n✓ your second brain is ready — {} files, {} links, {:.1}s",
+ files.len(),
+ live_edges,
+ t0.elapsed().as_secs_f64()
+ );
+ println!(" → {console_url}");
+ if let Some(link) = &setup_link {
+ println!(" one-time passkey setup (open once, valid 30 min):");
+ println!(" → {link}");
+ }
+ if cfg.no_open {
+ println!(" browser not opened (--no-open); use the links above.");
+ } else {
+ // Open the setup link when one was minted (first launch enrolls a
+ // passkey, then lands on the brain); otherwise the console itself.
+ let target = setup_link.as_deref().unwrap_or(&console_url);
+ match open_browser(target) {
+ Ok(()) => println!(" opening your browser…"),
+ Err(e) => println!(" could not open a browser ({e}); use the links above."),
+ }
+ }
+ Ok(code)
+}
+
+fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
+ let cores = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(8);
+ IndexCfg {
+ root: cfg.root.clone(),
+ url: cfg.url.clone(),
+ api_key,
+ workers: cores.min(8),
+ pdf_workers: cores.min(4),
+ pdf_timeout_secs: 120,
+ bulk_mb: 8,
+ bulk_timeout_secs: 300,
+ prefix: "ax".into(),
+ state_dir: None,
+ fresh: cfg.fresh,
+ follow_symlinks: false,
+ max_file_gb: 2,
+ sample: 500,
+ no_semantic: false,
+ brain: Some(brain.to_string()),
+ no_graph: false,
+ dry_run: false,
+ json: false,
+ quiet: false,
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Booting the server
+// ─────────────────────────────────────────────────────────────────────────────
+
+struct BootedServer {
+ pid: u32,
+ log_path: PathBuf,
+}
+
+/// Spawn `current_exe() --config <data-dir>/xerj-brain.toml` detached, with
+/// stdout+stderr appended to `<data-dir>/server.log`. The rest/grpc ports are
+/// pinned to `es_port+1`/`es_port+2` so a non-default `--url` port yields a
+/// fully non-colliding triple deterministically.
+fn boot_server(data_dir: &Path, es_port: u16) -> Result<BootedServer> {
+ if es_port > u16::MAX - 2 {
+ bail!("--url port {es_port} is too high — the booted server also needs ports +1 and +2");
+ }
+ std::fs::create_dir_all(data_dir)
+ .with_context(|| format!("create data dir {}", data_dir.display()))?;
+
+ let config_path = data_dir.join("xerj-brain.toml");
+ // serde_json string escaping is valid TOML basic-string escaping for the
+ // characters paths can contain (`\`, `"`, control chars → \uXXXX).
+ let dir_toml = serde_json::to_string(&data_dir.to_string_lossy())?;
+ std::fs::write(
+ &config_path,
+ format!(
+ "# written by `xerj brain` on every boot it performs — edit ports here\n\
+ # only if you also change the --url this command is given.\n\
+ [server]\n\
+ data_dir = {dir_toml}\n\
+ es_compat_port = {es_port}\n\
+ rest_port = {}\n\
+ grpc_port = {}\n",
+ es_port + 1,
+ es_port + 2,
+ ),
+ )
+ .with_context(|| format!("write {}", config_path.display()))?;
+
+ let log_path = data_dir.join("server.log");
+ let log = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&log_path)
+ .with_context(|| format!("open {}", log_path.display()))?;
+ let log_err = log.try_clone()?;
+
+ let exe = std::env::current_exe().context("locate the xerj binary")?;
+ let mut command = Command::new(exe);
+ command
+ .arg("--config")
+ .arg(&config_path)
+ .stdin(Stdio::null())
+ .stdout(Stdio::from(log))
+ .stderr(Stdio::from(log_err));
+ // Detach: its own process group, so the server outlives this command and
+ // never receives our Ctrl-C.
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ command.process_group(0);
+ }
+ let child = command.spawn().context("spawn the xerj server")?;
+ let pid = child.id();
+ // Best effort — the pid file is a convenience for `kill $(cat …)`.
+ let _ =
+ std::fs::File::create(data_dir.join("server.pid")).and_then(|mut f| writeln!(f, "{pid}"));
+ Ok(BootedServer { pid, log_path })
+}
+
+fn wait_ready(probe: &Es, booted: &BootedServer) -> Result<()> {
+ let deadline = Instant::now() + BOOT_TIMEOUT;
+ loop {
+ if matches!(probe.get_status("/health/ready"), Ok(200)) {
+ return Ok(());
+ }
+ if Instant::now() > deadline {
+ bail!(
+ "the booted server (pid {}) did not become ready within {}s — its log:\n{}",
+ booted.pid,
+ BOOT_TIMEOUT.as_secs(),
+ log_tail(&booted.log_path, 30)
+ );
+ }
+ // A dead child never becomes ready; surface its log immediately.
+ // (`try_wait` is unavailable here — the child is detached — so probe
+ // liveness via signal 0 on unix, and rely on the deadline elsewhere.)
+ #[cfg(unix)]
+ {
+ let alive = unsafe { libc::kill(booted.pid as libc::pid_t, 0) } == 0;
+ if !alive {
+ bail!(
+ "the booted server (pid {}) exited before becoming ready — its log:\n{}",
+ booted.pid,
+ log_tail(&booted.log_path, 30)
+ );
+ }
+ }
+ std::thread::sleep(BOOT_POLL);
+ }
+}
+
+fn log_tail(path: &Path, lines: usize) -> String {
+ match std::fs::read_to_string(path) {
+ Ok(text) => {
+ let all: Vec<&str> = text.lines().collect();
+ let start = all.len().saturating_sub(lines);
+ all[start..].join("\n")
+ }
+ Err(e) => format!("(log unreadable: {e})"),
+ }
+}
+
+/// Fish the first-launch passkey-setup link out of the freshly-booted
+/// server's log. The bordered banner wraps the URL in box-drawing chars and
+/// padding, but the URL itself never contains whitespace, so scan from the
+/// `http` before the marker to the first whitespace/border char after it.
+fn find_setup_link(log_path: &Path) -> Option<String> {
+ let text = std::fs::read_to_string(log_path).ok()?;
+ for line in text.lines().rev() {
+ let Some(marker) = line.find("/_xerj-console/setup#token=") else {
+ continue;
+ };
+ let Some(start) = line[..marker].rfind("http") else {
+ continue;
+ };
+ let tail = &line[start..];
+ let end = tail
+ .find(|c: char| c.is_whitespace() || c == '│')
+ .unwrap_or(tail.len());
+ return Some(tail[..end].to_string());
+ }
+ None
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Opening the browser
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Platform opener behind two env overrides. No new dependency: the command
+/// is spawned fire-and-forget (some openers block for the browser's whole
+/// lifetime, so waiting is wrong), and any spawn error is reported by the
+/// caller next to the always-printed URL — a headless/SSH user is never
+/// stranded.
+///
+/// `XERJ_BROWSER` (then `BROWSER`) names a command invoked with the URL as
+/// its single argument.
+fn open_browser(url: &str) -> Result<()> {
+ let mut command = if let Some(over) = std::env::var("XERJ_BROWSER")
+ .ok()
+ .or_else(|| std::env::var("BROWSER").ok())
+ .filter(|s| !s.trim().is_empty())
+ {
+ let mut c = Command::new(over);
+ c.arg(url);
+ c
+ } else if cfg!(target_os = "macos") {
+ let mut c = Command::new("open");
+ c.arg(url);
+ c
+ } else if cfg!(target_os = "windows") {
+ let mut c = Command::new("cmd");
+ // `start`'s first quoted arg is the window title — keep it empty so
+ // the URL is not eaten as a title.
+ c.args(["/C", "start", ""]).arg(url);
+ c
+ } else {
+ let mut c = Command::new("xdg-open");
+ c.arg(url);
+ c
+ };
+ command
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| anyhow::anyhow!("{e}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn url_parsing_defaults_port_and_rejects_https() {
+ assert_eq!(
+ parse_http_url("http://localhost:9200").unwrap(),
+ ("localhost".into(), 9200)
+ );
+ assert_eq!(
+ parse_http_url("http://localhost").unwrap(),
+ ("localhost".into(), 9200)
+ );
+ assert_eq!(
+ parse_http_url("http://10.0.0.7:9300").unwrap(),
+ ("10.0.0.7".into(), 9300)
+ );
+ assert!(parse_http_url("https://example.com:9200").is_err());
+ }
+
+ #[test]
+ fn parse_requires_folder_and_validates_brain() {
+ let strs = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+ assert!(parse(strs(&[])).unwrap().is_none(), "no folder → help");
+ assert!(parse(strs(&["--brain", "kb-edges", "notes"])).is_err());
+ let cfg = parse(strs(&["notes", "--no-open", "--brain", "kb"]))
+ .unwrap()
+ .unwrap();
+ assert!(cfg.no_open);
+ assert_eq!(cfg.brain.as_deref(), Some("kb"));
+ assert_eq!(cfg.url, "http://localhost:9200");
+ }
+
+ #[test]
+ fn setup_link_is_scraped_from_bordered_and_bare_banner_lines() {
+ let dir = std::env::temp_dir().join(format!("xerj-brain-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let log = dir.join("server.log");
+
+ std::fs::write(
+ &log,
+ "│ http://localhost:9200/_xerj-console/setup#token=AbC-_9 │\n",
+ )
+ .unwrap();
+ assert_eq!(
+ find_setup_link(&log).as_deref(),
+ Some("http://localhost:9200/_xerj-console/setup#token=AbC-_9")
+ );
+
+ std::fs::write(
+ &log,
+ "├────┤\n http://localhost:19200/_xerj-console/setup#token=zz\n├────┤\n",
+ )
+ .unwrap();
+ assert_eq!(
+ find_setup_link(&log).as_deref(),
+ Some("http://localhost:19200/_xerj-console/setup#token=zz")
+ );
+
+ std::fs::write(&log, "no banner here\n").unwrap();
+ assert_eq!(find_setup_link(&log), None);
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index e577e6132..831409bed 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -74,6 +74,7 @@ use xerj_common::{config::Config, metrics::Metrics};
use xerj_console_api::{state::ClusterMode, ConsoleState};
use xerj_engine::Engine;
+mod brain;
#[cfg(all(target_os = "linux", feature = "debug-profiling"))]
mod debug_profiling;
mod grpc;
@@ -201,6 +202,8 @@ fn print_help() {
xerj index <opts> direct NDJSON → engine ingest (see xerj index --help)\n\
xerj autoindex <folder> [opts] zero-config folder discovery + indexing (see xerj autoindex --help)\n\
xerj autoindex map print the discovered data map\n\
+ xerj brain <folder> one command: index a folder into a running, browsable\n\
+ second brain in your browser (see xerj brain --help)\n\
\n\
ENVIRONMENT:\n\
XERJ_LOG Log level filter (default: info)\n\
@@ -1291,6 +1294,16 @@ async fn async_main() -> Result<()> {
.unwrap_or(1);
std::process::exit(code);
}
+ if matches!(argv1.as_deref(), Some("brain")) {
+ // One command → running, browsable second brain: boots/attaches the
+ // server, reuses the autoindex pipeline with graph detection on,
+ // then opens the console. Fully synchronous internally — run it off
+ // the async runtime like `autoindex`.
+ let code = tokio::task::spawn_blocking(brain::run_cli)
+ .await
+ .unwrap_or(1);
+ std::process::exit(code);
+ }
// Start profiling before config loading, TLS, engine replay, and router
// construction so delay=0 is a genuine initialization profile.
diff --git a/engine/crates/xerj-server/tests/brain_cli.rs b/engine/crates/xerj-server/tests/brain_cli.rs
new file mode 100644
index 000000000..214ec9b7e
--- /dev/null
+++ b/engine/crates/xerj-server/tests/brain_cli.rs
@@ -0,0 +1,334 @@
+//! End-to-end tests for `xerj brain` — the one-command second brain.
+//!
+//! The heavy test drives the REAL binary against the contract's five-note
+//! fixture (SECOND_BRAIN_SPEC §8.1): run 1 must boot a detached server,
+//! index the folder, relay the first-launch passkey-setup link, and — with
+//! `--no-open` — never attempt to open a browser; run 2 must attach to the
+//! running server and converge to the byte-identical edge set; run 3 (no
+//! `--no-open`) must hand the console URL to the platform opener, observed
+//! via the `XERJ_BROWSER` override.
+
+#![cfg(unix)]
+
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::net::TcpListener;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+use std::time::{Duration, Instant};
+use xerj_autoindex::detect;
+use xerj_autoindex::esclient::Es;
+
+/// §8.1 — bodies are exact; offsets in §8.2 are byte offsets into them.
+fn write_fixture(dir: &Path) {
+ fs::write(
+ dir.join("alpha.md"),
+ "Alpha is the hub note. It links to [[beta]] and [[gamma]].",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("beta.md"),
+ "Beta continues the thread and references [[gamma]].",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("gamma.md"),
+ "Gamma is the sink note with no outgoing links.",
+ )
+ .unwrap();
+ fs::write(dir.join("delta.md"), "Delta cites [[alpha]] as its source.").unwrap();
+ fs::write(dir.join("epsilon.md"), "Epsilon stands alone.").unwrap();
+}
+
+/// A free (P, P+1, P+2) triple — the booted server needs es/rest/grpc.
+fn free_port_triple() -> u16 {
+ for _ in 0..64 {
+ let probe = TcpListener::bind(("127.0.0.1", 0)).unwrap();
+ let p = probe.local_addr().unwrap().port();
+ drop(probe);
+ if !(1025..=u16::MAX - 2).contains(&p) {
+ continue;
+ }
+ let all_free = (p..=p + 2).all(|q| TcpListener::bind(("127.0.0.1", q)).is_ok());
+ if all_free {
+ return p;
+ }
+ }
+ panic!("no free port triple found");
+}
+
+/// Fake platform opener: records the URL it was asked to open.
+fn write_fake_browser(script: &Path, marker: &Path) {
+ fs::write(
+ script,
+ format!("#!/bin/sh\nprintf '%s' \"$1\" > '{}'\n", marker.display()),
+ )
+ .unwrap();
+ use std::os::unix::fs::PermissionsExt;
+ let mut perm = fs::metadata(script).unwrap().permissions();
+ perm.set_mode(0o755);
+ fs::set_permissions(script, perm).unwrap();
+}
+
+/// Kills the detached server `xerj brain` booted, via its pid file.
+struct ServerGuard {
+ data_dir: PathBuf,
+}
+impl Drop for ServerGuard {
+ fn drop(&mut self) {
+ if let Ok(pid) = fs::read_to_string(self.data_dir.join("server.pid")) {
+ if let Ok(pid) = pid.trim().parse::<i32>() {
+ unsafe { libc::kill(pid, libc::SIGKILL) };
+ }
+ }
+ }
+}
+
+fn run_brain(args: &[&str], home: &Path, browser: &Path) -> Output {
+ Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .arg("brain")
+ .args(args)
+ // Isolate ~/.xerj (autoindex resume journal) into the test root.
+ .env("HOME", home)
+ .env("XERJ_BROWSER", browser)
+ .env_remove("BROWSER")
+ .env_remove("XERJ_API_KEY")
+ .output()
+ .unwrap()
+}
+
+const EDGES_INDEX: &str = ".xerj-memory-notes-edges";
+
+fn live_edges(es: &Es) -> Vec<Value> {
+ let resp = es
+ .search(
+ EDGES_INDEX,
+ &json!({
+ "size": 100,
+ "query": {"bool": {
+ "filter": [{"exists": {"field": "src"}}],
+ "must_not": [{"exists": {"field": "invalid_at"}}]
+ }}
+ }),
+ )
+ .expect("search edges index");
+ resp.pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default()
+}
+
+#[test]
+fn brain_end_to_end_five_note_fixture() {
+ let root = tempfile::tempdir().unwrap();
+ let notes = root.path().join("notes");
+ fs::create_dir(&notes).unwrap();
+ write_fixture(&notes);
+ let data_dir = root.path().join("data");
+ let marker = root.path().join("browser-marker");
+ let fake_browser = root.path().join("fake-browser.sh");
+ write_fake_browser(&fake_browser, &marker);
+ let port = free_port_triple();
+ let url = format!("http://localhost:{port}");
+ let _guard = ServerGuard {
+ data_dir: data_dir.clone(),
+ };
+
+ let notes_arg = notes.to_str().unwrap();
+ let data_arg = data_dir.to_str().unwrap();
+ let base_args = ["--url", &url, "--data-dir", data_arg];
+
+ // ── run 1: nothing listening → boot, index, relay setup link ─────────
+ let mut args1: Vec<&str> = vec![notes_arg, "--no-open"];
+ args1.extend_from_slice(&base_args);
+ let out1 = run_brain(&args1, root.path(), &fake_browser);
+ let stdout1 = String::from_utf8_lossy(&out1.stdout);
+ let stderr1 = String::from_utf8_lossy(&out1.stderr);
+ assert!(
+ out1.status.success(),
+ "run 1 failed (status {:?})\nstdout:\n{stdout1}\nstderr:\n{stderr1}",
+ out1.status
+ );
+ assert!(
+ stderr1.contains("booted xerj server"),
+ "run 1 must say it booted a server\nstderr:\n{stderr1}"
+ );
+ assert!(
+ stdout1.contains("your second brain is ready"),
+ "stdout:\n{stdout1}"
+ );
+ assert!(
+ stdout1.contains(&format!("{url}/_xerj-console/#/second-brain?brain=notes")),
+ "the console deep link must be printed\nstdout:\n{stdout1}"
+ );
+ assert!(
+ stdout1.contains("/_xerj-console/setup#token="),
+ "a fresh boot must relay the one-time passkey-setup link\nstdout:\n{stdout1}"
+ );
+ assert!(
+ stdout1.contains("browser not opened (--no-open)"),
+ "stdout:\n{stdout1}"
+ );
+ assert!(
+ !marker.exists(),
+ "--no-open must not attempt to open a browser"
+ );
+
+ // ── the brain index exists with the §8.3 edge set ────────────────────
+ let api_key = fs::read_to_string(data_dir.join("admin.key"))
+ .expect("booted server persists admin.key")
+ .trim()
+ .to_string();
+ let es = Es::new(&url, Some(api_key)).unwrap();
+
+ let meta = es
+ .get_doc(EDGES_INDEX, detect::BRAIN_META_ID)
+ .expect("read brain meta")
+ .expect("brain meta doc must exist");
+ assert_eq!(
+ meta["brain"],
+ json!("notes"),
+ "brain defaults to the folder name"
+ );
+
+ let edges1 = live_edges(&es);
+ assert_eq!(
+ edges1.len(),
+ 8,
+ "fixture yields 4 wikilink + 4 same_dir edges, got: {edges1:#?}"
+ );
+ let mut by_detector: BTreeMap<String, u64> = BTreeMap::new();
+ for e in &edges1 {
+ *by_detector
+ .entry(e["_source"]["detector"].as_str().unwrap().to_string())
+ .or_default() += 1;
+ }
+ assert_eq!(
+ by_detector,
+ BTreeMap::from([("wikilink@1".to_string(), 4), ("samedir@1".to_string(), 4)])
+ );
+ // §8.2 — wikilink evidence (source file, byte offset), exact.
+ let wikilinks: BTreeSet<(String, u64)> = edges1
+ .iter()
+ .filter(|e| e["_source"]["detector"] == json!("wikilink@1"))
+ .map(|e| {
+ (
+ e["_source"]["evidence"]["source"].as_str().unwrap().into(),
+ e["_source"]["evidence"]["offset"].as_u64().unwrap(),
+ )
+ })
+ .collect();
+ assert_eq!(
+ wikilinks,
+ BTreeSet::from([
+ ("alpha.md".to_string(), 35),
+ ("alpha.md".to_string(), 48),
+ ("beta.md".to_string(), 41),
+ ("delta.md".to_string(), 12),
+ ])
+ );
+ let ids1: BTreeSet<String> = edges1
+ .iter()
+ .map(|e| e["_id"].as_str().unwrap().to_string())
+ .collect();
+
+ // ── run 2: server already listening → attach; edge set converges ─────
+ let out2 = run_brain(&args1, root.path(), &fake_browser);
+ let stdout2 = String::from_utf8_lossy(&out2.stdout);
+ let stderr2 = String::from_utf8_lossy(&out2.stderr);
+ assert!(
+ out2.status.success(),
+ "run 2 failed\nstdout:\n{stdout2}\nstderr:\n{stderr2}"
+ );
+ assert!(
+ stderr2.contains("attached to the running xerj server"),
+ "run 2 must say it attached\nstderr:\n{stderr2}"
+ );
+ let edges2 = live_edges(&es);
+ let ids2: BTreeSet<String> = edges2
+ .iter()
+ .map(|e| e["_id"].as_str().unwrap().to_string())
+ .collect();
+ assert_eq!(
+ ids1, ids2,
+ "re-running on an unchanged folder must converge to identical edge_ids"
+ );
+ assert!(!marker.exists(), "--no-open again: still no browser");
+
+ // ── run 3: without --no-open, the opener gets the console URL ────────
+ let mut args3: Vec<&str> = vec![notes_arg];
+ args3.extend_from_slice(&base_args);
+ let out3 = run_brain(&args3, root.path(), &fake_browser);
+ let stdout3 = String::from_utf8_lossy(&out3.stdout);
+ assert!(out3.status.success(), "run 3 failed\nstdout:\n{stdout3}");
+ // The opener is spawned fire-and-forget; give it a moment.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !marker.exists() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ let opened = fs::read_to_string(&marker).expect("opener must have been invoked");
+ assert!(
+ opened.contains("/_xerj-console/") && opened.contains("second-brain?brain=notes"),
+ "opened URL must land in the second-brain view, got: {opened}"
+ );
+}
+
+#[test]
+fn brain_refuses_an_empty_folder_before_touching_a_server() {
+ let root = tempfile::tempdir().unwrap();
+ let empty = root.path().join("empty");
+ fs::create_dir(&empty).unwrap();
+ let data_dir = root.path().join("data-empty");
+ let marker = root.path().join("browser-marker");
+ let fake_browser = root.path().join("fake-browser.sh");
+ write_fake_browser(&fake_browser, &marker);
+ let url = format!("http://localhost:{}", free_port_triple());
+
+ let out = run_brain(
+ &[
+ empty.to_str().unwrap(),
+ "--url",
+ &url,
+ "--data-dir",
+ data_dir.to_str().unwrap(),
+ ],
+ root.path(),
+ &fake_browser,
+ );
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert_eq!(out.status.code(), Some(1), "stderr:\n{stderr}");
+ assert!(
+ stderr.contains("nothing to build a brain from"),
+ "must say honestly why, and what would work\nstderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("xerj brain ~/notes"),
+ "must show a working example\nstderr:\n{stderr}"
+ );
+ assert!(
+ !data_dir.exists(),
+ "an empty ask must not boot a server or create a data dir"
+ );
+ assert!(!marker.exists(), "and must certainly not open a browser");
+}
+
+#[test]
+fn brain_help_is_stranger_readable() {
+ let out = Command::new(env!("CARGO_BIN_EXE_xerj"))
+ .args(["brain", "--help"])
+ .output()
+ .unwrap();
+ assert!(out.status.success());
+ let help = String::from_utf8_lossy(&out.stdout);
+ for needle in [
+ "turn a folder into a running, browsable second brain",
+ "indexes every readable file",
+ "opens your knowledge in",
+ "USAGE",
+ "--no-open",
+ "--brain",
+ ] {
+ assert!(help.contains(needle), "help missing {needle:?}:\n{help}");
+ }
+}
diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.css
index e68dd4da0..4ad72ca43 100644
--- a/xerj-ux/assets/base.css
+++ b/xerj-ux/assets/base.css
@@ -1785,6 +1785,8 @@ html.mobile-preview .nav-sub {
}
.sb-ghcount { font-family: var(--font-data); font-size: var(--fs-11); color: var(--z-mute); white-space: nowrap; }
+.sb-sidecap { margin-bottom: var(--sp-1); }
+
.sb-erow { border-bottom: 1px solid var(--z-faint); }
.sb-erow-main { display: flex; gap: var(--sp-2); align-items: baseline; padding: 6px 0; }
.sb-ename {
@@ -1812,11 +1814,19 @@ html.mobile-preview .nav-sub {
}
.sb-emeta:hover .sb-eev, .sb-emeta:focus-visible .sb-eev { color: var(--z-accent); }
.sb-ehop2 { color: var(--z-ink); }
-.sb-extag { display: none; color: var(--z-accent); letter-spacing: var(--track-label); font-size: var(--fs-11); }
-.sb-erow.sb-expired .sb-extag { display: inline; }
+.sb-eq { letter-spacing: var(--track-label); font-size: 10px; }
+/* State tags. RETIRED wears the accent (the time-travel payoff);
+ NOT YET stays muted — the future is quiet, the past is loud. */
+.sb-tag { display: none; letter-spacing: var(--track-label); font-size: var(--fs-11); }
+.sb-tag-retired { color: var(--z-accent); }
+.sb-tag-notyet { color: var(--z-mute); }
+.sb-erow.sb-expired .sb-tag-retired { display: inline; }
+.sb-erow.sb-off .sb-tag-notyet { display: inline; }
.sb-erow.sb-expired .sb-ename,
.sb-erow.sb-expired .sb-ewin { text-decoration: line-through; color: var(--z-mute); }
-.sb-erow.sb-off { display: none; }
+/* A link not yet believed at the caret stays visible but ghosted —
+ rows never pop in and out while scrubbing, they dim. */
+.sb-erow.sb-off .sb-erow-main { opacity: 0.35; }
.sb-sidenote { font-size: var(--fs-11); letter-spacing: 0.06em; padding: var(--sp-2) 0; }
.sb-evbody { padding: 2px 0 10px; }
@@ -1844,7 +1854,9 @@ html.mobile-preview .nav-sub {
}
.sb-striplines { width: 100%; color: var(--z-ink); }
.sb-lseg.sb-l-live { stroke-opacity: 1; }
-.sb-lseg.sb-l-expired { stroke-opacity: 0.45; }
+/* Retired lifetimes go dashed as well as dim — state never rides on
+ opacity alone (print / forced-colors / low-contrast screens). */
+.sb-lseg.sb-l-expired { stroke-opacity: 0.45; stroke-dasharray: 3 2; }
.sb-lseg.sb-l-future { stroke-opacity: 0.15; }
.sb-ltick { stroke-opacity: 0.7; }
.sb-caret {
@@ -1902,22 +1914,76 @@ html.mobile-preview .nav-sub {
.sb-hv { font-weight: 700; }
.sb-hids { padding: 4px 0; font-size: var(--fs-11); }
-/* Hubs */
+/* Hubs (centers of gravity). Own row grid: the shared .row template
+ starves the name column — names are the point of this panel. */
.sb-hubs { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
.sb-hubs .key { margin-bottom: 8px; }
-.sb-hub-active .row__label { color: var(--z-accent); }
+.sb-hubrow {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto 64px;
+ gap: var(--sp-2);
+ align-items: baseline;
+ padding: 4px 0;
+ border-bottom: 1px solid var(--z-faint);
+ font-family: var(--font-data);
+ font-size: var(--fs-13);
+ cursor: pointer;
+}
+.sb-hubname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.sb-hubn { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
+.sb-hubbar { width: 100%; align-self: center; }
+.sb-hubrow:hover .sb-hubname,
+.sb-hubrow:focus-visible .sb-hubname { color: var(--z-accent); }
+.sb-hub-active .sb-hubname { color: var(--z-accent); }
+@media (max-width: 640px) {
+ .sb-hubs { grid-template-columns: 1fr; gap: var(--sp-3); }
+}
+
+/* Detector mini-rows (WHAT TAUGHT THIS BRAIN) */
+.sb-dets { display: flex; flex-direction: column; }
+.sb-det {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto 48px;
+ gap: var(--sp-2);
+ align-items: baseline;
+ padding: 3px 0;
+ border-bottom: 1px solid var(--z-faint);
+ font-family: var(--font-data);
+ font-size: var(--fs-13);
+}
+.sb-detname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--z-ink); }
+.sb-detn { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
+
+/* Believed-vs-retired composition bar — the one two-series comparison.
+ Accent = believed, --z-cmp = retired; both directly labelled. */
+.sb-splitwrap { margin-top: var(--sp-2); }
+.sb-split { width: 100%; height: 8px; display: block; }
+.sb-seg-live { color: var(--z-accent); }
+.sb-seg-retired { color: var(--z-cmp); }
+.sb-splitleg { display: flex; gap: var(--sp-3); margin-top: 6px; font-size: var(--fs-11); color: var(--z-ink); }
+.sb-leg { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
+.sb-legline { flex: none; }
/* Empty / live-only states */
.sb-empty { padding: var(--sp-2) 0 var(--sp-4); max-width: 760px; }
.sb-empty .sb-ftext { margin: var(--sp-2) 0; }
+.sb-cmdrow {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ margin: var(--sp-2) 0;
+}
.sb-cmd {
- font-size: var(--fs-13);
+ flex: 0 1 auto;
+ min-width: 0;
+ font-size: var(--fs-16);
color: var(--z-ink);
border-left: 1px solid var(--z-accent);
padding: var(--sp-1) var(--sp-2);
- margin: var(--sp-2) 0;
+ margin: 0;
overflow-x: auto;
white-space: pre;
+ user-select: all; /* one click selects the whole command */
}
/* Narrow screens: stack — focus card first, then in, then out. */
diff --git a/xerj-ux/assets/tokens.css b/xerj-ux/assets/tokens.css
index a314c3aa5..1de714672 100644
--- a/xerj-ux/assets/tokens.css
+++ b/xerj-ux/assets/tokens.css
@@ -5,12 +5,20 @@
============================================================ */
:root {
- /* Color — five values, no more */
+ /* Color — six values, no more.
+ --z-cmp is the ONLY comparison-series color: it pairs with
+ --z-accent when two series share one scale (e.g. believed vs
+ retired). Validated against both surfaces: CVD ΔE 23.2 night /
+ 17.7 day vs the accent (target ≥ 8) — never use mute-gray as a
+ second series; gray-vs-accent fails colorblind separation in day
+ mode. Deliberately low-chroma (recessive): every cmp mark must
+ carry a direct numeric label, so color is never the sole carrier. */
--z-paper: #0D0D0D;
--z-ink: #E0E0E0;
--z-mute: #555555;
--z-faint: #2A2A2A;
--z-accent: #EEBB00;
+ --z-cmp: #7F93AA;
/* Type families */
--font-display: 'Big Shoulders Display', 'Impact', 'Helvetica Neue Condensed', sans-serif;
@@ -54,6 +62,7 @@
--z-ink: #E0E0E0;
--z-mute: #555555;
--z-faint: #2A2A2A;
+ --z-cmp: #7F93AA;
}
:root[data-theme='day'] {
--z-paper: #FBFAF6;
@@ -64,4 +73,7 @@
The night accent (#EEBB00) is 1.7:1 on paper — unreadable.
#A06800 is 5.7:1, passes AA body text. Same hue family. */
--z-accent: #A06800;
+ /* Day comparison — same steel family, stepped for the light
+ surface (CVD ΔE 17.7 vs the day accent, ≥3:1 on paper). */
+ --z-cmp: #6F8AA8;
}
diff --git a/xerj-ux/setup.html b/xerj-ux/setup.html
index ccbb1a158..62fd93b97 100644
--- a/xerj-ux/setup.html
+++ b/xerj-ux/setup.html
@@ -142,6 +142,17 @@ function clearHash() {
}
const token = tokenFromHash();
+// Optional post-setup destination (`&next=…` in the fragment) — e.g. the
+// second-brain view `xerj brain` printed. Restricted to an in-console hash
+// route: anything with a scheme, `//`, or characters outside a route is
+// discarded, so a magic link can never become an open redirect. Captured
+// now because clearHash() wipes the fragment on redeem.
+const nextRoute = (() => {
+ const frag = window.location.hash.replace(/^#/, '');
+ const n = new URLSearchParams(frag).get('next') || '';
+ if (!n || n.includes(':') || n.includes('//') || !/^[A-Za-z0-9/?&=_-]+$/.test(n)) return '';
+ return '#/' + n.replace(/^[#/]+/, '');
+})();
if (!token) {
showError('No magic-link token in URL. The link must include #token=…');
$btnEnrol.disabled = true;
@@ -214,7 +225,7 @@ async function enrol() {
showStep('step-done');
showOk('Enrolled. Redirecting…');
- setTimeout(() => { window.location.href = '/_xerj-console/'; }, 800);
+ setTimeout(() => { window.location.href = '/_xerj-console/' + nextRoute; }, 800);
} catch (e) {
showStep('step-info');
showError(e.message || String(e));
diff --git a/xerj-ux/src/app.js b/xerj-ux/src/app.js
index 819a3de2d..d838b7936 100644
--- a/xerj-ux/src/app.js
+++ b/xerj-ux/src/app.js
@@ -392,7 +392,10 @@ function runSearchNow() {
* redirects to `#/settings`.
*/
function parseRoute() {
- const raw = (location.hash || '').replace(/^#\/?/, '');
+ // Route = the hash *path* only. A `?query` tail inside the hash (e.g.
+ // `#/second-brain?brain=notes`, the deep link `xerj brain` prints) is
+ // view state owned by the dashboard, never part of the route.
+ const raw = (location.hash || '').replace(/^#\/?/, '').split('?')[0];
const parts = raw.split('/').filter(Boolean);
const merged = mergedDashboards(defaults, { includeHidden: true });
diff --git a/xerj-ux/src/dashboards/second-brain.js b/xerj-ux/src/dashboards/second-brain.js
index 5f53f431e..32cfc26b3 100644
--- a/xerj-ux/src/dashboards/second-brain.js
+++ b/xerj-ux/src/dashboards/second-brain.js
@@ -34,24 +34,27 @@ export const secondBrain = {
sbAfterRender();
return {
title: 'SECOND BRAIN',
- kicker: 'GRAPH MEMORY · EVIDENCE · TIME TRAVEL',
+ kicker: 'WHAT YOUR NOTES BELIEVE · EVERY LINK HAS A QUOTE · REPLAYABLE AT ANY MOMENT',
meta: [time, 'XERJ-GRAPH'],
+ // Eyebrows speak user words — link / believed / retired / taught.
+ // Schema vocabulary (edge, src/dst, as-of) stays in the API and
+ // in the evidence paper-trail, never in a panel title.
panels: [
- { id: 'edgesLive', eyebrow: 'LIVE EDGES', cols: 3, type: 'metric',
+ { id: 'edgesLive', eyebrow: 'BELIEVED AT THIS MOMENT', cols: 3, type: 'metric',
render: () => body('edgesLive', data) },
- { id: 'edgesTotal', eyebrow: 'TOTAL ASSERTED', cols: 3, type: 'metric',
+ { id: 'edgesTotal', eyebrow: 'EVER ASSERTED', cols: 3, type: 'metric',
render: () => body('edgesTotal', data) },
- { id: 'invalidated', eyebrow: 'INVALIDATED (KEPT)', cols: 3, type: 'metric',
+ { id: 'invalidated', eyebrow: 'RETIRED · KEPT FOR REPLAY', cols: 3, type: 'metric',
render: () => body('invalidated', data) },
- { id: 'detectors', eyebrow: 'DETECTORS', cols: 3, type: 'metric',
+ { id: 'detectors', eyebrow: 'WHAT TAUGHT THIS BRAIN', cols: 3, type: 'metric',
render: () => body('detectors', data) },
- { id: 'typeDist', eyebrow: 'EDGE TYPES', cols: 6, type: 'dist',
+ { id: 'typeDist', eyebrow: 'HOW NOTES CONNECT', cols: 6, type: 'dist',
render: () => body('typeDist', data) },
- { id: 'edgeTimeline', eyebrow: 'EDGES OVER TIME', cols: 6, type: 'series',
+ { id: 'edgeTimeline', eyebrow: 'NEW LINKS PER DAY', cols: 6, type: 'series',
render: () => body('edgeTimeline', data) },
- { id: 'ego', eyebrow: 'EGO · 1 HOP FROM SELECTED NODE', cols: 12, type: 'ego',
+ { id: 'ego', eyebrow: 'THE LEDGER · ONE NOTE, EVERYTHING IT TOUCHES', cols: 12, type: 'ego',
render: () => body('ego', data) },
- { id: 'hubs', eyebrow: 'HUBS · IN / OUT', cols: 6, type: 'topn',
+ { id: 'hubs', eyebrow: 'CENTERS OF GRAVITY', cols: 6, type: 'topn',
render: () => body('hubs', data) },
{ id: 'notShown', eyebrow: 'WHAT THIS VIEW DID NOT SHOW', cols: 6, type: 'honesty',
render: () => body('notShown', data) },
diff --git a/xerj-ux/src/data/second-brain-api.js b/xerj-ux/src/data/second-brain-api.js
index 2c9da0d43..d076ce15b 100644
--- a/xerj-ux/src/data/second-brain-api.js
+++ b/xerj-ux/src/data/second-brain-api.js
@@ -56,16 +56,29 @@ const S = {
connected: false,
error: null, // transport-level error (engine unreachable)
uiError: null, // last interaction-level error (shown inline, non-fatal)
+ overviewError: null, // overview read failed on a REAL brain — an error state, never "empty"
brains: [],
brain: null,
+ lastHashBrain: null, // last `?brain=` deep-link value already applied
focus: null,
asOf: null, // epoch-ms | null = NOW
trail: [],
overview: null, // §4.4 body (or exists:false body)
ego: null, // §4.3 body — the belief at the caret
timeline: null, // §4.3 body — hop-1, include_expired, pinned at NOW
+ names: {}, // node id → { title } — display names for hub ids / crumbs
};
+/** `brain` out of the hash's query tail (`#/second-brain?brain=X`), or
+ * null. The router (app.js parseRoute) ignores everything after `?`. */
+function hashBrain() {
+ const h = location.hash || '';
+ const q = h.indexOf('?');
+ if (q < 0) return null;
+ const b = (new URLSearchParams(h.slice(q + 1)).get('brain') || '').trim();
+ return b || null;
+}
+
function loadBrainState() {
try {
const raw = sessionStorage.getItem(K.perBrain(S.brain));
@@ -138,6 +151,48 @@ async function discoverBrains(baseUrl, signal) {
const enc = encodeURIComponent;
+/**
+ * Hub lists and focus crumbs come back from the overview as raw node
+ * ids — for autoindex brains those are opaque hashes no person should
+ * have to read. One bounded ids-query against the brain's nodes index
+ * turns them into titles. Best-effort and honest: any id that does not
+ * resolve keeps rendering as its (shortened) id, never as a guess.
+ */
+async function hydrateNames(signal) {
+ const o = S.overview;
+ if (!o || o.exists === false || !o.nodes_index) return;
+ const ids = new Set();
+ for (const h of (o.hubs && o.hubs.in) || []) ids.add(h.id);
+ for (const h of (o.hubs && o.hubs.out) || []) ids.add(h.id);
+ for (const t of S.trail) ids.add(t);
+ if (S.focus) ids.add(S.focus);
+ const want = [...ids].filter((id) => !(id in S.names)).slice(0, 40);
+ if (!want.length) return;
+ try {
+ const r = await fetch(`${S.baseUrl}/${enc(o.nodes_index)}/_search`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ query: { ids: { values: want } },
+ size: want.length,
+ _source: ['title', 'text', 'body'],
+ }),
+ signal,
+ });
+ if (!r.ok) return; // cosmetic enrichment only — ids still render
+ const j = await r.json();
+ for (const h of (j.hits && j.hits.hits) || []) {
+ const src = h._source || {};
+ const title = typeof src.title === 'string' && src.title.trim()
+ ? src.title.trim()
+ : (typeof src.text === 'string' && src.text.trim()
+ ? src.text.trim().slice(0, 60)
+ : (typeof src.body === 'string' && src.body.trim() ? src.body.trim().slice(0, 60) : null));
+ if (title) S.names[h._id] = { title };
+ }
+ } catch { /* names are sugar; the ids remain the truth */ }
+}
+
function fetchOverview(signal) {
const qs = new URLSearchParams({ top: '10', histogram_interval: 'day' });
if (S.asOf != null) qs.set('as_of', String(S.asOf));
@@ -146,7 +201,7 @@ function fetchOverview(signal) {
/**
* The belief at the caret. `include_expired=true` so an invalidated
- * fact comes back struck-through + EXPIRED instead of silently gone;
+ * fact comes back struck-through + RETIRED instead of silently gone;
* hops=2 feeds the neighbour onward-counts; include_nodes hydrates
* titles/previews for the focus card and rows.
*/
@@ -182,14 +237,17 @@ function assemble() {
const num = (v) => new Intl.NumberFormat('en').format(v || 0);
const detectors = (o && o.detectors) || [];
const detTail = o && o.not_shown && o.not_shown.detectors_not_listed > 0 ? '+' : '';
+ // Hints in user words, and as-of-aware: the same tile must say
+ // WHEN it is true once the belief caret leaves NOW.
+ const atHint = S.asOf != null ? `at ${fmtTs(S.asOf)} UTC` : 'right now';
return {
brain: S.brain,
overview: S.overview,
ego: S.ego,
metrics: {
- edgesLive: { formatted: num(ed.live), hint: 'visible at as-of' },
- edgesTotal: { formatted: num(ed.total), hint: 'incl. invalidated' },
- invalidated: { formatted: num(ed.invalidated), hint: 'soft-deleted, kept for time travel' },
+ edgesLive: { formatted: num(ed.live), hint: `held true ${atHint}` },
+ edgesTotal: { formatted: num(ed.total), hint: 'nothing is ever deleted' },
+ invalidated: { formatted: num(ed.invalidated), hint: 'drag belief time left to revisit' },
detectors: { formatted: num(detectors.length) + detTail, hint: 'deterministic, versioned' },
},
series: {
@@ -200,11 +258,13 @@ function assemble() {
connected: S.connected,
error: S.error,
uiError: S.uiError,
+ overviewError: S.overviewError,
brains: S.brains.slice(),
focus: S.focus,
asOf: S.asOf,
trail: S.trail.slice(),
timeline: S.timeline,
+ names: S.names,
},
};
}
@@ -241,6 +301,20 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
let persisted = null;
try { persisted = localStorage.getItem(K.brain); } catch { /* private mode */ }
+ // Deep link: `#/second-brain?brain=X` — the URL `xerj brain` prints and
+ // opens. Applied when it CHANGES (pasting a new link switches brains) but
+ // never re-asserted on every render, so the in-app picker still wins for
+ // the rest of the session.
+ const fromHash = hashBrain();
+ if (fromHash && fromHash !== S.lastHashBrain) {
+ S.lastHashBrain = fromHash;
+ if (S.brains.includes(fromHash)) {
+ persisted = fromHash;
+ try { localStorage.setItem(K.brain, fromHash); } catch { /* private mode */ }
+ } else {
+ S.uiError = `brain "${fromHash}" not found on this engine`;
+ }
+ }
S.brain = persisted && S.brains.includes(persisted) ? persisted : (S.brains[0] || null);
if (!S.brain) {
S.overview = null; S.ego = null; S.timeline = null;
@@ -250,10 +324,15 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
try {
S.overview = await fetchOverview(signal);
+ S.overviewError = null;
} catch (e) {
+ // A failed read on a real brain is an ERROR, not an empty brain:
+ // the renderer must show "could not read", never zeros or the
+ // fill-me teaching copy.
S.overview = null; S.ego = null; S.timeline = null;
+ S.overviewError = String((e && e.message) || e);
const data = assemble();
- data.error = `overview failed: ${String((e && e.message) || e)}`;
+ data.error = `overview failed: ${S.overviewError}`;
return data;
}
@@ -279,6 +358,7 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
} else {
S.ego = null; S.timeline = null;
}
+ await hydrateNames(signal);
saveBrainState();
return assemble();
}
@@ -347,13 +427,15 @@ async function refetch({ overview = false, belief = false, timeline = false }) {
S.uiError = null;
try {
const jobs = [];
- if (overview) jobs.push(fetchOverview(signal).then((r) => { S.overview = r; }));
+ if (overview) jobs.push(fetchOverview(signal).then((r) => { S.overview = r; S.overviewError = null; }));
if (belief && S.focus) jobs.push(fetchBelief(signal).then((r) => { S.ego = r; }));
if (timeline && S.focus) jobs.push(fetchTimeline(signal).then((r) => { S.timeline = r; }));
await Promise.all(jobs);
+ await hydrateNames(signal);
} catch (e) {
if (!(e && e.name === 'AbortError')) {
S.uiError = String((e && e.message) || e);
+ if (overview) S.overviewError = S.uiError;
}
} finally {
setBusy(false);
@@ -417,7 +499,8 @@ function normalizeAsOf(ms, dom) {
/** Move the caret + relabel + restate every strip line and ledger row
* for a candidate as-of. Pure DOM, no queries — this is the mid-drag
- * preview over edges the server already returned. */
+ * preview over edges the server already returned. The live counter in
+ * the legend follows the caret so the drag narrates itself. */
function previewAsOf(scrub, ms) {
const dom = stripDomain(scrub);
if (!dom) return;
@@ -425,18 +508,28 @@ function previewAsOf(scrub, ms) {
const caret = scrub.querySelector('[data-sb-caret]');
const label = scrub.querySelector('[data-sb-caret-label]');
const atNow = normalizeAsOf(ms, dom) == null;
- if (caret) caret.style.left = `${pct}%`;
+ if (caret) {
+ caret.style.left = `${pct}%`;
+ caret.setAttribute('aria-valuenow', String(ms));
+ caret.setAttribute('aria-valuetext', atNow ? 'now' : `${fmtTs(ms)} UTC`);
+ }
if (label) {
- label.style.left = `${pct}%`;
+ label.style.left = `${Math.max(3, Math.min(97, pct))}%`;
label.textContent = atNow ? 'NOW' : fmtTs(ms);
}
const t = atNow ? null : ms;
+ let live = 0;
+ let total = 0;
for (const seg of scrub.querySelectorAll('.sb-lseg')) {
const e = { valid_at: Number(seg.getAttribute('data-va')), invalid_at: seg.hasAttribute('data-vi') ? Number(seg.getAttribute('data-vi')) : null };
const state = edgeStateAt(e, t);
+ total += 1;
+ if (state === 'live') live += 1;
seg.classList.remove('sb-l-live', 'sb-l-future', 'sb-l-expired');
seg.classList.add(`sb-l-${state}`);
}
+ const counter = scrub.querySelector('[data-sb-livecount]');
+ if (counter) counter.textContent = `${live} OF ${total}`;
for (const row of document.querySelectorAll('[data-sb-edge][data-va]')) {
const e = { valid_at: Number(row.getAttribute('data-va')), invalid_at: row.hasAttribute('data-vi') ? Number(row.getAttribute('data-vi')) : null };
const state = edgeStateAt(e, t);
@@ -450,15 +543,25 @@ function previewAsOf(scrub, ms) {
let wired = false;
let drag = null; // { scrub, dom, ms }
+/**
+ * Belief-time dragging starts ANYWHERE on the strip, not only on the
+ * 13px caret — discoverability beats precision here. A press previews
+ * immediately at the pointer; moving scrubs; releasing commits (a
+ * plain click is just a zero-length drag). pointercancel reverts the
+ * preview instead of committing a half-drag.
+ */
function onPointerDown(e) {
- const caret = e.target.closest && e.target.closest('[data-sb-caret]');
- if (!caret) return;
- const scrub = caret.closest('[data-sb-scrub]');
+ const strip = e.target.closest && e.target.closest('[data-sb-strip]');
+ if (!strip) return;
+ const scrub = strip.closest('[data-sb-scrub]');
const dom = scrub && stripDomain(scrub);
if (!dom) return;
e.preventDefault();
- drag = { scrub, dom, ms: S.asOf == null ? dom[1] : S.asOf };
- if (caret.setPointerCapture && e.pointerId != null) {
+ const ms = msFromClientX(strip, dom, e.clientX);
+ drag = { scrub, dom, ms };
+ previewAsOf(scrub, ms);
+ const caret = scrub.querySelector('[data-sb-caret]');
+ if (caret && caret.setPointerCapture && e.pointerId != null) {
try { caret.setPointerCapture(e.pointerId); } catch { /* older engines */ }
}
}
@@ -478,6 +581,15 @@ function onPointerUp() {
commitAsOf(ms);
}
+/** A cancelled drag (scroll steal, palm touch) must not time-travel:
+ * put the preview back where the committed caret is. */
+function onPointerCancel() {
+ if (!drag) return;
+ const { scrub, dom } = drag;
+ drag = null;
+ previewAsOf(scrub, S.asOf == null ? dom[1] : S.asOf);
+}
+
function onClick(e) {
const t = e.target;
if (!t || !t.closest) return;
@@ -487,6 +599,25 @@ function onClick(e) {
if (t.closest('[data-sb-now]')) { commitAsOf(null); return; }
+ if (t.closest('[data-sb-retry]')) {
+ refetch({ overview: true, belief: true, timeline: true });
+ return;
+ }
+
+ const copyBtn = t.closest('[data-sb-copy]');
+ if (copyBtn) {
+ const cmd = copyBtn.parentElement && copyBtn.parentElement.querySelector('[data-sb-cmd]');
+ const text = cmd ? cmd.textContent.trim() : '';
+ if (text && navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(text).then(() => {
+ const was = copyBtn.textContent;
+ copyBtn.textContent = 'COPIED';
+ setTimeout(() => { copyBtn.textContent = was; }, 1200);
+ }).catch(() => { /* clipboard blocked — the text is selectable */ });
+ }
+ return;
+ }
+
const focusBtn = t.closest('[data-sb-focus]');
if (focusBtn) { refocus(focusBtn.getAttribute('data-sb-focus')); return; }
@@ -497,18 +628,8 @@ function onClick(e) {
if (body) body.hidden = !body.hidden;
return;
}
-
- // Click on the strip (not the caret) = jump the caret there.
- const strip = t.closest('[data-sb-strip]');
- if (strip && !t.closest('[data-sb-caret]')) {
- const scrub = strip.closest('[data-sb-scrub]');
- const dom = scrub && stripDomain(scrub);
- if (dom) {
- const ms = msFromClientX(strip, dom, e.clientX);
- previewAsOf(scrub, ms);
- commitAsOf(normalizeAsOf(ms, dom));
- }
- }
+ // Strip clicks are handled by the pointer pipeline above (a click is
+ // a zero-length drag) — no second commit path here.
}
let keyCommit = 0;
@@ -540,7 +661,7 @@ function onResize() {
document.addEventListener('pointerdown', onPointerDown);
document.addEventListener('pointermove', onPointerMove);
document.addEventListener('pointerup', onPointerUp);
- document.addEventListener('pointercancel', onPointerUp);
+ document.addEventListener('pointercancel', onPointerCancel);
document.addEventListener('keydown', onKeyDown);
window.addEventListener('resize', onResize);
})();
diff --git a/xerj-ux/src/ux/ego-ledger.js b/xerj-ux/src/ux/ego-ledger.js
index 89445f54e..ef1f95e88 100644
--- a/xerj-ux/src/ux/ego-ledger.js
+++ b/xerj-ux/src/ux/ego-ledger.js
@@ -7,16 +7,21 @@
// same brain must always draw the same picture), and it optimises for
// looking at over navigating. The ledger is an ego view:
//
-// LEFT column = inbound edges, grouped by type
-// CENTRE = the focus card (one node, its text, its provenance)
-// RIGHT column = outbound edges, grouped by type
+// LEFT column = what links INTO the focus note, grouped by kind
+// CENTRE = the focus card (one note, its text, its provenance)
+// RIGHT column = what the focus note links OUT to, grouped by kind
//
// Graph gestalt comes from 1px orthogonal traces drawn from the focus
// card to each GROUP HEADER (never to every row — zero occlusion, zero
-// simulation). Hop 2 appears as a count on each neighbour row — a
-// promise of the next query, not 27 more drawn nodes. The signature
-// interaction is the BELIEF-TIME strip: every edge's validity interval
-// on one time axis with a draggable as-of caret.
+// simulation). Two-steps-away appears as a "+N MORE" count on each
+// neighbour row — a promise of the next click, not 27 more drawn
+// nodes. The signature interaction is the BELIEF-TIME strip: every
+// link's lifetime on one time axis with a draggable as-of caret.
+//
+// LANGUAGE RULE: this surface speaks user words — "link", "believed
+// since", "retired", "what taught this". Schema names (src/dst/
+// valid_at/edge_id) appear ONLY inside the evidence paper-trail, which
+// is the developer-facing raw view, and even there labelled in words.
//
// Honesty rules (§0 invariant 8 of the second-brain contract): every
// cap this view applies is labelled in place ("TOP 12 OF 41"), the
@@ -29,14 +34,47 @@
// ============================================================
import { esc, fmt, num, Num } from './text.js';
-import { Series, Dist } from './charts.js';
+import { Spark, Series, Dist } from './charts.js';
-// Rows shown per edge-type group before the in-band "TOP n OF m" cap.
+// Rows shown per link-kind group before the in-band "TOP n OF m" cap.
export const LEDGER_GROUP_CAP = 12;
-// Validity rows drawn in the belief-time strip (top by weight, then
-// valid_at, then edge_id — deterministic), cap labelled in the legend.
+// Lifetime rows drawn in the belief-time strip (top by strength, then
+// believed-since, then id — deterministic), cap labelled in the legend.
export const SCRUB_ROW_CAP = 64;
+// ----- user-word vocabulary ----------------------------------------
+
+/** Detector-flavoured edge types → words a first-run user knows.
+ * Unknown types (hand-asserted vocabularies) are prettified raw. */
+const TYPE_WORDS = {
+ wikilink: 'WIKI-LINKS',
+ mdlink: 'MARKDOWN LINKS',
+ href: 'HTML LINKS',
+ sequence: 'READING ORDER',
+ same_dir: 'SAME FOLDER',
+ manual: 'HAND-ASSERTED',
+};
+export const typeName = (t) =>
+ TYPE_WORDS[t] || String(t || 'links').replace(/[_-]+/g, ' ').toUpperCase();
+
+/** Ids are opaque doc ids — autoindex ones are long hashes. Never make
+ * a human read 32 hex chars as a name. */
+const looksHashy = (id) => /^[0-9a-f]{16,}$/i.test(String(id || ''));
+export const displayId = (id) => {
+ const s = String(id || '');
+ return looksHashy(s) ? `${s.slice(0, 10)}…` : s;
+};
+
+/** Display name for a node id: hydrated title first (ego nodes, then
+ * the console's own name cache), else the id (shortened if hashy). */
+const nodeName = (id, ctx) => {
+ const fromEgo = ctx && ctx.nodes && ctx.nodes[id] && ctx.nodes[id].title;
+ if (fromEgo) return fromEgo;
+ const fromCache = ctx && ctx.names && ctx.names[id] && ctx.names[id].title;
+ if (fromCache) return fromCache;
+ return displayId(id);
+};
+
// ----- time ---------------------------------------------------------
/** Epoch-ms → 'YYYY-MM-DD HH:MM' (UTC — belief time is server time). */
@@ -51,14 +89,17 @@ export const fmtDay = (ms) => {
return new Date(Number(ms)).toISOString().slice(0, 10);
};
-/** An edge's validity window as text: '2026-07-25 → NOW' / '→ 2026-07-26'. */
+/** A link's lifetime as words. The tags on the row (RETIRED / NOT
+ * YET) carry the state at the caret; this carries the facts. */
const fmtWindow = (validAt, invalidAt) =>
- `${fmtDay(validAt)} → ${invalidAt == null ? 'NOW' : fmtDay(invalidAt)}`;
+ invalidAt == null
+ ? `since ${fmtDay(validAt)}`
+ : `${fmtDay(validAt)} → ${fmtDay(invalidAt)}`;
// ----- bi-temporal cut (client-side preview only) -------------------
//
// The SERVER owns the as-of cut (`ego?as_of=`). These helpers exist so
-// the scrubber can preview visibility over already-fetched edges while
+// the scrubber can preview visibility over already-fetched links while
// the caret is mid-drag; the release commits an honest re-query.
export const edgeStateAt = (edge, asOfMs) => {
@@ -73,15 +114,11 @@ export const edgeStateAt = (edge, asOfMs) => {
/** The node on the far end of an edge, given the expansion direction. */
const farEnd = (edge) => (edge.direction === 'in' ? edge.src : edge.dst);
-/** Display name for a node id: hydrated title if present, else the id. */
-const nodeName = (id, nodes) =>
- (nodes && nodes[id] && nodes[id].title) ? nodes[id].title : id;
-
/**
* Hop-1 edges of one side, grouped by type. Order is deterministic:
- * groups by live-count desc then type asc; rows keep the server's
- * contract order (hop asc, weight desc, edge_id asc) untouched — the
- * same data always draws the same picture.
+ * groups by count desc then type asc; rows keep the server's contract
+ * order (hop asc, weight desc, edge_id asc) untouched — the same data
+ * always draws the same picture.
*/
export function groupEdges(edges, side) {
const byType = new Map();
@@ -97,9 +134,10 @@ export function groupEdges(edges, side) {
}
/**
- * Per-neighbour hop-2 degree: how many hop-2 edges touch this node,
- * counting only edges live at the caret. When the server clipped the
- * result set the count is a floor, rendered '≥n' — never a fake exact.
+ * Per-neighbour hop-2 degree: how many two-steps-away links touch this
+ * node, counting only links live at the caret. When the server clipped
+ * the result set the count is a floor, rendered '≥n' — never a fake
+ * exact.
*/
export function hop2Counts(edges, asOfMs) {
const counts = new Map();
@@ -114,55 +152,55 @@ export function hop2Counts(edges, asOfMs) {
// ----- evidence -----------------------------------------------------
-/** The exact source quote that taught this edge, plus its full paper trail. */
+/** The exact source quote that taught this link, plus its full paper
+ * trail. This block is the ONLY place raw ids surface — labelled. */
const EvidenceBlock = (e) => {
const ev = e.evidence || {};
const quote = ev.quote
? `<p class="sb-evquote">“${esc(ev.quote)}”</p>`
- : `<p class="sb-evquote sb-evnone">no evidence recorded for this edge</p>`;
+ : `<p class="sb-evquote sb-evnone">no source quote was recorded for this link</p>`;
const src = ev.source
- ? `<span>${esc(ev.source)}${ev.offset != null ? ` · byte ${esc(ev.offset)}` : ''}</span>`
+ ? `<span>from ${esc(ev.source)}${ev.offset != null && ev.offset > 0 ? ` · byte ${esc(ev.offset)}` : ''}</span>`
: '';
+ const conf = e.confidence ?? 1;
const invalid = e.invalid_at != null
- ? ` · invalid ${esc(fmtTs(e.invalid_at))}` : '';
+ ? ` · believed until ${esc(fmtTs(e.invalid_at))}` : '';
const expired = e.expired_at != null
- ? ` · expiry recorded ${esc(fmtTs(e.expired_at))}` : '';
+ ? ` · retirement recorded ${esc(fmtTs(e.expired_at))}` : '';
return `
<div class="sb-evbody" data-sb-evbody hidden>
${quote}
<div class="sb-evmeta mono faint">
${src}
- <span>${esc(e.detector || 'unknown-detector')} · conf ${esc(fmt(e.confidence ?? 1, { decimals: 2 }))} · w ${esc(fmt(e.weight ?? 1, { decimals: 2 }))}</span>
- <span>valid ${esc(fmtTs(e.valid_at))}${invalid}${expired}</span>
- <span>edge ${esc(e.edge_id)}</span>
+ <span>taught by ${esc(e.detector || 'unknown detector')} · ${esc(fmt(conf * 100, { decimals: 0 }))}% confident · strength ${esc(fmt(e.weight ?? 1, { decimals: 2 }))}</span>
+ <span>believed since ${esc(fmtTs(e.valid_at))}${invalid}${expired}</span>
+ <span>link id ${esc(e.edge_id)} · this is the handle the API takes</span>
</div>
</div>`;
};
// ----- rows + groups ------------------------------------------------
-const edgeRow = (e, side, { nodes, counts, asOf, clipped }) => {
+const edgeRow = (e, side, { counts, asOf, clipped, nodes, names }) => {
const id = farEnd(e);
const state = edgeStateAt(e, asOf);
const n = counts.get(id) || 0;
const hop2 = n > 0
- ? (side === 'out'
- ? `· ${clipped ? '≥' : ''}${num(n)} →`
- : `← ${clipped ? '≥' : ''}${num(n)} ·`)
+ ? `+${clipped ? '≥' : ''}${num(n)} MORE`
: '';
- const evMark = (e.evidence && e.evidence.quote) ? 'ev' : '·';
return `
<div class="sb-erow${state === 'expired' ? ' sb-expired' : ''}${state === 'future' ? ' sb-off' : ''}"
data-sb-edge="${esc(e.edge_id)}" data-va="${esc(e.valid_at)}"${e.invalid_at != null ? ` data-vi="${esc(e.invalid_at)}"` : ''}>
<div class="sb-erow-main">
<button type="button" class="sb-ename" data-sb-focus="${esc(id)}"
- title="Refocus the ledger on ${esc(id)}">${esc(nodeName(id, nodes))}</button>
+ title="Open the ledger for ${esc(id)}">${esc(nodeName(id, { nodes, names }))}</button>
<button type="button" class="sb-emeta" data-sb-evidence="${esc(e.edge_id)}"
- title="Show the evidence that taught this edge">
+ title="Show the source quote that taught this link">
<span class="sb-ewin">${esc(fmtWindow(e.valid_at, e.invalid_at))}</span>
- <span class="sb-eev">${evMark}</span>
- <span class="sb-ehop2">${esc(hop2)}</span>
- <span class="sb-extag">EXPIRED</span>
+ ${(e.evidence && e.evidence.quote) ? '<span class="sb-eq">QUOTE</span>' : ''}
+ ${hop2 ? `<span class="sb-ehop2" title="${esc(num(n))} more link${n === 1 ? '' : 's'} one step beyond — click the name to walk there">${esc(hop2)}</span>` : ''}
+ <span class="sb-tag sb-tag-retired">RETIRED</span>
+ <span class="sb-tag sb-tag-notyet">NOT YET</span>
</button>
</div>
${EvidenceBlock(e)}
@@ -174,12 +212,11 @@ const groupBlock = (g, side, ctx) => {
const shown = Math.min(total, LEDGER_GROUP_CAP);
const countLabel = shown < total
? `TOP ${num(shown)} OF ${num(total)}`
- : `${num(shown)} OF ${num(total)}`;
- const arrowType = side === 'in' ? `← ${g.type}` : `${g.type} →`;
+ : `${num(total)}`;
return `
<div class="sb-group">
<div class="sb-grouphead" data-sb-grouphead="${side}">
- <span class="sb-ghtype">${esc(arrowType.toUpperCase())}</span>
+ <span class="sb-ghtype">${esc(typeName(g.type))}</span>
<span class="sb-ghcount">${esc(countLabel)}</span>
</div>
${g.list.slice(0, LEDGER_GROUP_CAP).map((e) => edgeRow(e, side, ctx)).join('')}
@@ -188,12 +225,12 @@ const groupBlock = (g, side, ctx) => {
// ----- focus card ---------------------------------------------------
-const FocusCard = ({ ego, nodes, brain }) => {
+const FocusCard = ({ ego, nodes, names, brain }) => {
const id = ego.node;
const hop1 = (ego.edges || []).filter((e) => e.hop === 1);
const nIn = hop1.filter((e) => e.direction === 'in').length;
const nOut = hop1.length - nIn;
- const types = new Set(hop1.map((e) => e.type)).size;
+ const kinds = new Set(hop1.map((e) => e.type)).size;
const earliest = hop1.length
? Math.min(...hop1.map((e) => Number(e.valid_at)))
: null;
@@ -207,37 +244,41 @@ const FocusCard = ({ ego, nodes, brain }) => {
return `
<div class="sb-focuscard" data-sb-focuscard>
<div class="key">FOCUS</div>
- <div class="sb-ftitle">${esc(nodeName(id, nodes))}</div>
+ <div class="sb-ftitle">${esc(nodeName(id, { nodes, names }))}</div>
${preview}
<div class="sb-fdeg mono">
- <span>← IN <span class="sb-fnum">${num(nIn)}</span></span>
- <span>OUT <span class="sb-fnum">${num(nOut)}</span> →</span>
- <span>${num(types)} TYPES</span>
+ <span>← <span class="sb-fnum">${num(nIn)}</span> LINK${nIn === 1 ? '' : 'S'} IN</span>
+ <span><span class="sb-fnum">${num(nOut)}</span> OUT →</span>
+ <span><span class="sb-fnum">${num(kinds)}</span> KIND${kinds === 1 ? '' : 'S'}</span>
</div>
<div class="sb-fprov mono faint">
- ${esc(meta && meta.index ? meta.index : `brain ${brain}`)} · ${esc(id)}${dangling ? ' · NO BACKING DOC' : ''}${earliest != null ? ` · in graph since ${esc(fmtDay(earliest))}` : ''}
+ ${esc(meta && meta.index ? meta.index : `brain ${brain}`)} · id ${esc(id)}${dangling ? ' · NO DOCUMENT BEHIND THIS ID' : ''}${earliest != null ? ` · in this brain since ${esc(fmtDay(earliest))}` : ''}
</div>
</div>`;
};
// ----- controls line ------------------------------------------------
-const EgoControls = ({ brain, brains, focus, asOf, trail }) => {
+const EgoControls = ({ brain, brains, focus, asOf, trail, names, nodes }) => {
const others = (brains || []).filter((b) => b !== brain);
const brainSwitch = others.length
? `<span class="sb-cswitch">${others.map((b) =>
- `<button type="button" class="sb-clink" data-sb-brain="${esc(b)}">${esc(b)}</button>`).join('<span class="faint"> · </span>')}</span>`
+ `<button type="button" class="sb-clink" data-sb-brain="${esc(b)}" title="Switch to brain ${esc(b)}">${esc(b)}</button>`).join('<span class="faint"> · </span>')}</span>`
: '';
- const crumbs = (trail || []).filter((t) => t !== focus).slice(-4);
+ const crumbs = (trail || []).filter((t) => t !== focus).slice(-3);
+ const crumbName = (t) => {
+ const n = nodeName(t, { nodes, names });
+ return n.length > 18 ? `${n.slice(0, 17)}…` : n;
+ };
const trailHtml = crumbs.length
? `<span class="sb-ctrail">${crumbs.map((t) =>
- `<button type="button" class="sb-clink" data-sb-focus="${esc(t)}">${esc(t)}</button>`).join('<span class="faint"> → </span>')}<span class="faint"> → </span></span>`
+ `<button type="button" class="sb-clink" data-sb-focus="${esc(t)}" title="Back to ${esc(t)}">${esc(crumbName(t))}</button>`).join('<span class="faint"> → </span>')}<span class="faint"> → </span></span>`
: '';
return `
<div class="sb-controls mono">
<span><span class="key">BRAIN</span> <span class="sb-cval">${esc(brain || '—')}</span> ${brainSwitch}</span>
- <span><span class="key">FOCUS</span> ${trailHtml}<span class="sb-cval">${esc(focus || '—')}</span></span>
- <span><span class="key">AS OF</span> <span class="sb-cval${asOf != null ? ' accent' : ''}">${asOf != null ? esc(fmtTs(asOf)) + ' UTC' : 'NOW'}</span>${asOf != null ? ` <button type="button" class="sb-clink" data-sb-now>RESET</button>` : ''}</span>
+ <span><span class="key">FOCUS</span> ${trailHtml}<span class="sb-cval">${esc(focus ? crumbName(focus) : '—')}</span></span>
+ <span><span class="key">VIEWING</span> <span class="sb-cval${asOf != null ? ' accent' : ''}">${asOf != null ? esc(fmtTs(asOf)) + ' UTC' : 'NOW'}</span>${asOf != null ? ` <button type="button" class="sb-clink" data-sb-now>BACK TO NOW</button>` : ''}</span>
<span class="sb-cerr" data-sb-error></span>
</div>`;
};
@@ -245,19 +286,20 @@ const EgoControls = ({ brain, brains, focus, asOf, trail }) => {
// ----- belief-time scrubber ----------------------------------------
/**
- * Full-width strip of edge-validity intervals over one time axis with a
- * draggable as-of caret. The interval set comes from a timeline query
- * pinned at NOW with include_expired=true, so scrubbing left never
- * makes the strip itself lose rows — only their visibility state
- * changes. Dragging previews client-side; releasing re-queries the
- * server with `as_of` (the caret is a query parameter, not a filter).
+ * Full-width strip: one row per link, drawn from the moment the brain
+ * started believing it to the moment it stopped (or to now). The
+ * accent caret is draggable — drag anywhere on the strip; releasing
+ * re-queries the server with `as_of` (the caret is a query parameter,
+ * not a client filter). The interval set is pinned at NOW with
+ * retired links included, so scrubbing never removes rows — only
+ * their state changes.
*/
export const BeliefScrubber = ({ timeline, asOf }) => {
const edges = (timeline && timeline.edges) || [];
if (!edges.length) {
- return `<div class="sb-scrub" data-sb-scrub><div class="panel-empty mono faint">NO VALIDITY INTERVALS YET · EVERY EDGE DRAWS ITS LIFETIME HERE</div></div>`;
+ return `<div class="sb-scrub" data-sb-scrub><div class="panel-empty mono faint">NOTHING TO REPLAY YET · EVERY LINK WILL DRAW ITS LIFETIME HERE</div></div>`;
}
- // Deterministic row order: weight desc, valid_at asc, edge_id asc.
+ // Deterministic row order: strength desc, believed-since asc, id asc.
const rows = [...edges].sort((a, b) =>
(b.weight - a.weight)
|| (Number(a.valid_at) - Number(b.valid_at))
@@ -271,50 +313,59 @@ export const BeliefScrubber = ({ timeline, asOf }) => {
const d1 = now;
const pctOf = (ms) => Math.max(0, Math.min(100, ((ms - d0) / (d1 - d0)) * 100));
- const rowH = 4;
- const h = rows.length * rowH + 6;
+ // Few links deserve thick, readable rows; many links compress.
+ const rowH = rows.length <= 6 ? 10 : rows.length <= 16 ? 7 : rows.length <= 32 ? 5 : 4;
+ const h = Math.max(44, rows.length * rowH + 8);
const caretMs = asOf == null ? d1 : asOf;
const caretPct = pctOf(caretMs);
+ const labelPct = Math.max(3, Math.min(97, caretPct)); // keep the label on-page at the edges
+ let liveAtCaret = 0;
const lines = rows.map((e, i) => {
- const y = 4 + i * rowH;
+ const y = 6 + i * rowH;
const x1 = pctOf(Number(e.valid_at));
const x2 = e.invalid_at != null ? pctOf(Number(e.invalid_at)) : 100;
const state = edgeStateAt(e, asOf);
+ if (state === 'live') liveAtCaret += 1;
const tick = e.invalid_at != null
- ? `<line class="sb-ltick" x1="${x2}%" x2="${x2}%" y1="${y - 2}" y2="${y + 2}" stroke="currentColor" stroke-width="1"/>`
+ ? `<line class="sb-ltick" x1="${x2}%" x2="${x2}%" y1="${y - 3}" y2="${y + 3}" stroke="currentColor" stroke-width="1"/>`
: '';
return `<line class="sb-lseg sb-l-${state}" data-va="${esc(e.valid_at)}"${e.invalid_at != null ? ` data-vi="${esc(e.invalid_at)}"` : ''} x1="${x1}%" x2="${x2}%" y1="${y}" y2="${y}" stroke="currentColor" stroke-width="1"/>${tick}`;
}).join('');
const capNote = edges.length > rows.length
- ? ` · TOP ${num(rows.length)} OF ${num(edges.length)} BY WEIGHT`
+ ? ` · TOP ${num(rows.length)} OF ${num(edges.length)} BY STRENGTH`
: '';
return `
<div class="sb-scrub" data-sb-scrub data-d0="${d0}" data-d1="${d1}">
- <div class="key">BELIEF TIME · DRAG THE CARET · WHAT DID THIS BRAIN BELIEVE, WHEN</div>
+ <div class="key">BELIEF TIME · DRAG ANYWHERE ON THE STRIP — THE PAGE REPLAYS WHAT THIS BRAIN BELIEVED AT THAT MOMENT</div>
<div class="sb-strip" data-sb-strip style="height:${h}px;">
<svg class="chart sb-striplines" width="100%" height="${h}" aria-hidden="true">${lines}</svg>
<div class="sb-caret" data-sb-caret style="left:${caretPct}%;" role="slider" tabindex="0"
- aria-label="Belief as-of caret" aria-valuemin="${d0}" aria-valuemax="${d1}" aria-valuenow="${caretMs}"></div>
- <div class="sb-caret-label mono" data-sb-caret-label style="left:${caretPct}%;">${asOf == null ? 'NOW' : esc(fmtTs(caretMs))}</div>
+ aria-label="Belief time — what did this brain believe, when"
+ aria-valuemin="${d0}" aria-valuemax="${d1}" aria-valuenow="${caretMs}"
+ aria-valuetext="${asOf == null ? 'now' : esc(fmtTs(caretMs)) + ' UTC'}"></div>
+ <div class="sb-caret-label mono" data-sb-caret-label style="left:${labelPct}%;">${asOf == null ? 'NOW' : esc(fmtTs(caretMs))}</div>
</div>
<div class="sb-scrub-legend mono faint">
- <span>${esc(fmtTs(d0raw))} UTC</span>
- <span class="mid">${num(rows.length)} VALIDITY INTERVALS${esc(capNote)} · EXPIRED EDGES KEEP THEIR ROW</span>
- <span><button type="button" class="text-btn" data-sb-now>NOW</button></span>
+ <span>${esc(fmtDay(d0raw))}</span>
+ <span class="mid"><span data-sb-livecount>${num(liveAtCaret)} OF ${num(rows.length)}</span> BELIEVED AT THE CARET${esc(capNote)} · EACH LINE IS ONE LINK'S LIFETIME · RETIRED LINKS KEEP THEIR ROW</span>
+ <span>${asOf != null ? `<button type="button" class="text-btn" data-sb-now>BACK TO NOW</button>` : `TODAY · ${esc(fmtDay(now))}`}</span>
</div>
</div>`;
};
// ----- the ledger ---------------------------------------------------
-const sideCol = (groups, side, ctx, label) => {
+const sideCol = (groups, side, ctx, caption, emptyLabel) => {
const inner = groups.length
? groups.map((g) => groupBlock(g, side, ctx)).join('')
- : `<div class="sb-sidenote mono faint">${esc(label)}</div>`;
- return `<div class="sb-col sb-col-${side}">${inner}</div>`;
+ : `<div class="sb-sidenote mono faint">${esc(emptyLabel)}</div>`;
+ return `<div class="sb-col sb-col-${side}">
+ <div class="sb-sidecap key">${esc(caption)}</div>
+ ${inner}
+ </div>`;
};
/** The three-column ego ledger + rails + scrubber. */
@@ -322,17 +373,18 @@ export const EgoLedger = ({ data }) => {
const sb = data.sb || {};
const ego = data.ego;
const asOf = sb.asOf ?? null;
+ const names = sb.names || {};
if (!ego) {
// Controls stay up even without a belief response so the user can
// switch brain / reset the caret out of a dead end.
return `
- ${EgoControls({ brain: data.brain, brains: sb.brains, focus: sb.focus, asOf, trail: sb.trail })}
- <div class="panel-empty mono faint">${sb.focus ? 'LOADING BELIEF · ' + esc(String(sb.focus).toUpperCase()) : 'NO FOCUS NODE · PICK A HUB BELOW TO OPEN THE LEDGER'}</div>`;
+ ${EgoControls({ brain: data.brain, brains: sb.brains, focus: sb.focus, asOf, trail: sb.trail, names })}
+ <div class="panel-empty mono faint">${sb.focus ? 'READING WHAT THE BRAIN BELIEVES ABOUT ' + esc(String(sb.focus).toUpperCase()) + '…' : 'NO NOTE IN FOCUS · CLICK ANY NOTE BELOW TO OPEN ITS LEDGER'}</div>`;
}
const nodes = ego.nodes || {};
const clipped = !!(ego.not_shown && ego.not_shown.edges_clipped > 0);
const counts = hop2Counts(ego.edges, asOf);
- const ctx = { nodes, counts, asOf, clipped };
+ const ctx = { nodes, names, counts, asOf, clipped };
const inGroups = groupEdges(ego.edges, 'in');
const outGroups = groupEdges(ego.edges, 'out');
const hop1 = (ego.edges || []).filter((e) => e.hop === 1);
@@ -340,94 +392,92 @@ export const EgoLedger = ({ data }) => {
const body = hop1.length
? `
<div class="sb-ledger" data-sb-ledger>
- ${sideCol(inGroups, 'in', ctx, 'NOTHING POINTS HERE AT THIS AS-OF')}
+ ${sideCol(inGroups, 'in', ctx, '← WHAT LINKS IN', 'NOTHING LINKS IN AT THIS MOMENT')}
<div class="sb-rail" data-sb-rail="in" aria-hidden="true"></div>
- ${FocusCard({ ego, nodes, brain: data.brain })}
+ ${FocusCard({ ego, nodes, names, brain: data.brain })}
<div class="sb-rail" data-sb-rail="out" aria-hidden="true"></div>
- ${sideCol(outGroups, 'out', ctx, 'THIS NODE POINTS AT NOTHING AT THIS AS-OF')}
+ ${sideCol(outGroups, 'out', ctx, 'WHERE IT LINKS OUT →', 'NO OUTBOUND LINKS AT THIS MOMENT')}
</div>`
: `
<div class="sb-ledger" data-sb-ledger>
<div class="sb-col sb-col-in"></div>
<div class="sb-rail" data-sb-rail="in" aria-hidden="true"></div>
- ${FocusCard({ ego, nodes, brain: data.brain })}
+ ${FocusCard({ ego, nodes, names, brain: data.brain })}
<div class="sb-rail" data-sb-rail="out" aria-hidden="true"></div>
<div class="sb-col sb-col-out"></div>
</div>
- <div class="panel-empty mono faint">NO EDGES TOUCH ${esc(ego.node.toUpperCase())} AT THIS AS-OF · SCRUB TO NOW OR PICK A HUB BELOW</div>`;
+ <div class="panel-empty mono faint">NO LINKS TOUCH THIS NOTE AT THIS MOMENT · DRAG BELIEF TIME BACK TO NOW, OR CLICK ANOTHER NOTE BELOW</div>`;
return `
- ${EgoControls({ brain: data.brain, brains: sb.brains, focus: ego.node, asOf, trail: sb.trail })}
+ ${EgoControls({ brain: data.brain, brains: sb.brains, focus: ego.node, asOf, trail: sb.trail, names, nodes })}
${body}
${BeliefScrubber({ timeline: sb.timeline, asOf })}`;
};
// ----- honesty panel ------------------------------------------------
-const hrow = (k, v, emph) => `
- <div class="sb-hrow">
+const hrow = (k, v, emph, rawName) => `
+ <div class="sb-hrow"${rawName ? ` title="API field: ${esc(rawName)}"` : ''}>
<span class="sb-hk">${esc(k)}</span>
<span class="sb-hv${emph && v !== '0' ? ' accent' : ''}">${esc(v)}</span>
</div>`;
/**
- * Definition list over every `not_shown` counter of both endpoints plus
- * the view's own caps. ALWAYS renders, zeros included — this panel
- * exists to prove absence, not just to report presence.
+ * Definition list over every `not_shown` counter of both endpoints
+ * plus the view's own caps — in user words (the raw API field name
+ * rides on hover). ALWAYS renders, zeros included — this panel exists
+ * to prove absence, not just to report presence.
*/
export const HonestyList = ({ data }) => {
const ns = (data.ego && data.ego.not_shown) || {};
const on = (data.overview && data.overview.not_shown) || {};
const z = (v) => num(v || 0);
const dangling = Array.isArray(ns.dangling_ids) && ns.dangling_ids.length
- ? `<div class="sb-hids mono faint">dangling: ${ns.dangling_ids.slice(0, 8).map(esc).join(', ')}${ns.dangling_ids.length > 8 ? ` +${ns.dangling_ids.length - 8} more` : ''}</div>`
+ ? `<div class="sb-hids mono faint">no document behind: ${ns.dangling_ids.slice(0, 8).map(esc).join(', ')}${ns.dangling_ids.length > 8 ? ` +${ns.dangling_ids.length - 8} more` : ''}</div>`
: '';
const timelineEdges = (data.sb && data.sb.timeline && data.sb.timeline.edges) || [];
const scrubHidden = Math.max(0, timelineEdges.length - SCRUB_ROW_CAP);
return `
<div class="sb-honesty mono">
- <div class="sb-hgroup key">EGO QUERY</div>
- ${hrow('edges clipped', z(ns.edges_clipped), true)}
- ${hrow('frontier clipped', z(ns.frontier_clipped), true)}
- ${hrow('expired excluded', z(ns.expired_excluded), false)}
- ${hrow('type filtered', z(ns.type_filtered), false)}
- ${hrow('segments without columns', z(ns.segments_without_columns), true)}
- ${hrow('memtable docs scanned', z(ns.memtable_docs_scanned), false)}
- ${hrow('dangling node refs', z(ns.dangling_nodes), true)}
+ <div class="sb-hgroup key">THE LEDGER READ</div>
+ ${hrow('links beyond the fetch cap (not drawn)', z(ns.edges_clipped), true, 'edges_clipped')}
+ ${hrow('start notes over the expansion cap', z(ns.frontier_clipped), true, 'frontier_clipped')}
+ ${hrow('links hidden by the belief-time cut', z(ns.expired_excluded), false, 'expired_excluded')}
+ ${hrow('links hidden by a kind filter', z(ns.type_filtered), false, 'type_filtered')}
+ ${hrow('storage segments this read had to skip', z(ns.segments_without_columns), true, 'segments_without_columns')}
+ ${hrow('unflushed writes checked (cost, not loss)', z(ns.memtable_docs_scanned), false, 'memtable_docs_scanned')}
+ ${hrow('links pointing at notes with no document', z(ns.dangling_nodes), true, 'dangling_nodes')}
${dangling}
- <div class="sb-hgroup key">OVERVIEW AGGS</div>
- ${hrow('types not listed', z(on.types_not_listed), true)}
- ${hrow('detectors not listed', z(on.detectors_not_listed), true)}
- ${hrow('hubs (out) not listed', z(on.hubs_out_not_listed), false)}
- ${hrow('hubs (in) not listed', z(on.hubs_in_not_listed), false)}
- <div class="sb-hgroup key">THIS VIEW</div>
+ <div class="sb-hgroup key">THE COUNTS ABOVE</div>
+ ${hrow('link kinds beyond the top list', z(on.types_not_listed), true, 'types_not_listed')}
+ ${hrow('detectors beyond the top list', z(on.detectors_not_listed), true, 'detectors_not_listed')}
+ ${hrow('most-citing notes beyond the top list', z(on.hubs_out_not_listed), false, 'hubs_out_not_listed')}
+ ${hrow('most-cited notes beyond the top list', z(on.hubs_in_not_listed), false, 'hubs_in_not_listed')}
+ <div class="sb-hgroup key">CAPS THIS PAGE APPLIES</div>
${hrow('ledger rows per group', `≤ ${num(LEDGER_GROUP_CAP)} (capped groups say so)`, false)}
- ${hrow('scrubber rows hidden', z(scrubHidden), false)}
+ ${hrow('belief-strip rows hidden', z(scrubHidden), false)}
</div>`;
};
-// ----- hubs ---------------------------------------------------------
+// ----- hubs (centers of gravity) ------------------------------------
-const hubList = (items, notListed, side, focus) => {
- if (!items || !items.length) return `<div class="faint mono">No hubs yet.</div>`;
+const hubList = (items, notListed, focus, ctx) => {
+ if (!items || !items.length) return `<div class="sb-sidenote mono faint">NOTHING RANKS YET</div>`;
const max = Math.max(...items.map((i) => i.live_edges), 1);
const rows = items.map((i) => {
const frac = Math.max(0, Math.min(1, i.live_edges / max));
return `
- <div class="row clickable${i.id === focus ? ' sb-hub-active' : ''}" data-sb-focus="${esc(i.id)}" role="button"
- title="Refocus the ledger on ${esc(i.id)}">
- <div class="row__label">${esc(i.id)}</div>
- <div class="row__val">${esc(num(i.live_edges))}</div>
- <div class="row__bar">
- <svg class="chart" height="6" viewBox="0 0 200 6" preserveAspectRatio="none">
- <line x1="0" y1="5" x2="${(frac * 200).toFixed(1)}" y2="5" stroke="currentColor" stroke-width="1"/>
- </svg>
- </div>
- <div class="row__pct">${side === 'out' ? 'out' : 'in'}</div>
+ <div class="sb-hubrow${i.id === focus ? ' sb-hub-active' : ''}" data-sb-focus="${esc(i.id)}" role="button" tabindex="0"
+ title="Open the ledger for ${esc(i.id)}">
+ <span class="sb-hubname">${esc(nodeName(i.id, ctx))}</span>
+ <span class="sb-hubn">${esc(num(i.live_edges))}</span>
+ <svg class="chart sb-hubbar" height="6" viewBox="0 0 100 6" preserveAspectRatio="none">
+ <line x1="0" y1="5" x2="${(frac * 100).toFixed(1)}" y2="5" stroke="currentColor" stroke-width="1"/>
+ </svg>
</div>`;
}).join('');
const tail = notListed > 0
- ? `<div class="hint">+ ${num(notListed)} more not listed</div>` : '';
+ ? `<div class="hint">+ ${num(notListed)} more beyond this list</div>` : '';
return rows + tail;
};
@@ -435,30 +485,114 @@ export const HubsPanel = ({ data }) => {
const o = data.overview || {};
const hubs = o.hubs || { out: [], in: [] };
const ns = o.not_shown || {};
- const focus = data.sb ? data.sb.focus : null;
+ const sb = data.sb || {};
+ const focus = sb.focus || null;
+ const ctx = { nodes: (data.ego && data.ego.nodes) || {}, names: sb.names || {} };
return `
<div class="sb-hubs">
<div>
- <div class="key">OUT · MOST ASSERTIVE</div>
- ${hubList(hubs.out, ns.hubs_out_not_listed, 'out', focus)}
+ <div class="key">MOST CITED · LINKS POINTING AT A NOTE</div>
+ ${hubList(hubs.in, ns.hubs_in_not_listed, focus, ctx)}
</div>
<div>
- <div class="key">IN · MOST CITED</div>
- ${hubList(hubs.in, ns.hubs_in_not_listed, 'in', focus)}
+ <div class="key">CITES THE MOST · LINKS A NOTE SENDS OUT</div>
+ ${hubList(hubs.out, ns.hubs_out_not_listed, focus, ctx)}
</div>
</div>
- <div class="hint" style="margin-top:var(--sp-1);">click a hub to refocus the ledger</div>`;
+ <div class="hint" style="margin-top:var(--sp-1);">click any note to open its ledger above</div>`;
};
// ----- small panels -------------------------------------------------
+/** 2-series comparison legend chip: a short 3px line in the series
+ * color + the number IN INK — color is identity, text is the value. */
+const legChip = (cls, label) =>
+ `<span class="sb-leg"><svg class="sb-legline ${cls}" width="14" height="4" viewBox="0 0 14 4" aria-hidden="true"><line x1="0" y1="2" x2="14" y2="2" stroke="currentColor" stroke-width="3"/></svg>${label}</span>`;
+
+/**
+ * BELIEVED NOW — headline number + the believed-vs-retired composition
+ * bar. The ONE two-series comparison on this page: accent (believed)
+ * against --z-cmp (retired), 2px surface gap, both directly labelled.
+ */
+const BelievedPanel = ({ data }) => {
+ const o = data.overview || {};
+ const ed = o.edges || { total: 0, live: 0, invalidated: 0 };
+ const m = (data.metrics && data.metrics.edgesLive) || { formatted: num(ed.live), hint: '' };
+ if (!ed.total) {
+ return Num({ value: '0', unit: 'links', hint: 'nothing asserted yet — see below', emphasis: true });
+ }
+ const W = 200;
+ const liveW = Math.round((ed.live / ed.total) * W);
+ const gap = ed.live > 0 && ed.invalidated > 0 ? 2 : 0;
+ const bar = `
+ <svg class="chart sb-split" width="100%" height="8" viewBox="0 0 ${W} 8" preserveAspectRatio="none" aria-hidden="true">
+ ${ed.live > 0 ? `<line class="sb-seg-live" x1="0" y1="4" x2="${liveW - gap}" y2="4" stroke="currentColor" stroke-width="3"/>` : ''}
+ ${ed.invalidated > 0 ? `<line class="sb-seg-retired" x1="${liveW + gap}" y1="4" x2="${W}" y2="4" stroke="currentColor" stroke-width="3"/>` : ''}
+ </svg>`;
+ return `
+ ${Num({ value: m.formatted, unit: 'links', hint: m.hint, emphasis: true })}
+ <div class="sb-splitwrap">
+ ${bar}
+ <div class="sb-splitleg mono">
+ ${legChip('sb-seg-live', `${num(ed.live)} BELIEVED`)}
+ ${legChip('sb-seg-retired', `${num(ed.invalidated)} RETIRED`)}
+ </div>
+ </div>`;
+};
+
+/** EVER ASSERTED — total + the growth shape (cumulative spark). */
+const AssertedPanel = ({ data }) => {
+ const o = data.overview || {};
+ const ed = o.edges || { total: 0 };
+ const m = (data.metrics && data.metrics.edgesTotal) || { formatted: num(ed.total || 0), hint: '' };
+ const buckets = o.created_over_time || [];
+ let run = 0;
+ const cumulative = buckets.map((b) => { run += (b.count || 0); return run; });
+ const spark = cumulative.length >= 2 ? Spark(cumulative, { w: 150, h: 30 }) : '';
+ return Num({ value: m.formatted, unit: 'links', spark, hint: m.hint, emphasis: false });
+};
+
+/** RETIRED — count + share of everything ever asserted. */
+const RetiredPanel = ({ data }) => {
+ const o = data.overview || {};
+ const ed = o.edges || { total: 0, invalidated: 0 };
+ const m = (data.metrics && data.metrics.invalidated) || { formatted: num(ed.invalidated || 0), hint: '' };
+ const share = ed.total > 0 ? `${((100 * ed.invalidated) / ed.total).toFixed(ed.invalidated ? 1 : 0)}% of all links` : '';
+ return `
+ ${Num({ value: m.formatted, unit: 'links', hint: m.hint, emphasis: false })}
+ ${share ? `<div class="hint" style="margin-top:6px;">${esc(share)} · never deleted, only retired</div>` : ''}`;
+};
+
+/** WHAT TAUGHT THIS BRAIN — the detectors as identity + magnitude
+ * rows (name · count · 1px bar), not a bare count. */
+const TaughtByPanel = ({ data }) => {
+ const o = data.overview || {};
+ const dets = o.detectors || [];
+ if (!dets.length) return `<div class="panel-empty mono faint">NO DETECTOR HAS RUN YET</div>`;
+ const shown = dets.slice(0, 4);
+ const max = Math.max(...shown.map((d) => d.live), 1);
+ const rows = shown.map((d) => `
+ <div class="sb-det">
+ <span class="sb-detname" title="deterministic detector ${esc(d.detector)} — same folder in, same links out">${esc(d.detector)}</span>
+ <span class="sb-detn">${esc(num(d.live))}</span>
+ <svg class="chart sb-hubbar" height="6" viewBox="0 0 100 6" preserveAspectRatio="none">
+ <line x1="0" y1="5" x2="${((d.live / max) * 100).toFixed(1)}" y2="5" stroke="currentColor" stroke-width="1"/>
+ </svg>
+ </div>`).join('');
+ const notListed = (o.not_shown && o.not_shown.detectors_not_listed) || 0;
+ const tail = (dets.length > 4 || notListed > 0)
+ ? `<div class="hint">+ ${num(Math.max(0, dets.length - 4) + notListed)} more</div>` : '';
+ return `<div class="sb-dets">${rows}${tail}</div>
+ <div class="hint" style="margin-top:6px;">deterministic · versioned · no LLM</div>`;
+};
+
const TypeDistPanel = ({ data }) => {
const o = data.overview || {};
const types = o.types || [];
- if (!types.length) return `<div class="panel-empty mono faint">NO LIVE EDGES AT THIS AS-OF</div>`;
+ if (!types.length) return `<div class="panel-empty mono faint">NO LINKS AT THIS MOMENT</div>`;
const tail = o.not_shown && o.not_shown.types_not_listed > 0
- ? `<div class="hint">+ ${num(o.not_shown.types_not_listed)} types not listed</div>` : '';
- return Dist({ segments: types.map((t) => ({ label: t.type, value: t.live })) }) + tail;
+ ? `<div class="hint">+ ${num(o.not_shown.types_not_listed)} kinds beyond this list</div>` : '';
+ return Dist({ segments: types.map((t) => ({ label: typeName(t.type), value: t.live })) }) + tail;
};
const TimelinePanel = ({ data }) => {
@@ -472,28 +606,17 @@ const TimelinePanel = ({ data }) => {
: (o.embedder ? `<div class="hint" style="margin-top:var(--sp-1);">embedder · ${esc(o.embedder)}</div>` : '');
if (series.length < 2) {
const one = series.length === 1
- ? `<div class="mono">${esc(num(series[0]))} edges asserted · ${esc(fmtDay(ts[0]))}</div>` : '';
- return `${one || '<div class="panel-empty mono faint">NO ASSERTIONS RECORDED YET</div>'}${embedderNote}`;
+ ? `<div class="mono">${esc(num(series[0]))} link${series[0] === 1 ? '' : 's'} · all asserted ${esc(fmtDay(ts[0]))}</div>` : '';
+ return `${one || '<div class="panel-empty mono faint">EACH DAY’S NEW LINKS WILL DRAW HERE</div>'}${embedderNote}`;
}
return Series(series, {
h: 120,
labels: [fmtDay(ts[0]), fmtDay(ts[ts.length - 1])],
- unit: 'edges',
+ unit: 'links',
}) + embedderNote;
};
-const metricPanel = (data, id) => {
- const m = data.metrics && data.metrics[id];
- if (!m) return `<div class="panel-empty mono faint">—</div>`;
- return Num({
- value: m.formatted,
- unit: id === 'detectors' ? 'active' : 'edges',
- hint: m.hint,
- emphasis: id === 'edgesLive',
- });
-};
-
-// ----- empty / disconnected states ---------------------------------
+// ----- empty / error / disconnected states -------------------------
/**
* The dashboard reads the LIVE graph endpoints only — no demo numbers.
@@ -501,32 +624,46 @@ const metricPanel = (data, id) => {
*/
const LiveOnlyNote = () => `
<div class="sb-empty">
- <div class="mono">THIS DASHBOARD READS THE LIVE ENGINE · IT NEVER SHOWS DEMO DATA</div>
+ <div class="mono">THIS PAGE READS THE LIVE ENGINE · IT NEVER INVENTS A BRAIN</div>
<div class="mono faint" style="margin-top:var(--sp-1);">start xerj, point the console at it (SETTINGS → BACKEND · XERJ), reload</div>
</div>`;
-/** A brand-new brain: tell the user exactly how to fill it. */
+/** Overview failed on a real brain: say so — never render zeros as truth. */
+const BrainErrorNote = ({ brain, reason }) => `
+ <div class="sb-empty">
+ <div class="sb-ftitle">COULD NOT READ THIS BRAIN</div>
+ <p class="sb-ftext">The engine answered, but the graph overview for
+ <span class="mono">${esc(brain || '—')}</span> failed. Nothing on this page is a guess —
+ so nothing is shown.</p>
+ <div class="mono faint" style="margin:var(--sp-1) 0;">${esc(String(reason || 'unknown error').slice(0, 140))}</div>
+ <button type="button" class="text-btn" data-sb-retry>RETRY</button>
+ </div>`;
+
+/** A brand-new brain: the ONE command that fills it, copyable. */
export const EmptyBrainNote = ({ brain, connected, error }) => {
if (!connected) {
return `
<div class="sb-empty">
- <div class="mono">ENGINE UNREACHABLE${error ? ` · ${esc(String(error).slice(0, 80).toUpperCase())}` : ''}</div>
- <div class="mono faint" style="margin-top:var(--sp-1);">start xerj and reload — this dashboard reads the live graph API only</div>
+ <div class="sb-ftitle">ENGINE UNREACHABLE</div>
+ ${error ? `<div class="mono faint" style="margin:var(--sp-1) 0;">${esc(String(error).slice(0, 120))}</div>` : ''}
+ <p class="sb-ftext">This page reads the live graph API only — it never shows demo data.
+ Start xerj, then reload:</p>
+ <div class="sb-cmdrow"><pre class="sb-cmd mono" data-sb-cmd>xerj</pre><button type="button" class="text-btn" data-sb-copy>COPY</button></div>
</div>`;
}
const b = brain || 'notes';
return `
<div class="sb-empty">
- <div class="sb-ftitle">THIS BRAIN IS EMPTY</div>
- <p class="sb-ftext">No edges yet. A second brain grows from documents you already have —
- point the deterministic detectors at any folder and every wiki-link, relative link and
- file adjacency becomes an edge with evidence:</p>
- <pre class="sb-cmd mono">xerj autoindex ~/notes --brain ${esc(b)}</pre>
- <p class="sb-ftext">or assert the first edge yourself:</p>
- <pre class="sb-cmd mono">curl -X POST localhost:9200/_graph/${esc(b)}/link \\
- -H 'content-type: application/json' \\
- -d '{"src":"note-a","dst":"note-b","type":"cites"}'</pre>
- <div class="mono faint">then reload — the ledger, hubs and belief-time strip fill themselves</div>
+ <div class="sb-ftitle">THIS BRAIN IS EMPTY — ONE COMMAND FILLS IT</div>
+ <p class="sb-ftext">Point it at a folder of notes, docs or exports. Every wiki-link,
+ relative link, reading sequence and folder neighborhood becomes a link that
+ remembers the exact quote that taught it — then this page turns into a ledger
+ of what your notes believe, replayable at any moment in time.</p>
+ <div class="sb-cmdrow"><pre class="sb-cmd mono" data-sb-cmd>xerj brain ~/${esc(b)}</pre><button type="button" class="text-btn" data-sb-copy>COPY</button></div>
+ <p class="sb-ftext">Detection is deterministic — the same folder always produces the same
+ brain, and re-running only picks up what changed. Agents can assert links of
+ their own through the graph API once there is something to build on.</p>
+ <div class="mono faint">no upload · runs local · nothing is ever hard-deleted</div>
</div>`;
};
@@ -542,23 +679,37 @@ export function renderPanelBody(id, data) {
const sb = data.sb;
const hasBrain = !!(data.overview && data.overview.exists !== false);
const hasEdges = hasBrain && data.overview.edges && data.overview.edges.total > 0;
+ const broken = !!sb.overviewError && sb.connected; // engine up, brain unreadable
+
+ if (broken) {
+ // An error is not an empty brain: never render teaching copy or
+ // zero-metrics over a failed read.
+ switch (id) {
+ case 'ego': return BrainErrorNote({ brain: data.brain, reason: sb.overviewError });
+ case 'notShown': return HonestyList({ data });
+ default: return `<div class="panel-empty mono faint">COULD NOT READ THIS BRAIN · SEE THE LEDGER PANEL</div>`;
+ }
+ }
switch (id) {
case 'edgesLive':
+ return hasBrain ? BelievedPanel({ data }) : `<div class="panel-empty mono faint">NO BRAIN YET · SEE BELOW</div>`;
case 'edgesTotal':
+ return hasBrain ? AssertedPanel({ data }) : `<div class="panel-empty mono faint">—</div>`;
case 'invalidated':
+ return hasBrain ? RetiredPanel({ data }) : `<div class="panel-empty mono faint">—</div>`;
case 'detectors':
- return metricPanel(data, id);
+ return hasBrain ? TaughtByPanel({ data }) : `<div class="panel-empty mono faint">—</div>`;
case 'typeDist':
- return hasEdges ? TypeDistPanel({ data }) : `<div class="panel-empty mono faint">NO EDGE TYPES YET</div>`;
+ return hasEdges ? TypeDistPanel({ data }) : `<div class="panel-empty mono faint">LINK KINDS RANK HERE · WIKI-LINKS, FOLDER NEIGHBORS, READING ORDER…</div>`;
case 'edgeTimeline':
- return hasEdges ? TimelinePanel({ data }) : `<div class="panel-empty mono faint">NO ASSERTIONS YET</div>`;
+ return hasEdges ? TimelinePanel({ data }) : `<div class="panel-empty mono faint">EACH DAY’S NEW LINKS WILL DRAW HERE</div>`;
case 'ego':
return hasEdges
? EgoLedger({ data })
: EmptyBrainNote({ brain: data.brain, connected: sb.connected, error: sb.error });
case 'hubs':
- return hasEdges ? HubsPanel({ data }) : `<div class="panel-empty mono faint">NO HUBS YET</div>`;
+ return hasEdges ? HubsPanel({ data }) : `<div class="panel-empty mono faint">YOUR MOST-CITED NOTES WILL RANK HERE</div>`;
case 'notShown':
// Always renders — zeros prove absence.
return HonestyList({ data });
diff --git a/xerj-ux/src/ux/text.js b/xerj-ux/src/ux/text.js
index 4521edeae..dc606dc96 100644
--- a/xerj-ux/src/ux/text.js
+++ b/xerj-ux/src/ux/text.js
@@ -15,6 +15,8 @@ const nf = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDig
export const fmt = (v, { decimals } = {}) => {
if (v == null || Number.isNaN(v)) return '—';
if (decimals != null) return Number(v).toFixed(decimals);
+ // Exact integers stay integers — a count of 4 must never read "4.0".
+ if (Number.isInteger(v) && Math.abs(v) < 10_000) return new Intl.NumberFormat('en').format(v);
if (Math.abs(v) < 1) return Number(v).toFixed(2);
if (Math.abs(v) < 100) return Number(v).toFixed(1);
return nf.format(v);