AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(memory): explain a flood-stage write block in plain text (#2284) (#2290)
xerj-org13ee3d0b31e7
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 8fb6cfc37..b5dc3a1a9 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -35546,6 +35546,9 @@ pub async fn cat_allocation("host": "127.0.0.1","ip": "127.0.0.1","node": "xerj-node-1",+ // #2284: memory writes name this directory when the flood-stage+ // block fires. Not a cat column — the text table below is unchanged.+ "path.data": state.config.server.data_dir,});// #2077: effective flood-stage gate, so autoindex can refuse before// it walks. Not cat columns — the text table below is unchanged.diff --git a/engine/crates/xerj-api/src/memory_api.rs b/engine/crates/xerj-api/src/memory_api.rsindex 22f67c4e0..ef5bd28a7 100644--- a/engine/crates/xerj-api/src/memory_api.rs+++ b/engine/crates/xerj-api/src/memory_api.rs@@ -144,6 +144,48 @@ pub(crate) fn validate_namespace(ns: &str) -> Result<(), String> {Ok(())}+/// A memory write that failed because the data-dir disk is at the flood-stage+/// watermark (#2284).+///+/// The document API answers that with a `cluster_block_exception`, and this+/// module used to stringify that JSON into `error.reason` — the nested blob+/// the CLI and MCP showed. The replacement is the same sentence autoindex+/// prints for the watermark (#2077): free space, used percent, threshold,+/// and the `limits.disk_flood_stage_percent` override — plus the data-dir+/// path and the `--data-dir` move. Any other failure keeps `wrapped`.+fn memory_failure(status: StatusCode, body: &Value, data_dir: &str, wrapped: String) -> Response {+ error_response(status, memory_failure_reason(body, data_dir, &wrapped))+}++fn memory_failure_reason(body: &Value, data_dir: &str, wrapped: &str) -> String {+ let (free, used_live) = disk_sample(data_dir);+ let flood_live = xerj_engine::governor::global().and_then(|governor| {+ let pct = governor.disk_flood_admission().flood_pct;+ (pct > 0).then_some(pct)+ });+ let facts = xerj_autoindex::flood::DiskFacts {+ data_dir: data_dir.to_string(),+ free_bytes: free,+ used_pct: used_live,+ flood_pct: flood_live,+ };+ xerj_autoindex::flood::explain_memory_flood(body, Some(&facts))+ .unwrap_or_else(|| wrapped.to_string())+}++/// `(free bytes, used percent)` for the filesystem holding `data_dir`.+/// `None` when the probe fails — the message then says unknown, it does not+/// invent a zero.+fn disk_sample(data_dir: &str) -> (Option<u64>, Option<u64>) {+ match xerj_engine::governor::disk_stats(data_dir) {+ Some((total, avail)) if total > 0 => {+ let used = ((total.saturating_sub(avail) as u128 * 100) / total as u128) as u64;+ (Some(avail), Some(used))+ }+ _ => (None, None),+ }+}+/// Emit a uniform ES-shaped error response.fn error_response(status: StatusCode, reason: impl Into<String>) -> Response {(@@ -251,8 +293,10 @@ async fn ensure_backing_index(if status.is_success() || index_exists(state, index) {return Ok(());}- Err(error_response(+ Err(memory_failure(status,+ &body,+ &state.config.server.data_dir,format!("failed to create memory namespace backing index: {body}"),))}@@ -425,7 +469,14 @@ pub async fn store(let (status, body) = drain_json(resp).await;if !status.is_success() {- return error_response(status, format!("failed to store memory: {body}"));+ // #2284: a flood-stage block arrives as a nested+ // `cluster_block_exception`. Say the disk is nearly full instead.+ return memory_failure(+ status,+ &body,+ &state.config.server.data_dir,+ format!("failed to store memory: {body}"),+ );}(@@ -1521,7 +1572,12 @@ pub async fn forget_one(.into_response();}if !status.is_success() {- return error_response(status, format!("forget failed: {body}"));+ return memory_failure(+ status,+ &body,+ &state.config.server.data_dir,+ format!("forget failed: {body}"),+ );}Json(json!({ "id": id, "namespace": namespace, "forgotten": true })).into_response()}@@ -1627,6 +1683,54 @@ mod tests {);}+ /// #2284: the flood-stage block is a nested `cluster_block_exception`+ /// inside `failed to store memory: {json}`. The reason the CLI and MCP+ /// print is the disk sentence, with this process's free space and the+ /// data-dir path. A mapping error stays the raw body.+ #[test]+ fn a_flood_stage_store_failure_names_the_disk_and_the_data_dir() {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().to_string_lossy();+ let inner = crate::error::ApiError::new(xerj_common::XerjError::index_blocked(+ ".xerj-memory-notes",+ "read_only_allow_delete (disk usage 96% exceeded flood-stage watermark [95%])",+ ))+ .into_value();+ let wrapped_body = json!({+ "error": {+ "type": "memory_error",+ "reason": format!("failed to store memory: {inner}")+ },+ "status": 429+ });+ let unused = "failed to store memory: {raw}".to_string();+ let reason = memory_failure_reason(&wrapped_body, &path, &unused);+ assert!(+ reason.contains("the disk holding the data dir is nearly full"),+ "{reason}"+ );+ assert!(reason.contains("96% used"), "{reason}");+ assert!(reason.contains("threshold 95%"), "{reason}");+ assert!(reason.contains(path.as_ref()), "{reason}");+ assert!(+ reason.contains("Free space on that drive, or restart the node with --data-dir"),+ "{reason}"+ );+ assert!(+ reason.contains("limits.disk_flood_stage_percent"),+ "{reason}"+ );+ assert!(!reason.contains("cluster_block_exception"), "{reason}");+ assert!(reason.contains("free "), "{reason}");+ assert!(!reason.contains("free unknown"), "{reason}");++ let other = json!({+ "error": { "type": "mapper_parsing_exception", "reason": "bad field" }+ });+ let wrapped = format!("failed to store memory: {other}");+ assert_eq!(memory_failure_reason(&other, &path, &wrapped), wrapped);+ }+#[tokio::test]async fn store_recall_vector_topk_and_isolation() {let state = test_state();diff --git a/engine/crates/xerj-api/tests/flood_stage_allocation.rs b/engine/crates/xerj-api/tests/flood_stage_allocation.rsindex 466f9c798..d86e48c6f 100644--- a/engine/crates/xerj-api/tests/flood_stage_allocation.rs+++ b/engine/crates/xerj-api/tests/flood_stage_allocation.rs@@ -60,6 +60,12 @@ async fn allocation_json_reports_the_flood_stage_gate_and_text_does_not() {.parse().expect("integer percent");assert!(percent <= 100, "{percent}");+ let data_dir = _dir.path().to_string_lossy().into_owned();+ assert_eq!(+ row["path.data"].as_str(),+ Some(data_dir.as_str()),+ "memory writes name this directory when the flood-stage block fires: {row}"+ );let response = app.oneshot(diff --git a/engine/crates/xerj-autoindex/src/flood.rs b/engine/crates/xerj-autoindex/src/flood.rsindex 3ae8ececa..c466f0ade 100644--- a/engine/crates/xerj-autoindex/src/flood.rs+++ b/engine/crates/xerj-autoindex/src/flood.rs@@ -13,6 +13,13 @@//! or the HTTP doubles in this crate's tests) is not guessed at. Those runs//! behave as they did before: the write itself still reports the block if one//! engages later.+//!+//! Memory writes (#2284) hit the same watermark later, as a nested+//! `cluster_block_exception`, because `/_memory` stringifies the document+//! error. [`explain_memory_flood`] turns that body into the same kind of+//! sentence this module already prints for autoindex: free space, the+//! threshold, and the config override — plus the data-dir path and the+//! `--data-dir` move, which is the recovery the memory field report needed.use serde_json::Value;@@ -178,6 +185,173 @@ fn parse_bool(value: &Value) -> Option<bool> {}}+/// How a memory-write error body relates to the flood-stage block.+#[derive(Debug, Clone, PartialEq, Eq)]+enum MemoryFloodClass {+ /// Some other failure. The caller keeps its existing error text.+ Other,+ /// The node already replaced the nested exception with the plain sentence.+ Plain(String),+ /// Raw `cluster_block_exception` for the flood-stage block. Percents are+ /// taken from the reason when it names them (`disk usage 96% exceeded+ /// flood-stage watermark [95%]`).+ Raw {+ used_pct: Option<u64>,+ flood_pct: Option<u8>,+ },+}++/// Disk facts a memory-write client can attach to the plain sentence.+///+/// The server fills these from `statvfs` on its data dir. A client that only+/// has `GET /_cat/allocation?format=json` fills them with+/// [`disk_facts_from_allocation`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DiskFacts {+ pub data_dir: String,+ pub free_bytes: Option<u64>,+ pub used_pct: Option<u64>,+ pub flood_pct: Option<u8>,+}++/// `Some` when `body` is a flood-stage write refusal.+///+/// `Plain` is returned unchanged (the server already explained it). A raw+/// nested `cluster_block_exception` is rewritten with `facts`: error-text+/// percents win over `facts`, because those are the numbers the block used.+/// `None` means this is not that block — an explicit `index.blocks.write`,+/// a mapping error, a validation 400 — and the caller must not claim the+/// disk is full.+pub fn explain_memory_flood(body: &Value, facts: Option<&DiskFacts>) -> Option<String> {+ match classify_memory_flood(body) {+ MemoryFloodClass::Other => None,+ MemoryFloodClass::Plain(text) => Some(text),+ MemoryFloodClass::Raw {+ used_pct,+ flood_pct,+ } => {+ let facts = facts.cloned().unwrap_or(DiskFacts {+ data_dir: String::new(),+ free_bytes: None,+ used_pct: None,+ flood_pct: None,+ });+ Some(memory_flood_stage_message(+ &facts.data_dir,+ facts.free_bytes,+ used_pct.or(facts.used_pct),+ flood_pct.or(facts.flood_pct),+ ))+ }+ }+}++/// The sentence memory writes show instead of a nested `cluster_block_exception`.+///+/// Same free-space scale and the same `limits.disk_flood_stage_percent` /+/// `PUT /_cluster/settings` recovery as the autoindex refusal (#2077, #823).+/// `data_dir` empty is printed as unknown rather than omitted: the field+/// report's fix was moving that directory to another drive.+pub fn memory_flood_stage_message(+ data_dir: &str,+ free_bytes: Option<u64>,+ used_pct: Option<u64>,+ flood_pct: Option<u8>,+) -> String {+ let free = match free_bytes {+ Some(bytes) => format_bytes(bytes),+ None => "unknown".to_string(),+ };+ let used = match used_pct {+ Some(pct) => format!("{pct}% used"),+ None => "used percent unknown".to_string(),+ };+ let flood = match flood_pct {+ Some(pct) => format!("threshold {pct}%"),+ None => "threshold unknown".to_string(),+ };+ let dir = if data_dir.is_empty() {+ "unknown"+ } else {+ data_dir+ };+ // Hysteresis (#823): the block stays latched for 1% under the threshold.+ // The disk is still the reason; say the block has not released yet.+ let held = match (used_pct, flood_pct) {+ (Some(used), Some(flood)) if used < u64::from(flood) => {+ " The disk flood-stage write block is still engaged."+ }+ _ => "",+ };+ format!(+ "the disk holding the data dir is nearly full, so this memory write was refused \+ (free {free}, {used}, {flood}, data dir {dir}).{held} \+ Free space on that drive, or restart the node with --data-dir on another drive. \+ Set limits.disk_flood_stage_percent above the used percent in the node config and \+ restart (0 disables the watermark), or raise it live with \+ PUT /_cluster/settings {{\"persistent\":{{\"cluster.routing.allocation.disk.watermark.flood_stage\":\"<percent>\"}}}}."+ )+}++/// `path.data`, `disk.avail`, `disk.percent`, and `disk.flood_stage` from one+/// allocation body. Missing columns stay empty; this does not invent a+/// threshold the node left out.+pub fn disk_facts_from_allocation(body: &Value) -> DiskFacts {+ let row = body.as_array().and_then(|rows| rows.first());+ let data_dir = row+ .and_then(|row| row.get("path.data"))+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ let volume = volume_from_allocation(body);+ DiskFacts {+ data_dir,+ free_bytes: volume.and_then(|v| v.avail),+ used_pct: volume.and_then(|v| v.used_percent),+ flood_pct: volume.and_then(|v| v.flood_stage),+ }+}++fn classify_memory_flood(body: &Value) -> MemoryFloodClass {+ if let Some(reason) = body.pointer("/error/reason").and_then(Value::as_str) {+ if reason.contains("the disk holding the data dir is nearly full") {+ return MemoryFloodClass::Plain(reason.to_string());+ }+ }+ // `Value`'s JSON keeps the words even when `/_memory` has stringified the+ // inner `cluster_block_exception` into `error.reason`.+ let flat = body.to_string();+ if flat.contains("cluster_block_exception")+ && flat.contains("read_only_allow_delete")+ && (flat.contains("flood-stage") || flat.contains("flood_stage"))+ {+ let (used_pct, flood_pct) = percents_from_flood_text(&flat);+ return MemoryFloodClass::Raw {+ used_pct,+ flood_pct,+ };+ }+ MemoryFloodClass::Other+}++/// `disk usage 96% exceeded flood-stage watermark [95%]` — the governor's+/// block reason. Absent on a block that only names `read_only_allow_delete`.+fn percents_from_flood_text(text: &str) -> (Option<u64>, Option<u8>) {+ let used = text.split("disk usage ").nth(1).and_then(|rest| {+ let num = rest.split('%').next()?.trim();+ num.parse().ok()+ });+ let flood = text+ .split("flood-stage watermark [")+ .nth(1)+ .and_then(|rest| {+ let num = rest.split(['%', ']']).next()?.trim();+ let n: u64 = num.parse().ok()?;+ u8::try_from(n.min(100)).ok()+ });+ (used, flood)+}+/// `/_cat/allocation` emits free space as a raw byte count with a `b` suffix/// (`"2147483648b"`). Anything else is left unknown rather than guessed.fn parse_bytes(value: &Value) -> Option<u64> {@@ -290,6 +464,148 @@ mod tests {assert!(volume_from_allocation(&json!({"acknowledged": true})).is_none());}+ fn nested_flood_body() -> Value {+ // The shape `/_memory` used to return: the document error JSON+ // stringified into `error.reason`, so the agent saw only+ // `cluster_block_exception`.+ let inner = json!({+ "error": {+ "root_cause": [{+ "type": "cluster_block_exception",+ "reason": "index [.xerj-memory-notes] is blocked for read_only_allow_delete (disk usage 96% exceeded flood-stage watermark [95%]) operations"+ }],+ "type": "cluster_block_exception",+ "reason": "index [.xerj-memory-notes] is blocked for read_only_allow_delete (disk usage 96% exceeded flood-stage watermark [95%]) operations"+ },+ "status": 429+ });+ json!({+ "error": {+ "type": "memory_error",+ "reason": format!("failed to store memory: {inner}")+ },+ "status": 429+ })+ }++ #[test]+ fn a_nested_flood_stage_block_becomes_the_plain_disk_sentence() {+ let facts = DiskFacts {+ data_dir: "D:\\xerj-data".to_string(),+ free_bytes: Some(2 * 1024 * 1024 * 1024),+ used_pct: None,+ flood_pct: None,+ };+ let message = explain_memory_flood(&nested_flood_body(), Some(&facts))+ .expect("the nested cluster_block_exception is the flood-stage block");+ assert!(+ message.contains("the disk holding the data dir is nearly full"),+ "{message}"+ );+ assert!(message.contains("free 2.0gb"), "{message}");+ assert!(message.contains("96% used"), "{message}");+ assert!(message.contains("threshold 95%"), "{message}");+ assert!(message.contains("data dir D:\\xerj-data"), "{message}");+ assert!(+ message.contains("restart the node with --data-dir on another drive"),+ "{message}"+ );+ assert!(+ message.contains("limits.disk_flood_stage_percent"),+ "{message}"+ );+ assert!(+ message.contains("cluster.routing.allocation.disk.watermark.flood_stage"),+ "{message}"+ );+ assert!(!message.contains("cluster_block_exception"), "{message}");++ // The sentence, once written, is not composed again.+ let already = json!({+ "error": { "type": "memory_error", "reason": message }+ });+ assert_eq!(+ explain_memory_flood(&already, None).as_deref(),+ Some(already["error"]["reason"].as_str().unwrap())+ );+ }++ #[test]+ fn an_explicit_write_block_is_not_called_a_full_disk() {+ let write = json!({+ "error": {+ "type": "cluster_block_exception",+ "reason": "index [notes] is blocked for write operations"+ },+ "status": 403+ });+ assert!(explain_memory_flood(&write, None).is_none());++ // `read_only_allow_delete` set by the block API, with no flood-stage+ // wording, is that block — not a guess that the disk is full.+ let manual = json!({+ "error": {+ "type": "cluster_block_exception",+ "reason": "index [notes] is blocked for read_only_allow_delete operations"+ },+ "status": 429+ });+ assert!(explain_memory_flood(&manual, None).is_none());+ }++ #[test]+ fn allocation_supplies_the_path_and_free_space_the_error_omits() {+ let body = json!({+ "error": {+ "type": "cluster_block_exception",+ "reason": "index [n] is blocked for read_only_allow_delete (disk usage 96% exceeded flood-stage watermark [95%]) operations"+ }+ });+ let facts = disk_facts_from_allocation(&json!([{+ "disk.percent": "96",+ "disk.avail": "2147483648b",+ "disk.flood_stage": "95",+ "path.data": "/var/lib/xerj"+ }]));+ assert_eq!(facts.data_dir, "/var/lib/xerj");+ assert_eq!(facts.free_bytes, Some(2 * 1024 * 1024 * 1024));+ let message = explain_memory_flood(&body, Some(&facts)).unwrap();+ assert!(message.contains("data dir /var/lib/xerj"), "{message}");+ assert!(message.contains("free 2.0gb"), "{message}");++ // No allocation and no percents in a flood reason still explains,+ // with the unknowns named rather than invented.+ let bare = json!({+ "error": {+ "type": "cluster_block_exception",+ "reason": "read_only_allow_delete flood-stage"+ }+ });+ let message = explain_memory_flood(&bare, None).unwrap();+ assert!(message.contains("free unknown"), "{message}");+ assert!(message.contains("data dir unknown"), "{message}");+ assert!(message.contains("--data-dir"), "{message}");+ }++ #[test]+ fn a_block_still_engaged_under_the_threshold_says_so() {+ let body = json!({+ "error": {+ "type": "cluster_block_exception",+ "reason": "index [n] is blocked for read_only_allow_delete (disk usage 94% exceeded flood-stage watermark [95%]) operations"+ }+ });+ let message = explain_memory_flood(&body, None).unwrap();+ assert!(+ message.contains("The disk flood-stage write block is still engaged."),+ "{message}"+ );+ assert!(+ message.contains("the disk holding the data dir is nearly full"),+ "{message}"+ );+ }+/// The probe runs before the walk: a flooded node refuses with the/// override text and never opens the folder, and a healthy node is not/// refused (the walk then reports that the root is a file).diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex f6e9d44fb..8db1490b4 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -17,7 +17,7 @@ pub mod esclient;pub mod estimate;pub mod extract;pub mod feedback;-mod flood;+pub mod flood;pub mod gain;pub mod gate;mod generation_catalog;@@ -32,6 +32,7 @@ pub mod infer;pub mod init;/// `--label`: ingest-time labelling through the node's `/_decide` (#1062).pub mod label;+pub mod memory_cli;pub mod objsource;#[cfg(test)]mod objsource_minio_tests;diff --git a/engine/crates/xerj-autoindex/src/memory_cli.rs b/engine/crates/xerj-autoindex/src/memory_cli.rsnew file mode 100644index 000000000..74feb701b--- /dev/null+++ b/engine/crates/xerj-autoindex/src/memory_cli.rs@@ -0,0 +1,201 @@+//! `xerj memory store` — one agent memory, on a node that is already running.+//!+//! A flood-stage write block used to come back as a nested+//! `cluster_block_exception` (#2284). This command prints the plain sentence+//! from [`crate::flood::explain_memory_flood`]: the disk holding the data dir+//! is nearly full, the free space, the path, and what to do.++use serde_json::{json, Value};++use crate::esclient::Es;+use crate::flood::{disk_facts_from_allocation, explain_memory_flood, DiskFacts};++const USAGE: &str = "\+xerj memory — store one agent memory on a running XERJ node++USAGE:+ xerj memory store <namespace> --text <text>++OPTIONS:+ --url <U> node endpoint (default $XERJ_URL or http://localhost:9200)+ --api-key <K> API key (or $XERJ_API_KEY; a loopback node falls back to <data-dir>/admin.key)+ --text <text> the memory to store+ --id <id> optional explicit id+ --json print the raw response body on success++A disk flood-stage write block is explained in plain text: free space, the+data-dir path, and whether to free space or restart with --data-dir on+another drive. Other errors are the server's own reason.++EXAMPLE:+ xerj --insecure --data-dir ./xerj-data &+ xerj memory store agent-ada --text \"the user prefers dark mode\"+";++/// Entry point for the `memory` subcommand. Returns a process exit code.+pub fn run_memory_cli() -> i32 {+ run_memory_from(&xerj_common::argv::args_after_subcommand())+}++pub fn run_memory_from(args: &[String]) -> i32 {+ if args.is_empty() || args.iter().any(|a| a == "-h" || a == "--help") {+ print!("{USAGE}");+ return 0;+ }+ let Some(verb) = args.first() else {+ print!("{USAGE}");+ return 0;+ };+ if verb != "store" {+ eprintln!("xerj memory: unknown command '{verb}'\n\n{USAGE}");+ return 2;+ }++ let mut url = std::env::var("XERJ_URL")+ .ok()+ .filter(|s| !s.is_empty())+ .unwrap_or_default();+ let mut api_key = std::env::var("XERJ_API_KEY").ok().filter(|s| !s.is_empty());+ let mut namespace: Option<String> = None;+ let mut text: Option<String> = None;+ let mut id: Option<String> = None;+ let mut as_json = false;++ let mut it = args.iter().skip(1).cloned();+ while let Some(arg) = it.next() {+ match arg.as_str() {+ "--url" => url = it.next().unwrap_or_default(),+ "--api-key" => api_key = it.next(),+ "--text" => text = it.next(),+ "--id" => id = it.next(),+ "--json" => as_json = true,+ "--disable-feedback" => {}+ other if other.starts_with('-') => {+ eprintln!("xerj memory: unexpected argument '{other}'\n\n{USAGE}");+ return 2;+ }+ other if namespace.is_none() => namespace = Some(other.to_string()),+ other => {+ eprintln!("xerj memory: unexpected argument '{other}'\n\n{USAGE}");+ return 2;+ }+ }+ }++ let namespace = match namespace {+ Some(ns) if !ns.trim().is_empty() => ns,+ _ => {+ eprintln!("xerj memory: a namespace is required.\n\n{USAGE}");+ return 2;+ }+ };+ let text = match text {+ Some(text) if !text.is_empty() => text,+ _ => {+ eprintln!("xerj memory: --text is required.\n\n{USAGE}");+ return 2;+ }+ };+ if url.is_empty() {+ url = "http://localhost:9200".to_string();+ }+ if api_key.is_none() && xerj_common::localauth::url_is_loopback(&url) {+ if let Some((key, path)) = xerj_common::localauth::discover_local_admin_key_for_url(&url) {+ eprintln!(+ "xerj memory: no --api-key/XERJ_API_KEY given; using the admin key at {}",+ path.display()+ );+ api_key = Some(key);+ }+ }++ let es = match Es::new(&url, api_key) {+ Ok(es) => es,+ Err(error) => {+ eprintln!("xerj memory: {error}");+ return 1;+ }+ };+ let mut payload = json!({ "text": text });+ if let Some(id) = id {+ payload["id"] = json!(id);+ }+ let path = format!("/_memory/{namespace}");+ let (status, body) = match es.request_json("POST", &path, Some(&payload)) {+ Ok(pair) => pair,+ Err(error) => {+ eprintln!("xerj memory: {error}");+ return 1;+ }+ };+ if (200..300).contains(&status) {+ if as_json {+ println!(+ "{}",+ serde_json::to_string(&body).unwrap_or_else(|_| body.to_string())+ );+ } else if let Some(id) = body.get("id").and_then(Value::as_str) {+ let created = body+ .get("created")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ println!("stored {id} created={created}");+ } else {+ println!(+ "{}",+ serde_json::to_string(&body).unwrap_or_else(|_| body.to_string())+ );+ }+ return 0;+ }+ report_write_failure(&es, status, &body)+}++fn report_write_failure(es: &Es, status: u16, body: &Value) -> i32 {+ let facts = allocation_facts(es);+ match explain_memory_flood(body, facts.as_ref()) {+ Some(text) => eprintln!("xerj memory: {text}"),+ None => {+ let reason = body.pointer("/error/reason").and_then(Value::as_str);+ match reason {+ Some(reason) if !reason.is_empty() => eprintln!("xerj memory: {reason}"),+ _ => eprintln!("xerj memory: HTTP {status}: {body}"),+ }+ }+ }+ 1+}++/// Allocation is how a client learns free space and `path.data` when the+/// error body is still the raw block (#2077's probe). A stats blip leaves+/// the facts empty; the sentence then says unknown.+fn allocation_facts(es: &Es) -> Option<DiskFacts> {+ let (status, body) = es+ .request_json("GET", "/_cat/allocation?format=json", None)+ .ok()?;+ if !(200..300).contains(&status) {+ return None;+ }+ Some(disk_facts_from_allocation(&body))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn v(args: &[&str]) -> Vec<String> {+ args.iter().map(|s| (*s).to_string()).collect()+ }++ #[test]+ fn help_and_usage_do_not_talk_to_a_node() {+ assert_eq!(run_memory_from(&v(&[])), 0);+ assert_eq!(run_memory_from(&v(&["--help"])), 0);+ assert_eq!(run_memory_from(&v(&["store", "--help"])), 0);+ assert_eq!(run_memory_from(&v(&["recall", "ns"])), 2);+ assert_eq!(run_memory_from(&v(&["store"])), 2);+ assert_eq!(run_memory_from(&v(&["store", "ns"])), 2);+ assert_eq!(run_memory_from(&v(&["store", "ns", "--text"])), 2);+ assert_eq!(run_memory_from(&v(&["store", "--bogus", "x"])), 2);+ }+}diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rsindex 9bb338973..54050733b 100644--- a/engine/crates/xerj-hub/src/cli.rs+++ b/engine/crates/xerj-hub/src/cli.rs@@ -1482,6 +1482,7 @@ pub const KNOWN_SUBCOMMANDS: &[&str] = &["brain","share","feedback",+ "memory","code","corpus","hub",@@ -2267,6 +2268,7 @@ mod tests {"brain","share","feedback",+ "memory","code","corpus","hub",diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rsindex 08c520fd5..6cff933e7 100644--- a/engine/crates/xerj-mcp/src/lib.rs+++ b/engine/crates/xerj-mcp/src/lib.rs@@ -3102,6 +3102,52 @@ fn error_detail(err: &reqwest::Error) -> String {out}+/// `POST /_memory/{namespace}` — not recall, not the bare list.+fn is_memory_store_path(path: &str) -> bool {+ let Some(rest) = path.strip_prefix("/_memory/") else {+ return false;+ };+ !rest.is_empty() && !rest.contains('/')+}++/// #2284: a flood-stage block on `xerj_memory_store` is a nested+/// `cluster_block_exception`. Replace that blob with the plain disk sentence.+/// `None` keeps the HTTP wrapper — this was not the flood-stage block.+async fn memory_flood_tool_text(ctx: &Ctx, body_text: &str) -> Option<String> {+ let body = serde_json::from_str::<Value>(body_text).ok()?;+ // `None` facts: a plain server sentence comes back unchanged, and a raw+ // block becomes the sentence with unknown free space. The raw case is+ // filled in from `/_cat/allocation` below — the same probe autoindex uses.+ let without = xerj_autoindex::flood::explain_memory_flood(&body, None)?;+ if body+ .pointer("/error/reason")+ .and_then(Value::as_str)+ .is_some_and(|reason| reason == without)+ {+ return Some(without);+ }+ let facts = fetch_allocation(ctx)+ .await+ .map(|alloc| xerj_autoindex::flood::disk_facts_from_allocation(&alloc));+ Some(xerj_autoindex::flood::explain_memory_flood(&body, facts.as_ref()).unwrap_or(without))+}++async fn fetch_allocation(ctx: &Ctx) -> Option<Value> {+ let url = format!(+ "{}/_cat/allocation?format=json",+ ctx.base_url.trim_end_matches('/')+ );+ let mut req = ctx.client.get(&url);+ if let Some(auth) = &ctx.auth {+ req = req.header("Authorization", auth);+ }+ let resp = req.send().await.ok()?;+ if !resp.status().is_success() {+ return None;+ }+ resp.json().await.ok()+}+/// The query `xerj_search` should locate inside each passage (#2266)./// Other tools do not get the annotation: a semantic/vector ordinal is a/// chunk index, and `xerj_def` already returns the declaration's `line`.@@ -3159,6 +3205,12 @@ async fn engine_request(}None => tool_text(text, false),}+ } else if is_memory_store_path(path) {+ if let Some(explained) = memory_flood_tool_text(ctx, &text).await {+ tool_text(explained, true)+ } else {+ tool_text(format!("XERJ returned HTTP {status}: {text}"), true)+ }} else {tool_text(format!("XERJ returned HTTP {status}: {text}"), true)}@@ -3288,6 +3340,162 @@ mod tests {assert!(!text.contains("xerj --insecure"), "{text}");}+ /// One HTTP/1.1 response, then close. Enough for the memory-store tests,+ /// which may open a second connection for `/_cat/allocation`.+ async fn answer_once(listener: tokio::net::TcpListener, status: &str, body: &str) {+ let body = body.to_string();+ let status = status.to_string();+ tokio::spawn(async move {+ let Ok((mut sock, _)) = listener.accept().await else {+ return;+ };+ let mut buf = vec![0u8; 8192];+ let _ = tokio::io::AsyncReadExt::read(&mut sock, &mut buf).await;+ let header = format!(+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n",+ body.len()+ );+ let _ = tokio::io::AsyncWriteExt::write_all(&mut sock, header.as_bytes()).await;+ let _ = tokio::io::AsyncWriteExt::write_all(&mut sock, body.as_bytes()).await;+ });+ }++ /// #2284: the server already explained the flood-stage block. The tool+ /// text is that sentence, not `XERJ returned HTTP` plus the JSON.+ #[tokio::test]+ async fn memory_store_prints_a_plain_flood_reason_verbatim() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let reason = "the disk holding the data dir is nearly full, so this memory write was refused (free 2.0gb, 96% used, threshold 95%, data dir D:\\xerj-data). Free space on that drive, or restart the node with --data-dir on another drive.";+ let body = format!(+ r#"{{"error":{{"type":"memory_error","reason":{}}},"status":429}}"#,+ serde_json::to_string(reason).unwrap()+ );+ answer_once(listener, "429 Too Many Requests", &body).await;+ let ctx = Ctx {+ client: reqwest::Client::new(),+ base_url: format!("http://{addr}"),+ auth: None,+ };+ let msg = json!({+ "params": {+ "name": "xerj_memory_store",+ "arguments": { "namespace": "notes", "text": "remember this" }+ }+ });+ let res = call_tool(&ctx, &msg).await;+ assert_eq!(res["isError"], true, "{res}");+ let text = res["content"][0]["text"].as_str().unwrap();+ assert_eq!(text, reason);+ assert!(!text.contains("cluster_block_exception"), "{text}");+ assert!(!text.contains("XERJ returned HTTP"), "{text}");+ }++ /// The raw nested exception: the tool probes allocation (the #2077 read)+ /// and says the disk is nearly full, with free space and the data dir.+ #[tokio::test]+ async fn memory_store_rewrites_a_nested_cluster_block_using_allocation() {+ let store = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = store.local_addr().unwrap();+ tokio::spawn(async move {+ // Two requests, either order, possibly one connection each.+ for _ in 0..2 {+ let Ok((mut sock, _)) = store.accept().await else {+ return;+ };+ let mut buf = vec![0u8; 8192];+ let n = tokio::io::AsyncReadExt::read(&mut sock, &mut buf)+ .await+ .unwrap_or(0);+ let req = String::from_utf8_lossy(&buf[..n]);+ let body = if req.contains("GET /_cat/allocation") {+ r#"[{"disk.percent":"96","disk.avail":"2147483648b","disk.flood_stage":"95","disk.threshold_enabled":"true","disk.flood_blocked":"true","path.data":"D:\\xerj-data"}]"#.to_string()+ } else {+ let inner = r#"{"error":{"type":"cluster_block_exception","reason":"index [.xerj-memory-notes] is blocked for read_only_allow_delete (disk usage 96% exceeded flood-stage watermark [95%]) operations"},"status":429}"#;+ format!(+ r#"{{"error":{{"type":"memory_error","reason":{}}},"status":429}}"#,+ serde_json::to_string(&format!("failed to store memory: {inner}")).unwrap()+ )+ };+ let header = format!(+ "HTTP/1.1 429 Too Many Requests\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n",+ body.len()+ );+ // Allocation is 200. A 429 on the probe would be ignored and+ // the sentence would say free space is unknown.+ let header = if req.contains("GET /_cat/allocation") {+ format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\nContent-Type: application/json\r\n\r\n",+ body.len()+ )+ } else {+ header+ };+ let _ = tokio::io::AsyncWriteExt::write_all(&mut sock, header.as_bytes()).await;+ let _ = tokio::io::AsyncWriteExt::write_all(&mut sock, body.as_bytes()).await;+ }+ });+ let ctx = Ctx {+ client: reqwest::Client::new(),+ base_url: format!("http://{addr}"),+ auth: None,+ };+ let msg = json!({+ "params": {+ "name": "xerj_memory_store",+ "arguments": { "namespace": "notes", "text": "remember this" }+ }+ });+ let res = call_tool(&ctx, &msg).await;+ assert_eq!(res["isError"], true, "{res}");+ let text = res["content"][0]["text"].as_str().unwrap();+ assert!(+ text.contains("the disk holding the data dir is nearly full"),+ "{text}"+ );+ assert!(text.contains("free 2.0gb"), "{text}");+ assert!(text.contains("96% used"), "{text}");+ assert!(text.contains("threshold 95%"), "{text}");+ assert!(text.contains("data dir D:\\xerj-data"), "{text}");+ assert!(+ text.contains("restart the node with --data-dir on another drive"),+ "{text}"+ );+ assert!(!text.contains("cluster_block_exception"), "{text}");+ assert!(!text.contains("XERJ returned HTTP"), "{text}");+ }++ /// A memory-store 400 is not a full disk. The HTTP wrapper stays.+ #[tokio::test]+ async fn memory_store_validation_error_is_not_a_flood_message() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ answer_once(+ listener,+ "400 Bad Request",+ r#"{"error":{"type":"memory_error","reason":"a memory must have non-empty `text` or a `vector`"},"status":400}"#,+ )+ .await;+ let ctx = Ctx {+ client: reqwest::Client::new(),+ base_url: format!("http://{addr}"),+ auth: None,+ };+ let msg = json!({+ "params": {+ "name": "xerj_memory_store",+ "arguments": { "namespace": "notes", "text": "remember this" }+ }+ });+ let res = call_tool(&ctx, &msg).await;+ assert_eq!(res["isError"], true, "{res}");+ let text = res["content"][0]["text"].as_str().unwrap();+ assert!(text.contains("XERJ returned HTTP 400"), "{text}");+ assert!(text.contains("non-empty"), "{text}");+ assert!(!text.contains("nearly full"), "{text}");+ assert!(!text.contains("--data-dir"), "{text}");+ }+#[test]fn required_string_errors_say_what_to_pass_next() {let err = build_semantic(&json!({})).unwrap_err();diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex e18ea1ff8..49f963be2 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -179,6 +179,7 @@ fn is_top_level_command(arg: &str) -> bool {| "brain"| "share"| "feedback"+ | "memory"| "code"| "corpus"| "hub"@@ -458,6 +459,9 @@ fn help_text(feedback: bool) -> String {\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20log — searches, hit rate, latency (xerj gain --help)\n\\x20\x20\x20\x20xerj brain <folder> one command: index a folder into a running, browsable\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20second brain in your browser (see xerj brain --help)\n\+ \x20\x20\x20\x20xerj memory store <ns> --text <t>\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20store one agent memory on a running node\n\+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(see xerj memory --help)\n\\x20\x20\x20\x20xerj mcp [opts] Model Context Protocol stdio server: exposes {mcp_tools} tools\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(search, semantic, vector, hybrid, memory, second-brain,\n\\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20map, plan, code-search, Corpus Hub) to any MCP client.\n\@@ -3698,6 +3702,12 @@ async fn async_main() -> Result<()> {let cmd = parse_index_args();return run_cli_index(cmd).await;}+ if matches!(argv1.as_deref(), Some("memory")) {+ let code = tokio::task::spawn_blocking(xerj_autoindex::memory_cli::run_memory_cli)+ .await+ .unwrap_or(1);+ std::process::exit(code);+ }if matches!(argv1.as_deref(), Some("search")) {let code = tokio::task::spawn_blocking(xerj_autoindex::search::run_search_cli).await