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.

fix(autoindex): fold small configs and page the data map (#1610)

xerj-orgc872a6dc67a2
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index 8b0b58f4f..5616a2514 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -545,6 +545,25 @@ pub fn file_matches_prefix(doc: &Value, prefix: &str) -> bool {
== Some(prefix)
}
+/// How many dataset detail sections the default map prints before it asks
+/// for a page. The summary table always lists every dataset; the per-dataset
+/// field tables and sample queries are what blow the map up to hundreds of
+/// kilobytes.
+pub const MAP_DETAIL_PAGE: usize = 8;
+
+/// `(start, end)` of the detail page. `limit = None` prints every dataset
+/// when there are at most [`MAP_DETAIL_PAGE`], and the first page otherwise.
+pub fn detail_bounds(total: usize, offset: usize, limit: Option<usize>) -> (usize, usize) {
+ let start = offset.min(total);
+ let limit = limit.unwrap_or(if total > MAP_DETAIL_PAGE {
+ MAP_DETAIL_PAGE
+ } else {
+ total
+ });
+ let end = start.saturating_add(limit).min(total);
+ (start, end)
+}
+
pub fn render_map(
run: Option<&Value>,
datasets: &[Value],
@@ -552,6 +571,29 @@ pub fn render_map(
junk_files: &[Value],
duplicate_files: &[Value],
junk_total: u64,
+) -> String {
+ render_map_page(
+ run,
+ datasets,
+ correlations,
+ junk_files,
+ duplicate_files,
+ junk_total,
+ 0,
+ None,
+ )
+}
+
+#[allow(clippy::too_many_arguments)] // paging is two extra args on the existing map renderer
+pub fn render_map_page(
+ run: Option<&Value>,
+ datasets: &[Value],
+ correlations: &[Value],
+ junk_files: &[Value],
+ duplicate_files: &[Value],
+ junk_total: u64,
+ detail_offset: usize,
+ detail_limit: Option<usize>,
) -> String {
let mut s = String::new();
s.push_str("# Data map (xerj autoindex)\n\n");
@@ -626,7 +668,24 @@ pub fn render_map(
}
s.push('\n');
- for d in datasets {
+ let (detail_start, detail_end) = detail_bounds(datasets.len(), detail_offset, detail_limit);
+ let detail_truncated = detail_start > 0 || detail_end < datasets.len();
+ if detail_truncated {
+ s.push_str(&format!(
+ "Field detail for datasets {}–{} of {} (largest first). \
+ One dataset: `xerj autoindex map --dataset <slug>`. \
+ Next page: `--offset {detail_end}`.\n\n",
+ detail_start + 1,
+ detail_end,
+ datasets.len()
+ ));
+ }
+
+ for d in datasets
+ .iter()
+ .skip(detail_start)
+ .take(detail_end - detail_start)
+ {
let g = |k: &str| d.get(k).map(pretty_val).unwrap_or_default();
s.push_str(&format!("### `{}`\n\n", g("index_name")));
if let Some(sem) = d.get("semantic_field").filter(|v| v.is_string()) {
@@ -845,6 +904,57 @@ fn trunc_f(s: &str) -> String {
mod duplicate_tests {
use super::*;
+ #[test]
+ fn a_long_catalog_pages_field_detail_and_keeps_the_summary_table() {
+ let datasets: Vec<Value> = (0..20)
+ .map(|i| {
+ json!({
+ "index_name": format!("ax-d{i:02}"),
+ "slug": format!("d{i:02}"),
+ "record_count": 100 - i,
+ "file_count": 1,
+ "formats": "json",
+ "fields_json": serde_json::to_string(&vec![crate::infer::FieldSpec {
+ name: format!("col{i}"),
+ es_type: "keyword".into(),
+ date_enc: None,
+ semantic: None,
+ cardinality_est: 1,
+ cardinality_overflow: false,
+ null_ratio: 0.0,
+ avg_len: 3.0,
+ coverage: 1.0,
+ examples: vec!["v".into()],
+ notes: vec![],
+ date_min: None,
+ date_max: None,
+ date_evidence: vec![],
+ num_min: None,
+ num_max: None,
+ }]).unwrap()
+ })
+ })
+ .collect();
+ let rendered = render_map(None, &datasets, &[], &[], &[], 0);
+ assert!(
+ rendered.contains("`ax-d00`"),
+ "summary table lists every dataset"
+ );
+ assert!(rendered.contains("`ax-d19`"));
+ assert_eq!(
+ rendered.matches("### `").count(),
+ super::MAP_DETAIL_PAGE,
+ "detail sections stop at the page: {rendered}"
+ );
+ assert!(rendered.contains("Field detail for datasets 1–8 of 20"));
+ assert!(rendered.contains("--offset 8"));
+ let page = render_map_page(None, &datasets, &[], &[], &[], 0, 8, Some(2));
+ assert!(page.contains("### `ax-d08`"));
+ assert!(page.contains("### `ax-d09`"));
+ assert!(!page.contains("### `ax-d10`"));
+ assert!(page.contains("Field detail for datasets 9–10 of 20"));
+ }
+
#[test]
fn duplicate_aliases_render_separately_from_junk() {
let duplicate = json!({
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index a9173857a..f050d3bca 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -131,6 +131,12 @@ pub struct MapCfg {
pub prefix: Option<String>,
pub json: bool,
pub dataset: Option<String>,
+ /// `--offset` for the map's per-dataset field detail. The summary table
+ /// always lists every dataset.
+ pub detail_offset: usize,
+ /// `--limit` for that detail page. `None` uses the default page when
+ /// there are more datasets than [`crate::catalog::MAP_DETAIL_PAGE`].
+ pub detail_limit: Option<usize>,
/// A startup note when `XERJ_URL` was set but ignored (endpoint comes from
/// `--url` only). `map` reads the catalog, so a stale var shows the wrong
/// node's map without a word — same trap as the index path, read side.
@@ -363,6 +369,11 @@ pub fn help_text_with(feedback: bool) -> String {
exactly like an agent-driven run. See ESTIMATE + DECISION\n\
GATE.\n\
--dataset <SLUG> (map) show a single dataset\n\
+ --offset <N> (map) skip the first N dataset detail sections\n\
+ --limit <N> (map) how many dataset detail sections to print\n\
+ (default: all of them when there are few, otherwise\n\
+ the first page — the summary table always lists every\n\
+ dataset)\n\
--disable-feedback do not print the feedback invitation above; honoured in\n\
any position, including after --help (env\n\
XERJ_DISABLE_FEEDBACK=true)\n\
@@ -737,6 +748,8 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
let mut progress: Option<ProgressMode> = None;
let mut progress_interval: Option<Duration> = None;
let mut dataset: Option<String> = None;
+ let mut detail_offset: Option<usize> = None;
+ let mut detail_limit: Option<usize> = None;
// Object-storage watch (`--watch` on an s3:// root). Kept in their own
// variables so the watch route can refuse an index-only flag instead of
// accepting it and doing nothing with it (#204's class).
@@ -993,6 +1006,25 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
"--dataset needs a dataset slug: `autoindex map --dataset <SLUG>`",
)?);
}
+ "--offset" => {
+ let n: usize = it
+ .next()
+ .ok_or("--offset needs a non-negative integer: `autoindex map --offset <N>`")?
+ .parse()
+ .map_err(|_| "--offset needs a non-negative integer".to_string())?;
+ detail_offset = Some(n);
+ }
+ "--limit" => {
+ let n: usize = it
+ .next()
+ .ok_or("--limit needs an integer from 1 to 100: `autoindex map --limit <N>`")?
+ .parse()
+ .map_err(|_| "--limit needs an integer from 1 to 100".to_string())?;
+ if !(1..=100).contains(&n) {
+ return Err("--limit must be from 1 to 100".into());
+ }
+ detail_limit = Some(n);
+ }
"--poll-interval" => {
watch_flags_used.push("--poll-interval");
let secs: u64 = it
@@ -1526,8 +1558,15 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
prefix: prefix_explicit.then_some(prefix),
json,
dataset,
+ detail_offset: detail_offset.unwrap_or(0),
+ detail_limit,
xerj_url_note,
})),
+ (_, _) if detail_offset.is_some() || detail_limit.is_some() => Err(format!(
+ "--offset and --limit page the data map and are only supported with \
+ `autoindex map`, not `autoindex {}`",
+ sub.as_deref().unwrap_or("<root>")
+ )),
// #1231: --dataset only selects which dataset `autoindex map` prints;
// it is NOT an indexing destination filter. Accepting it on the
// indexing/status routes and then dropping it is the silent no-op this
diff --git a/engine/crates/xerj-autoindex/src/dataset.rs b/engine/crates/xerj-autoindex/src/dataset.rs
index 17a1a8417..69502b50d 100644
--- a/engine/crates/xerj-autoindex/src/dataset.rs
+++ b/engine/crates/xerj-autoindex/src/dataset.rs
@@ -17,10 +17,13 @@
//! cluster by schema fingerprint (Jaccard on field-name sets ≥ 0.7) within the
//! same format family AND scope — a real schema that recurs across files is a
//! dataset. But a self-describing config blob is not: a small cluster of
-//! `json`/`yaml`/`xml` files that each produced exactly one record is *demoted*
-//! to the scope's document dataset and indexed as a document (title/body),
-//! because its one-off key set is configuration, not a collection
-//! (#173: valkey's per-command JSON files made 382 such "datasets").
+//! `json`/`yaml`/`xml` files, including a short multi-document stream, is
+//! *demoted* to the scope's document dataset and indexed as a document
+//! (title/body), because its one-off key set is configuration, not a
+//! collection (#173: valkey's per-command JSON files made 382 such
+//! "datasets"). A scope that still has more medium structured clusters than
+//! [`MAX_STRUCTURED_DATASETS_PER_SCOPE`] folds the smallest into documents;
+//! a cluster of [`DATASET_CAP_PROTECT_RECORDS`] or more stays.
//!
//! Only DATA-derived names take part in schema clustering. A name the
//! extractor invented — `defs`, `symbols`, `title`, `page` — is not evidence
@@ -36,12 +39,41 @@ use crate::infer::FieldAcc;
use crate::sniff::Family;
use std::collections::{BTreeMap, HashMap, HashSet};
-/// A schema-clustered `json`/`yaml`/`xml` group at most this many files large,
-/// in which every file produced exactly one record, is configuration — demote
-/// it to the scope's document dataset. A schema that recurs across more files
-/// than this is treated as a real single-record-per-file collection.
+/// A schema-clustered `json`/`yaml`/`xml` group at most this many files large
+/// is eligible to fold into the scope's document dataset. A schema that
+/// recurs across more files than this is treated as a real collection.
pub const DOC_DEMOTE_MAX_FILES: usize = 8;
+/// Per file, this many records is still a config document: one JSON object,
+/// a short array, or a multi-document YAML stream. The old rule required
+/// exactly one record, so a workflow file or a small manifest became its own
+/// index (one repository → well over a hundred indices).
+pub const DOC_DEMOTE_MAX_RECORDS_PER_FILE: u64 = 32;
+
+/// After the small-config fold, one repository scope keeps at most this many
+/// `json`/`yaml`/`xml` data datasets below [`DATASET_CAP_PROTECT_RECORDS`].
+/// The smallest are folded into the document dataset until the scope is at
+/// the cap. CSV, JSONL, logs and SQL are collections by nature and are never
+/// folded by this cap.
+pub const MAX_STRUCTURED_DATASETS_PER_SCOPE: usize = 12;
+
+/// A `json`/`yaml`/`xml` cluster with at least this many records is a real
+/// collection. The per-scope cap never folds it.
+pub const DATASET_CAP_PROTECT_RECORDS: u64 = 1024;
+
+/// A small `json`/`yaml`/`xml` cluster (no sub-file group) is configuration,
+/// not a dataset: few files, and not many records in each file.
+pub(crate) fn small_structured_config(c: &Cluster) -> bool {
+ if !demotable_family(c.family) || c.group.is_some() || c.members.is_empty() {
+ return false;
+ }
+ if c.members.len() > DOC_DEMOTE_MAX_FILES {
+ return false;
+ }
+ let ceiling = (c.members.len() as u64).saturating_mul(DOC_DEMOTE_MAX_RECORDS_PER_FILE);
+ c.records <= ceiling
+}
+
#[derive(Debug)]
pub struct Sketch {
pub file_idx: usize,
@@ -174,24 +206,51 @@ pub fn cluster(sketches: Vec<Sketch>, rels: &[String], scopes: &[String]) -> Vec
}
}
- // Demote one-off config clusters to their scope's document dataset. Their
- // sampled fields are dropped — the caller re-samples the demoted files
- // through the document renderer, which is also what indexes them.
+ // Demote small config clusters — one record each, or a short multi-doc
+ // YAML/JSON/XML file — to their scope's document dataset. Their sampled
+ // fields are dropped — the caller re-samples the demoted files through
+ // the document renderer, which is also what indexes them.
let mut kept: Vec<Cluster> = Vec::with_capacity(data.len());
+ let mut capped: BTreeMap<String, Vec<Cluster>> = BTreeMap::new();
for c in data {
- let one_record_each = c.records == c.members.len() as u64;
- if demotable_family(c.family)
- && c.group.is_none()
- && c.members.len() <= DOC_DEMOTE_MAX_FILES
- && one_record_each
- {
+ if small_structured_config(&c) {
let d = docs_cluster(&mut docs, &c.scope);
d.members.extend(c.members.iter().copied());
d.demoted.extend(c.members);
continue;
}
+ // Candidates for the per-scope cap: structured formats, no sub-file
+ // group, and not a large collection. Everything else stays.
+ if demotable_family(c.family)
+ && c.group.is_none()
+ && c.records < DATASET_CAP_PROTECT_RECORDS
+ {
+ capped.entry(c.scope.clone()).or_default().push(c);
+ continue;
+ }
kept.push(c);
}
+ for (scope, mut group) in capped {
+ // Largest collections stay. Ties break toward the earlier file so
+ // the fold does not depend on hash order.
+ group.sort_by(|a, b| {
+ b.records
+ .cmp(&a.records)
+ .then(b.members.len().cmp(&a.members.len()))
+ .then_with(|| {
+ let am = a.members.iter().copied().min().unwrap_or(usize::MAX);
+ let bm = b.members.iter().copied().min().unwrap_or(usize::MAX);
+ am.cmp(&bm)
+ })
+ });
+ let keep_n = MAX_STRUCTURED_DATASETS_PER_SCOPE.min(group.len());
+ for c in group.drain(keep_n..) {
+ let d = docs_cluster(&mut docs, &scope);
+ d.members.extend(c.members.iter().copied());
+ d.demoted.extend(c.members);
+ }
+ kept.extend(group);
+ }
// Docs slugs are scope-derived — independent of which other files exist,
// so adding a file can never rename (and re-home, #178) a docs dataset.
@@ -613,7 +672,8 @@ mod tests {
/// one-off key sets are configuration, not datasets — they demote into
/// the scope's document dataset and their config keys never reach its
/// mapping. A recurring schema (many files) stays a data dataset, and a
- /// multi-record structured file is a collection whatever its size.
+ /// large multi-record file stays a collection when the scope is under
+ /// the dataset cap.
#[test]
fn one_off_config_files_demote_to_documents() {
let mut sketches = Vec::new();
@@ -664,10 +724,102 @@ mod tests {
assert!(
data.iter()
.any(|c| c.records == 500 && c.key_fields.contains("evt")),
- "a multi-record collection must stay a data dataset"
+ "a multi-record collection must stay a data dataset while the scope is under the cap"
);
}
+ /// A YAML/JSON file that yields a handful of records is still config.
+ /// The one-record rule left every multi-doc manifest as its own index.
+ #[test]
+ fn small_multi_doc_yaml_and_json_fold_into_documents() {
+ let mut sketches = Vec::new();
+ let mut rels = Vec::new();
+ rels.push("src/main.rs".into());
+ sketches.push(code_sketch(0, true));
+ for i in 1..=20 {
+ rels.push(format!(".github/workflows/w{i}.yml"));
+ sketches.push(data_sketch_n(
+ i,
+ Family::Yaml,
+ &[&format!("job{i}"), "runs_on"],
+ 4,
+ ));
+ }
+ // one short JSON array, its own schema
+ rels.push("config/matrix.json".into());
+ sketches.push(data_sketch_n(21, Family::Json, &["os", "rust"], 6));
+ let clusters = cluster(sketches, &rels, &root_scopes(rels.len()));
+ let docs: Vec<&Cluster> = clusters.iter().filter(|c| c.is_docs).collect();
+ assert_eq!(docs.len(), 1, "{clusters:#?}");
+ assert_eq!(docs[0].demoted.len(), 21, "20 workflows + the matrix");
+ assert!(
+ clusters.iter().filter(|c| !c.is_docs).count() == 0,
+ "small multi-doc configs must not each become an index: {clusters:#?}"
+ );
+ }
+
+ /// Twenty medium one-off JSON files would be twenty indices. The cap
+ /// keeps the largest [`MAX_STRUCTURED_DATASETS_PER_SCOPE`] and folds the
+ /// rest. A collection at the protect threshold is never folded.
+ #[test]
+ fn a_scope_caps_medium_structured_datasets_and_keeps_large_ones() {
+ let mut sketches = Vec::new();
+ let mut rels = Vec::new();
+ rels.push("README.md".into());
+ sketches.push(prose_sketch(0));
+ let n_medium = MAX_STRUCTURED_DATASETS_PER_SCOPE + 8;
+ for i in 0..n_medium {
+ let idx = i + 1;
+ rels.push(format!("fixtures/f{idx}.json"));
+ // Larger index → more records, so the cap keeps the tail.
+ sketches.push(data_sketch_n(
+ idx,
+ Family::Json,
+ &[&format!("k{idx}")],
+ 40 + i as u64,
+ ));
+ }
+ let big = n_medium + 1;
+ rels.push("data/events.json".into());
+ sketches.push(data_sketch_n(
+ big,
+ Family::Json,
+ &["evt", "ts"],
+ DATASET_CAP_PROTECT_RECORDS,
+ ));
+ // A CSV schema is not subject to the structured cap.
+ let csv = big + 1;
+ rels.push("data/rows.csv".into());
+ sketches.push(data_sketch_n(csv, Family::Csv, &["a", "b"], 10));
+
+ let clusters = cluster(sketches, &rels, &root_scopes(rels.len()));
+ let docs = clusters.iter().find(|c| c.is_docs).expect("docs");
+ assert_eq!(
+ docs.demoted.len(),
+ 8,
+ "the eight smallest medium files fold"
+ );
+ let data: Vec<&Cluster> = clusters.iter().filter(|c| !c.is_docs).collect();
+ assert_eq!(
+ data.len(),
+ MAX_STRUCTURED_DATASETS_PER_SCOPE + 2,
+ "cap + the protected JSON + the CSV: {data:#?}"
+ );
+ assert!(
+ data.iter()
+ .any(|c| c.records == DATASET_CAP_PROTECT_RECORDS),
+ "a large collection is not folded by the cap"
+ );
+ assert!(data.iter().any(|c| c.family == Family::Csv));
+ let kept_medium: Vec<u64> = data
+ .iter()
+ .filter(|c| c.family == Family::Json && c.records < DATASET_CAP_PROTECT_RECORDS)
+ .map(|c| c.records)
+ .collect();
+ assert_eq!(kept_medium.len(), MAX_STRUCTURED_DATASETS_PER_SCOPE);
+ assert!(kept_medium.iter().all(|r| *r >= 40 + 8), "{kept_medium:?}");
+ }
+
/// Scope is a hard boundary for data schemas too: the same CSV schema in
/// two repositories is two datasets (per-repo corpora stay self-contained).
#[test]
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 4e85db9bd..6d3c0113d 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -9542,27 +9542,56 @@ fn run_map(cfg: MapCfg) -> Result<i32> {
duplicate_files.retain(|f| catalog::file_matches_prefix(f, prefix));
}
if cfg.json {
- println!(
- "{}",
- serde_json::to_string_pretty(&json!({
+ let (start, end) =
+ catalog::detail_bounds(datasets.len(), cfg.detail_offset, cfg.detail_limit);
+ let truncated = start > 0 || end < datasets.len();
+ let body = if truncated {
+ let summary: Vec<Value> = datasets
+ .iter()
+ .map(|d| {
+ json!({
+ "index_name": d.get("index_name"),
+ "slug": d.get("slug"),
+ "record_count": d.get("record_count"),
+ "file_count": d.get("file_count"),
+ })
+ })
+ .collect();
+ json!({
+ "run": runs.first(),
+ "datasets_total": datasets.len(),
+ "detail_offset": start,
+ "datasets": &datasets[start..end],
+ "datasets_summary": summary,
+ "detail_note": "field detail is paged; `autoindex map --dataset <slug>` or `--offset`/`--limit`",
+ "correlations": correlations,
+ "junk_files": junk_files,
+ "duplicate_files": duplicate_files,
+ "gotchas": catalog::GOTCHAS,
+ })
+ } else {
+ json!({
"run": runs.first(),
"datasets": datasets,
"correlations": correlations,
"junk_files": junk_files,
"duplicate_files": duplicate_files,
"gotchas": catalog::GOTCHAS,
- }))?
- );
+ })
+ };
+ println!("{}", serde_json::to_string_pretty(&body)?);
} else {
print!(
"{}",
- catalog::render_map(
+ catalog::render_map_page(
runs.first(),
&datasets,
&correlations,
&junk_files,
&duplicate_files,
- junk_files.len() as u64
+ junk_files.len() as u64,
+ cfg.detail_offset,
+ cfg.detail_limit,
)
);
// Second-brain summary (§6.1): live edge count straight from the
diff --git a/engine/crates/xerj-mcp/src/lib.rs b/engine/crates/xerj-mcp/src/lib.rs
index afe9223c5..f1bd93953 100644
--- a/engine/crates/xerj-mcp/src/lib.rs
+++ b/engine/crates/xerj-mcp/src/lib.rs
@@ -987,7 +987,9 @@ pub fn tool_specs() -> Value {
"cardinality is an estimate (with `cardinality_overflow:true` it means ",
"AT LEAST that many), and min/max/coverage describe the sample, not ",
"the whole index. Up to 100 indexes per call (`indexes_omitted` ",
- "reports more)."
+ "reports more). When more than 8 indexes match and you did not pass ",
+ "`index`, the answer is a SUMMARY page (index, records, field names) ",
+ "— pass `index` or `detail: true` with `offset`/`limit` for full fields."
),
"inputSchema": {
"type": "object",
@@ -998,6 +1000,24 @@ pub fn tool_specs() -> Value {
catalogued index. An exact name filters engine-side; a glob filters \
against the catalog before the 100-index limit."
},
+ "offset": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Skip this many datasets (largest record count first) before rendering. Default 0."
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": map::MAX_INDEXES,
+ "description": format!(
+ "How many datasets to return (1..={}). Default: {} on a summary page, otherwise every dataset this call fetched (up to {}).",
+ map::MAX_INDEXES, map::SUMMARY_PAGE, map::MAX_INDEXES
+ )
+ },
+ "detail": {
+ "type": "boolean",
+ "description": "true = full field entries. false = summary rows (index, records, field names). Default: summary when more than 8 indexes match and `index` was not passed; full entries otherwise."
+ },
"max_bytes": {
"type": "integer",
"minimum": map::MIN_MAX_BYTES,
diff --git a/engine/crates/xerj-mcp/src/map.rs b/engine/crates/xerj-mcp/src/map.rs
index 914783174..6f570bb73 100644
--- a/engine/crates/xerj-mcp/src/map.rs
+++ b/engine/crates/xerj-mcp/src/map.rs
@@ -52,6 +52,13 @@ pub const MAX_INDEXES: usize = 100;
/// published contract if that ever grows.
pub const MAX_EXAMPLES: usize = 5;
+/// Past this many datasets, the default `xerj_map` answer is a summary page
+/// (index, records, field names) instead of a full field entry per index.
+/// A hundred 4 KB entries is what truncated the tool result.
+pub const SUMMARY_AT: usize = 8;
+/// Datasets in one default summary page.
+pub const SUMMARY_PAGE: usize = 25;
+
/// Parsed, validated `xerj_map` arguments.
#[derive(Debug, Clone)]
pub(crate) struct MapArgs {
@@ -59,6 +66,15 @@ pub(crate) struct MapArgs {
pub index: Option<String>,
/// Per-index byte budget for the rendered entry.
pub max_bytes: usize,
+ /// Skip this many datasets (record-count order) before rendering.
+ pub offset: usize,
+ /// How many datasets to return. `None` is the summary page when the
+ /// catalog is large, and every fetched dataset otherwise.
+ pub limit: Option<usize>,
+ /// `Some(true)` forces full field entries. `Some(false)` forces the
+ /// summary. `None` summarizes when no index filter is set and more than
+ /// [`SUMMARY_AT`] datasets matched.
+ pub detail: Option<bool>,
}
/// Parse and validate the tool arguments. Present-but-mistyped is an error,
@@ -85,7 +101,34 @@ pub(crate) fn parse_args(args: &Value) -> Result<MapArgs, String> {
)
})?,
};
- Ok(MapArgs { index, max_bytes })
+ let offset = match args.get("offset") {
+ None | Some(Value::Null) => 0,
+ Some(v) => v
+ .as_u64()
+ .and_then(|n| usize::try_from(n).ok())
+ .ok_or_else(|| "`offset` must be an integer >= 0".to_string())?,
+ };
+ let limit = match args.get("limit") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(
+ v.as_u64()
+ .and_then(|n| usize::try_from(n).ok())
+ .filter(|n| (1..=MAX_INDEXES).contains(n))
+ .ok_or_else(|| format!("`limit` must be an integer from 1 to {MAX_INDEXES}"))?,
+ ),
+ };
+ let detail = match args.get("detail") {
+ None | Some(Value::Null) => None,
+ Some(Value::Bool(b)) => Some(*b),
+ Some(_) => return Err("`detail` must be a boolean".into()),
+ };
+ Ok(MapArgs {
+ index,
+ max_bytes,
+ offset,
+ limit,
+ detail,
+ })
}
/// The `_search` body for the catalog read. Filter exact names with `term`
@@ -100,9 +143,11 @@ pub(crate) fn catalog_body(args: &MapArgs) -> Value {
must.push(json!({ "term": { "index_name": name } }));
}
}
+ let size = args.limit.unwrap_or(MAX_INDEXES).clamp(1, MAX_INDEXES);
json!({
"query": { "bool": { "must": must } },
- "size": MAX_INDEXES,
+ "from": args.offset,
+ "size": size,
"sort": [{ "record_count": "desc" }],
// The dataset doc also carries sample_queries_json (by far its
// largest field); project it out rather than transfer it to drop it.
@@ -378,13 +423,46 @@ pub(crate) fn render_response(resp: &Value, args: &MapArgs) -> String {
})
});
+ let summarize = match args.detail {
+ Some(true) => false,
+ Some(false) => true,
+ None => args.index.is_none() && indexes.len() > SUMMARY_AT,
+ };
+ let page_limit = if summarize {
+ args.limit.unwrap_or(SUMMARY_PAGE)
+ } else {
+ args.limit.unwrap_or(indexes.len())
+ };
+ let shown: Vec<Value> = if summarize {
+ indexes.iter().take(page_limit).map(summary_entry).collect()
+ } else {
+ indexes.into_iter().take(page_limit).collect()
+ };
let mut out = Map::new();
- out.insert("matched".into(), json!(indexes.len()));
+ out.insert("matched".into(), json!(shown.len()));
+ if summarize {
+ out.insert("summary".into(), json!(true));
+ out.insert(
+ "hint".into(),
+ json!(
+ "summary page — pass `index` (name or glob) or `detail: true` with \
+ `offset`/`limit` for full field entries"
+ ),
+ );
+ }
if let Some(p) = &args.index {
out.insert("pattern".into(), json!(p));
}
- out.insert("indexes".into(), Value::Array(indexes));
- let omitted = total.saturating_sub(hits.len() as u64);
+ out.insert("indexes".into(), Value::Array(shown.clone()));
+ // `from` already applied `offset` on a live fetch. Counting from the
+ // rendered page (not the fetched page) is what makes a summary of 25
+ // out of 161 say so, and it matches the old `total - hits` figure when
+ // the whole fetch is rendered.
+ let omitted = if summarize || args.limit.is_some() || args.offset > 0 {
+ total.saturating_sub(args.offset as u64 + shown.len() as u64)
+ } else {
+ total.saturating_sub(hits.len() as u64)
+ };
if omitted > 0 {
out.insert("indexes_omitted".into(), json!(omitted));
}
@@ -401,6 +479,27 @@ pub(crate) fn render_response(resp: &Value, args: &MapArgs) -> String {
Value::Object(out).to_string()
}
+/// One summary row: enough to pick an index, not the field tables that
+/// overflow the tool result.
+fn summary_entry(entry: &Value) -> Value {
+ let names: Vec<Value> = entry
+ .get("fields")
+ .and_then(Value::as_array)
+ .map(|fs| {
+ fs.iter()
+ .filter_map(|f| f.get("name").cloned())
+ .take(40)
+ .collect()
+ })
+ .unwrap_or_default();
+ json!({
+ "index": entry.get("index").cloned().unwrap_or(Value::Null),
+ "records": entry.get("records").cloned().unwrap_or(Value::Null),
+ "field_count": entry.get("field_count").cloned().unwrap_or(json!(0)),
+ "field_names": names,
+ })
+}
+
/// `xerj_map` dispatch: read the catalog, render the map. A missing catalog
/// (the node never ran autoindex) is an error with the fix named — the
/// response an agent can act on — while an empty-but-present catalog is a
@@ -476,6 +575,9 @@ mod tests {
MapArgs {
index: index.map(str::to_string),
max_bytes: DEFAULT_MAX_BYTES,
+ offset: 0,
+ limit: None,
+ detail: None,
}
}
@@ -651,6 +753,9 @@ mod tests {
let huge = MapArgs {
index: None,
max_bytes: 1_000_000,
+ offset: 0,
+ limit: None,
+ detail: None,
};
let full_len = serde_json::to_string(
&serde_json::from_str::<Value>(&render_response(&resp_full, &huge)).unwrap()["indexes"]
@@ -674,6 +779,9 @@ mod tests {
let tight = MapArgs {
index: None,
max_bytes: budget,
+ offset: 0,
+ limit: None,
+ detail: None,
};
let out: Value = serde_json::from_str(&render_response(&resp_full, &tight)).unwrap();
let idx = &out["indexes"][0];
@@ -709,6 +817,9 @@ mod tests {
let tight = MapArgs {
index: None,
max_bytes: MIN_MAX_BYTES,
+ offset: 0,
+ limit: None,
+ detail: None,
};
let out: Value = serde_json::from_str(&render_response(&resp, &tight)).unwrap();
let idx = &out["indexes"][0];
@@ -776,6 +887,26 @@ mod tests {
);
}
+ #[test]
+ fn many_datasets_render_as_a_summary_page() {
+ let f = r#"[{"name":"body","es_type":"text","cardinality_est":1,"coverage":1.0,"examples":["hello"]}]"#;
+ let hits: Vec<Value> = (0..12)
+ .map(|i| dataset_doc(&format!("ax-{i:02}"), 100 - i, f))
+ .collect();
+ let resp = catalog_response(hits);
+ let out: Value = serde_json::from_str(&render_response(&resp, &args(None))).unwrap();
+ assert_eq!(out["summary"], true);
+ assert_eq!(out["matched"], SUMMARY_PAGE.min(12));
+ assert!(out["indexes"][0].get("fields").is_none(), "{out}");
+ assert_eq!(out["indexes"][0]["field_names"][0], "body");
+ let mut full = args(None);
+ full.detail = Some(true);
+ let detailed: Value = serde_json::from_str(&render_response(&resp, &full)).unwrap();
+ assert!(detailed.get("summary").is_none(), "{detailed}");
+ assert_eq!(detailed["matched"], 12);
+ assert!(detailed["indexes"][0].get("fields").is_some());
+ }
+
#[test]
fn indexes_past_the_fetch_cap_are_reported_not_silently_dropped() {
let f = r#"[{"name":"a","es_type":"keyword","cardinality_est":1,"coverage":1.0}]"#;
diff --git a/landing/docs/agents/schemas/mcp-tools.json b/landing/docs/agents/schemas/mcp-tools.json
index 7692b9245..5ece614bd 100644
--- a/landing/docs/agents/schemas/mcp-tools.json
+++ b/landing/docs/agents/schemas/mcp-tools.json
@@ -506,7 +506,7 @@
},
{
"name": "xerj_map",
- "description": "Per-index FIELD MAP from this node's autoindex catalog — call it BEFORE writing query DSL, so you stop guessing field names. For each catalogued index: record count, time field and time range, semantic body field, and every field the profiler inferred — name, es_type (keyword|text|long|double|boolean|date|semantic_text), date encoding, semantic tag, cardinality estimate, coverage, up to 5 examples, and the sampled date AND numeric min-max (numeric ranges appear on `long` fields only; fractional `double` ranges are not tracked). Reads the catalog index `autoindex-catalog` that `xerj autoindex <folder>` writes; never-autoindexed indexes are not listed. Honesty: every fact is inferred from a bounded sample taken at autoindex time — cardinality is an estimate (with `cardinality_overflow:true` it means AT LEAST that many), and min/max/coverage describe the sample, not the whole index. Up to 100 indexes per call (`indexes_omitted` reports more).",
+ "description": "Per-index FIELD MAP from this node's autoindex catalog — call it BEFORE writing query DSL, so you stop guessing field names. For each catalogued index: record count, time field and time range, semantic body field, and every field the profiler inferred — name, es_type (keyword|text|long|double|boolean|date|semantic_text), date encoding, semantic tag, cardinality estimate, coverage, up to 5 examples, and the sampled date AND numeric min-max (numeric ranges appear on `long` fields only; fractional `double` ranges are not tracked). Reads the catalog index `autoindex-catalog` that `xerj autoindex <folder>` writes; never-autoindexed indexes are not listed. Honesty: every fact is inferred from a bounded sample taken at autoindex time — cardinality is an estimate (with `cardinality_overflow:true` it means AT LEAST that many), and min/max/coverage describe the sample, not the whole index. Up to 100 indexes per call (`indexes_omitted` reports more). When more than 8 indexes match and you did not pass `index`, the answer is a SUMMARY page (index, records, field names) — pass `index` or `detail: true` with `offset`/`limit` for full fields.",
"inputSchema": {
"type": "object",
"properties": {
@@ -514,6 +514,21 @@
"type": "string",
"description": "Index name or `*`-glob (e.g. `ax-logs`, `ax-*`). Default: every catalogued index. An exact name filters engine-side; a glob filters against the catalog before the 100-index limit."
},
+ "offset": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Skip this many datasets (largest record count first) before rendering. Default 0."
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 100,
+ "description": "How many datasets to return (1..=100). Default: 25 on a summary page, otherwise every dataset this call fetched (up to 100)."
+ },
+ "detail": {
+ "type": "boolean",
+ "description": "true = full field entries. false = summary rows (index, records, field names). Default: summary when more than 8 indexes match and `index` was not passed; full entries otherwise."
+ },
"max_bytes": {
"type": "integer",
"minimum": 1024,