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
feat(autoindex): export offline HTML and Markdown data maps (#2705)
Jarvise5321224c9bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8091c2ca2..6e673a7bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- `xerj autoindex map --html <FILE>` and `--md <FILE>` export an offline+ report with datasets, format counts, top symbols, graph file hubs,+ catalog exclusions and suggested searches. `--redact-paths` hides file+ paths and skip reasons. Existing files are never overwritten; ordinary+ map and JSON output retain their behavior (#2643).+- `xerj autoindex --exclude <glob>` leaves matching paths out of the indexwithout editing an ignore file or deleting anything. Repeatable, same globsyntax as `--stub` — a pattern without `/` matches a file name at any depth,diff --git a/README.md b/README.mdindex 09e7e3383..f57bbb04e 100644--- a/README.md+++ b/README.md@@ -150,6 +150,12 @@ phase B: indexing 25329 files with 8 workersdone in 158.1s, 593 datasets, 83103 records live, 790 junk records```+Share an offline data map with `xerj autoindex map --prefix myproject --html+xerj-map.html --redact-paths`, or use `--md xerj-map.md` for Markdown. Reports+include dataset counts, symbol names, graph hubs when available, skipped-file+information and suggested searches. Review metadata names before sharing.+[Examples, privacy scope and reproduction](tools/map-report/README.md).+## What people point it at- Reference coding: index the OSS projects nearest your problem and retrieve how they solveddiff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex ee5ee17ea..9e765b011 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -163,6 +163,7 @@ pub struct IndexCfg {#[derive(Debug, Clone)]pub struct MapCfg {+ pub report: Option<crate::map_report::Output>,pub url: String,pub api_key: Option<String>,/// Explicit `--prefix` filter (`None` when the user did not pass `--prefix`,@@ -338,6 +339,11 @@ pub fn help_text_with(feedback: bool) -> String {\x20\x20\x20\x20xerj autoindex s3://bucket/prefix --watch [OPTIONS]\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\x20\x20\x20\x20\x20\x20poll object storage and emit a change feed\n\\n\+ MAP REPORTS (catalog map only):\n\+ \x20\x20\x20\x20--html <FILE> write an offline HTML report (new file only)\n\+ \x20\x20\x20\x20--md <FILE> write a Markdown report (new file only)\n\+ \x20\x20\x20\x20--redact-paths omit file paths and skip reasons from the report\n\+ \n\OPTIONS:\n\\x20\x20\x20\x20--url <U> ES-compat endpoint (default http://localhost:9200)\n\\x20\x20\x20\x20--api-key <K> Authorization header (or env XERJ_API_KEY)\n\@@ -982,7 +988,9 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {let mut yes_flag = false;let mut remove_root: Option<String> = None;let mut remove_uncataloged = false;- let mut markdown = false;+ let markdown = false;+ let mut report_output = None;+ let mut redact_paths = false;let mut code_analyzer_explicit = false;let mut max_index_bytes: Option<u64> = None;let mut max_index_explicit = false;@@ -1254,10 +1262,28 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {"--dry-run" => dry_run = true,"--walk-only" => walk_only = true,"--json" => json = true,- "--md" => {- json = false;- markdown = true;+ "--html" | "--md" => {+ if report_output.is_some() {+ return Err("choose one report output: --html <FILE> or --md <FILE>".into());+ }+ let path = it+ .next()+ .filter(|s| !s.is_empty() && !s.starts_with('-'))+ .ok_or_else(|| {+ format!("{arg} needs an output file; use ./ for a name starting with '-'")+ })?;+ let format = if arg == "--html" {+ crate::map_report::Format::Html+ } else {+ crate::map_report::Format::Markdown+ };+ report_output = Some(crate::map_report::Output {+ path: PathBuf::from(path),+ format,+ redact_paths: false,+ });}+ "--redact-paths" => redact_paths = true,"--code-analyzer" => {let raw = it.next()@@ -1470,6 +1496,23 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {}}+ if report_output.is_some() || redact_paths {+ if sub.as_deref() != Some("map") || folder.is_some() {+ return Err(+ "--html/--md/--redact-paths apply only to `autoindex map` without a folder".into(),+ );+ }+ if report_output.is_none() {+ return Err("--redact-paths requires --html <FILE> or --md <FILE>".into());+ }+ if json || detail_offset.is_some() || detail_limit.is_some() {+ return Err("report output cannot be combined with --json/--offset/--limit; reports use the full fetched catalog selection".into());+ }+ if let Some(output) = &mut report_output {+ output.redact_paths = redact_paths;+ }+ }+let prefix = crate::dataset::sanitize_prefix(&prefix);if prefix.is_empty() {return Err("--prefix must contain at least one [a-z0-9] character".into());@@ -2039,6 +2082,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {sub.as_deref().unwrap_or_default())),(Some("map"), None) => Ok(Cmd::Map(MapCfg {+ report: report_output,url,api_key,prefix: prefix_explicit.then_some(prefix),@@ -2302,6 +2346,34 @@ mod tests {use super::{parse, Approval, Cmd, Duration, ProgressMode, DEFAULT_MAX_MINUTES};use std::path::PathBuf;+ #[test]+ fn map_report_flags_select_export_and_refuse_ambiguous_modes() {+ for flag in ["--html", "--md"] {+ let args = ["map", flag, "report.out", "--redact-paths"];+ let result = parse(args.iter().map(|s| s.to_string()).collect());+ assert!(matches!(result, Ok(Cmd::Map(_))), "{flag}: {result:?}");+ }+ for args in [+ vec!["map", "--html"],+ vec!["map", "--md"],+ vec!["map", "--html", "--json"],+ vec!["map", "--html", "a", "--md", "b"],+ vec!["map", "--html", "a", "--json"],+ vec!["map", "--json", "--md", "a"],+ vec!["map", "--redact-paths"],+ vec!["map", "folder", "--html", "a"],+ vec!["folder", "--html", "a"],+ vec!["status", "--html", "a"],+ vec!["remove", "--prefix", "p", "--html", "a"],+ vec!["map", "--html", "a", "--offset", "1"],+ ] {+ assert!(+ parse(args.iter().map(|s| s.to_string()).collect()).is_err(),+ "{args:?}"+ );+ }+ }+#[test]fn a_bare_autoindex_is_a_usage_error() {let err = parse(Vec::new()).expect_err("bare autoindex must not succeed");diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex d8c7ca76b..731833108 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -33,6 +33,7 @@ pub mod infer;pub mod init;/// `--label`: ingest-time labelling through the node's `/_decide` (#1062).pub mod label;+pub mod map_report;pub mod memory_cli;pub mod neural_cost;pub mod objsource;@@ -13389,6 +13390,7 @@ fn run_remove(cfg: cli::RemoveCfg) -> Result<i32> {}fn run_map(cfg: MapCfg) -> Result<i32> {+ let report_stage = cfg.report.as_ref().map(map_report::prepare).transpose()?;if let Some(note) = &cfg.xerj_url_note {eprintln!("autoindex: {note}");}@@ -13577,6 +13579,13 @@ fn run_map(cfg: MapCfg) -> Result<i32> {junk_files.retain(|f| catalog::file_matches_prefix(f, prefix));duplicate_files.retain(|f| catalog::file_matches_prefix(f, prefix));}+ if let Some(output) = &cfg.report {+ let report =+ map_report::Report::collect(&es, &runs, &datasets, &junk_files, output.redact_paths);+ report.publish(report_stage.expect("report staging was prepared"), output)?;+ println!("report: {}", output.path.display());+ return Ok(0);+ }if cfg.json {let (start, end) =catalog::detail_bounds(datasets.len(), cfg.detail_offset, cfg.detail_limit);diff --git a/engine/crates/xerj-autoindex/src/map_report.css b/engine/crates/xerj-autoindex/src/map_report.cssnew file mode 100644index 000000000..d2d2f1705--- /dev/null+++ b/engine/crates/xerj-autoindex/src/map_report.css@@ -0,0 +1,2 @@+:root{color-scheme:light;--ink:#18324a;--muted:#485d6e;--accent:#145d86;--paper:#fff;--line:#cbdbe6;--wash:#eff5f9}+*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.65 "Avenir Next","Segoe UI",sans-serif}main{max-width:1120px;margin:auto;padding:56px 40px}header{border-left:7px solid var(--accent);padding-left:28px;margin-bottom:36px}.brand{font-weight:700;color:var(--accent);margin:0 0 12px}h1{font-size:clamp(2rem,5vw,3.6rem);line-height:1.12;letter-spacing:-.035em;margin:0 0 20px;max-width:760px}.intro{font-size:1.15rem;color:var(--muted)}aside{background:var(--wash);padding:16px 24px;border-radius:8px;font-size:.9rem}p{max-width:78ch}section{margin:42px 0}h2{font-size:1.5rem;margin:0 0 10px}h3{font-size:1rem;font-weight:600;margin-top:24px}section>p{color:var(--muted);font-size:.92rem}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:8px}table{width:100%;border-collapse:collapse;text-align:left;font-size:.9rem}th{background:var(--wash);font-weight:600;white-space:nowrap}td,th{padding:12px 16px;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}tbody tr:last-child td{border:0}tbody tr:nth-child(even){background:#f8fbfd}pre{background:var(--wash);border-left:3px solid var(--accent);padding:16px 20px;white-space:pre-wrap;overflow-wrap:anywhere}code{font:14px/1.7 "SFMono-Regular",Consolas,monospace}.empty{font-style:italic}footer{margin-top:60px;border-top:1px solid var(--line);padding-top:20px;font-size:.85rem;color:var(--muted)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}@media(max-width:600px){main{padding:28px 18px}header{padding-left:18px}aside{padding:12px 16px}td,th{padding:10px 12px}}@media print{main{padding:0}body{font-size:11pt}.table-wrap{overflow:visible}section{break-inside:avoid}aside{background:none}pre{white-space:pre-wrap}}diff --git a/engine/crates/xerj-autoindex/src/map_report.rs b/engine/crates/xerj-autoindex/src/map_report.rsnew file mode 100644index 000000000..d397cc806--- /dev/null+++ b/engine/crates/xerj-autoindex/src/map_report.rs@@ -0,0 +1,814 @@+//! Offline map exports (#2643). Read-only enrichment; render an allowlist of+//! metadata, never raw catalog JSON, document bodies, credentials or endpoints.+//!+//! Existing contracts used here: catalog.rs:245-279 (dataset metadata),+//! detect/mod.rs:158-170 (file-card graph anchors), and+//! xerj-api/src/graph_api.rs:1374-1397 (overview hubs). This client feature+//! does not link the engine or change its wire/storage contracts.++use crate::esclient::Es;+use anyhow::{bail, Context, Result};+use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};+use std::fmt::Write as _;+use std::io::Write;+use std::path::PathBuf;++const TOP: usize = 10;+const ENRICH_DATASETS: usize = 20;+const ENRICH_BRAINS: usize = 5;++#[derive(Debug, Clone, Copy)]+pub enum Format {+ Html,+ Markdown,+}++#[derive(Debug, Clone)]+pub struct Output {+ pub path: PathBuf,+ pub format: Format,+ pub redact_paths: bool,+}++/// Stage beside the destination, before any node requests. Never overwrite+/// an existing file or follow an output symlink, including a dangling one.+pub(crate) fn prepare(output: &Output) -> Result<tempfile::NamedTempFile> {+ match output.path.symlink_metadata() {+ Ok(_) => bail!("report output already exists; choose a new --html/--md path"),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => return Err(e).context("cannot inspect report output"),+ }+ let parent = output.path.parent().filter(|p| !p.as_os_str().is_empty());+ tempfile::NamedTempFile::new_in(parent.unwrap_or_else(|| std::path::Path::new(".")))+ .context("cannot stage report; choose an existing writable output directory")+}++#[derive(Debug, Default)]+struct Section {+ title: String,+ note: String,+ headers: Vec<String>,+ rows: Vec<Vec<String>>,+}++#[derive(Debug, Default)]+pub(crate) struct Report {+ sections: Vec<Section>,+ questions: Vec<(String, String)>,+ notes: Vec<String>,+}++fn text(v: &Value, field: &str) -> String {+ v.get(field).map_or_else(+ || "unknown".into(),+ |v| match v {+ Value::String(s) => clean(s),+ Value::Number(n) => n.to_string(),+ Value::Array(a) => a+ .iter()+ .filter_map(Value::as_str)+ .map(clean)+ .collect::<Vec<_>>()+ .join(", "),+ _ => "unknown".into(),+ },+ )+}++fn clean(s: &str) -> String {+ s.chars()+ .take(300)+ .map(|c| if c.is_control() { ' ' } else { c })+ .collect()+}++fn enc(s: &str) -> String {+ s.bytes()+ .map(|b| match b {+ b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' => (b as char).to_string(),+ _ => format!("%{b:02X}"),+ })+ .collect()+}++fn quote(s: &str) -> String {+ format!("'{}'", s.replace('\'', "'\"'\"'"))+}++/// Escape both HTML and GFM table metacharacters; no catalog value becomes+/// markup, a URL, a script, an image, or an executable command outside quotes.+fn escape(s: &str) -> String {+ let mut out = String::new();+ for c in s.chars() {+ out.push_str(match c {+ '&' => "&",+ '<' => "<",+ '>' => ">",+ '"' => """,+ '\'' => "'",+ '|' => "|",+ '[' => "[",+ ']' => "]",+ '(' => "(",+ ')' => ")",+ '!' => "!",+ '*' => "*",+ '_' => "_",+ '#' => "#",+ '~' => "~",+ ':' => ":",+ '`' => "`",+ '\\' => "\",+ '\n' | '\r' => " ",+ _ => {+ out.push(c);+ continue;+ }+ });+ }+ out+}++impl Report {+ fn metadata(datasets: &[Value], junk: &[Value], redacted: bool) -> Self {+ let mut report = Self::default();+ report.notes.push(if redacted {+ "File paths and skip reasons are redacted. Dataset/index/format and symbol names remain; review these before sharing."+ } else {+ "Contains dataset/index/format names, symbol names, file paths and skip reasons. No full document bodies or configured credentials/endpoints are exported. Skip reasons can contain excerpts or sensitive metadata. Review before sharing, or use --redact-paths."+ }.into());+ report.notes.push("Catalog snapshot, not a live inventory: at most 500 datasets and 500 skipped-file entries. Counts are per dataset; files shared across datasets are not deduplicated. Lists and enrichments are bounded and may be incomplete.".into());+ report.sections.push(Section {+ title: "Datasets".into(),+ note: format!("{} catalog dataset entries shown.", datasets.len()),+ headers: ["Dataset", "Index", "Records", "Files", "Formats"]+ .map(String::from)+ .into(),+ rows: datasets+ .iter()+ .map(|d| {+ [+ "slug",+ "index_name",+ "record_count",+ "file_count",+ "formats",+ ]+ .map(|f| text(d, f))+ .into()+ })+ .collect(),+ });+ let mut formats = BTreeMap::<String, usize>::new();+ for d in datasets {+ match d.get("formats") {+ Some(Value::Array(a)) => {+ let unique: BTreeSet<_> = a.iter().filter_map(Value::as_str).collect();+ for f in unique {+ *formats.entry(clean(f)).or_default() += 1;+ }+ }+ Some(Value::String(s)) => {+ *formats.entry(clean(s)).or_default() += 1;+ }+ _ => {}+ }+ }+ report.sections.push(Section {+ title: "File families".into(),+ note: "Catalog format labels. A dataset can contain more than one format; these are dataset counts, not file counts.".into(),+ headers: ["Format", "Datasets containing format"].map(String::from).into(),+ rows: formats.into_iter().map(|(f, n)| vec![f, n.to_string()]).collect(),+ });+ report.sections.push(Section {+ title: "Skipped and refused files".into(),+ note: "Catalog exclusions include skipped, junk and refused files. An empty list does not prove every file was indexed.".into(),+ headers: ["Path", "Format", "Status", "Reason"].map(String::from).into(),+ rows: junk.iter().map(|f| vec![+ if redacted { "[path redacted]".into() } else { text(f, "path") },+ text(f, "format"), text(f, "status"),+ if redacted { "[reason omitted: may contain paths]".into() } else { text(f, "reason") },+ ]).collect(),+ });+ report+ }++ pub(crate) fn collect(+ es: &Es,+ runs: &[Value],+ datasets: &[Value],+ junk: &[Value],+ redacted: bool,+ ) -> Self {+ let mut report = Self::metadata(datasets, junk, redacted);+ let prefixes: BTreeSet<_> = runs+ .iter()+ .filter_map(|r| r.get("prefix").and_then(Value::as_str))+ .filter(|p| {+ datasets+ .iter()+ .any(|d| crate::catalog::dataset_matches_prefix(d, p))+ })+ .collect();+ let query_prefix = prefixes.first().copied();+ let mut symbols = Section {+ title: "Top symbols".into(),+ note: format!("Up to {TOP} names per dataset, for the first {ENRICH_DATASETS} datasets. Counts are indexed definition records, not calls or relevance. Only keyword-mapped name fields are aggregated."),+ headers: ["Index", "Symbol", "Definition records"].map(String::from).into(),+ ..Default::default()+ };+ let mut query_terms = Vec::new();+ for d in datasets.iter().take(ENRICH_DATASETS) {+ let Some(index) = d.get("index_name").and_then(Value::as_str) else {+ continue;+ };+ // Inspect the mapping before aggregating: user datasets can have+ // numeric or text `name` fields. Do not invent a keyword subfield.+ let Ok(mapping) = es.get_json(&format!("/{}/_mapping", enc(index))) else {+ report+ .notes+ .push(format!("Symbol mapping unavailable for {}.", clean(index)));+ continue;+ };+ let name = mapping+ .get(index)+ .and_then(|v| v.pointer("/mappings/properties/name"));+ let field = match name {+ Some(v) if v.get("type").and_then(Value::as_str) == Some("keyword") => "name",+ Some(v)+ if v.pointer("/fields/keyword/type").and_then(Value::as_str)+ == Some("keyword") =>+ {+ "name.keyword"+ }+ _ => continue,+ };+ let response = es.search_without_savings(+ index,+ &json!({"size":0,"query":{"exists":{"field":"kind"}},+ "aggs":{"symbols":{"terms":{"field":field,"size":TOP}}}}),+ );+ let Ok(response) = response else {+ report+ .notes+ .push(format!("Symbol counts unavailable for {}.", clean(index)));+ continue;+ };+ let Some(buckets) = response+ .pointer("/aggregations/symbols/buckets")+ .and_then(Value::as_array)+ else {+ report+ .notes+ .push(format!("Symbol counts malformed for {}.", clean(index)));+ continue;+ };+ for bucket in buckets.iter().take(TOP) {+ let Some(name) = bucket.get("key").and_then(Value::as_str) else {+ continue;+ };+ symbols+ .rows+ .push(vec![clean(index), clean(name), text(bucket, "doc_count")]);+ if !name.is_empty()+ && name.chars().count() <= 160+ && !name.chars().any(char::is_control)+ && query_prefix.is_some_and(|p| crate::catalog::dataset_matches_prefix(d, p))+ {+ query_terms.push(name.to_owned());+ }+ }+ }+ report.sections.push(symbols);+ // run_map supplies newest-first runs. A later --no-graph run must+ // not resurrect graph metadata from a superseded run of that prefix.+ let mut seen_prefixes = BTreeSet::new();+ let latest_runs: Vec<_> = runs+ .iter()+ .filter(|r| {+ r.get("prefix").and_then(Value::as_str).is_some_and(|p| {+ datasets+ .iter()+ .any(|d| crate::catalog::dataset_matches_prefix(d, p))+ && seen_prefixes.insert(p)+ })+ })+ .cloned()+ .collect();+ report.graph(es, &latest_runs, datasets, redacted);+ // Suggestions are lexical probes, not generated answers. They reuse+ // observed symbols where available; generic fallbacks are labelled.+ if let Some(prefix) = prefixes.first() {+ query_terms.extend(+ [+ "configuration",+ "error handling",+ "data flow",+ "validation",+ "startup",+ ]+ .map(String::from),+ );+ let mut seen = BTreeSet::new();+ for term in query_terms+ .into_iter()+ .filter(|q| seen.insert(q.clone()))+ .take(5)+ {+ report.questions.push((+ format!("Where is {term} described or implemented?"),+ format!("xerj search --prefix {} {}", quote(prefix), quote(&term)),+ ));+ }+ report.notes.push("Suggested searches are unexecuted lexical probes, not guaranteed answers. Commands use your search client's endpoint/auth settings; select the original node with XERJ_URL if needed. On a multi-prefix map, suggestions target the first prefix alphabetically.".into());+ } else {+ report.notes.push("Search suggestions unavailable: no matching catalog run records a prefix. No prefix was guessed.".into());+ }+ report+ }++ fn graph(&mut self, es: &Es, runs: &[Value], datasets: &[Value], redacted: bool) {+ let mut brains = BTreeSet::new();+ for brain in runs+ .iter()+ .filter_map(|r| r.pointer("/graph/brain").and_then(Value::as_str))+ {+ if brains.contains(brain) {+ continue;+ }+ if brains.len() >= ENRICH_BRAINS {+ break;+ }+ brains.insert(brain);+ // IDs are only unique within an index namespace. Hydrate from+ // selected datasets owned by this brain's recorded prefixes;+ // another prefix's identical file must not supply the location.+ let indices: Vec<_> = datasets+ .iter()+ .filter(|d| {+ runs.iter().any(|r| {+ r.pointer("/graph/brain").and_then(Value::as_str) == Some(brain)+ && r.get("prefix")+ .and_then(Value::as_str)+ .is_some_and(|p| crate::catalog::dataset_matches_prefix(d, p))+ })+ })+ .filter_map(|d| d.get("index_name").and_then(Value::as_str))+ .collect();+ if crate::detect::validate_brain(brain).is_err() {+ self.notes+ .push("Graph metadata contains an invalid brain name; omitted.".into());+ continue;+ }+ let response = es.get_json(&format!("/_graph/{}/overview?top={TOP}", enc(brain)));+ let mut section = Section {+ title: format!("Most-linked files — {}", clean(brain)),+ note: format!("Top {TOP} incoming graph nodes, hydrated only from the selected datasets. Edge counts belong to each node, not a sum over all records in a file. At most {ENRICH_BRAINS} brains are inspected. Relationships are deterministic links, not semantic understanding."),+ headers: ["File", "Incoming live edges"].map(String::from).into(),+ ..Default::default()+ };+ let hubs = response+ .as_ref()+ .ok()+ .and_then(|v| v.pointer("/hubs/in"))+ .and_then(Value::as_array);+ if let Some(hubs) = hubs {+ let ids: Vec<_> = hubs+ .iter()+ .take(TOP)+ .filter_map(|h| h.get("id").and_then(Value::as_str))+ .collect();+ let locations = if ids.is_empty() || indices.is_empty() {+ None+ } else {+ es.search_without_savings(+ &indices.join(","),+ &json!({"size":TOP,"query":{"ids":{"values":ids}},+ "_source":["ax_path","path"]}),+ )+ .ok()+ };+ let mut paths = BTreeMap::new();+ if let Some(hits) = locations+ .as_ref()+ .and_then(|v| v.pointer("/hits/hits"))+ .and_then(Value::as_array)+ {+ for h in hits {+ if let (Some(id), Some(path)) = (+ h.get("_id").and_then(Value::as_str),+ h.pointer("/_source/ax_path")+ .or_else(|| h.pointer("/_source/path"))+ .and_then(Value::as_str),+ ) {+ paths.insert(id, path);+ }+ }+ }+ let mut missing = 0;+ for hub in hubs.iter().take(TOP) {+ if let Some(path) = hub+ .get("id")+ .and_then(Value::as_str)+ .and_then(|id| paths.get(id))+ {+ section.rows.push(vec![+ if redacted {+ "[path redacted]".into()+ } else {+ clean(path)+ },+ text(hub, "live_edges"),+ ]);+ } else {+ missing += 1;+ }+ }+ if missing > 0 {+ section.note.push_str(&format!(" {missing} nodes could not be resolved to a file in this selection and are omitted."));+ }+ } else {+ section.note = "Graph overview unavailable or malformed; this is not evidence that the corpus has no links.".into();+ }+ self.sections.push(section);+ }+ if brains.is_empty() {+ self.notes.push("Graph sections omitted: the selected catalog runs contain no graph metadata (for example, indexed with --no-graph). No graph request was made.".into());+ }+ }++ pub(crate) fn publish(+ &self,+ mut staging: tempfile::NamedTempFile,+ output: &Output,+ ) -> Result<()> {+ let body = match output.format {+ Format::Html => self.html(),+ Format::Markdown => self.markdown(),+ };+ staging+ .write_all(body.as_bytes())+ .context("cannot write staged report")?;+ staging+ .as_file()+ .sync_all()+ .context("cannot sync staged report")?;+ // Reference: sessions.rs:166-170 uses the same no-clobber publish+ // contract. A failure leaves any previous destination untouched.+ staging.persist_noclobber(&output.path).map_err(|_| {+ anyhow::anyhow!(+ "cannot publish report: output exists or is not writable; choose a new path"+ )+ })?;+ Ok(())+ }++ pub(crate) fn markdown(&self) -> String {+ let mut out = String::from(+ "# XERJ data map\n\nAn offline inventory of the selected catalog datasets.\n\n",+ );+ for note in &self.notes {+ let _ = writeln!(out, "{}\n", escape(note));+ }+ for section in &self.sections {+ let _ = writeln!(+ out,+ "## {}\n\n{}\n",+ escape(§ion.title),+ escape(§ion.note)+ );+ if section.rows.is_empty() {+ out.push_str("No entries available.\n\n");+ continue;+ }+ let _ = writeln!(+ out,+ "| {} |",+ section+ .headers+ .iter()+ .map(|s| escape(s))+ .collect::<Vec<_>>()+ .join(" | ")+ );+ let _ = writeln!(+ out,+ "| {} |",+ vec!["---"; section.headers.len()].join(" | ")+ );+ for row in §ion.rows {+ let _ = writeln!(+ out,+ "| {} |",+ row.iter()+ .map(|s| escape(s))+ .collect::<Vec<_>>()+ .join(" | ")+ );+ }+ out.push('\n');+ }+ out.push_str("## Questions to explore\n\nCommands below use POSIX shell quoting.\n\n");+ for (question, command) in &self.questions {+ let _ = writeln!(+ out,+ "{}\n\n<pre><code>{}</code></pre>\n",+ escape(question),+ escape(command)+ );+ }+ if out.ends_with("\n\n") {+ out.pop();+ }+ out+ }++ pub(crate) fn html(&self) -> String {+ let mut out = String::from("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'\"><title>XERJ data map</title><style>");+ out.push_str(include_str!("map_report.css"));+ out.push_str("</style></head><body><main><header><p class=\"brand\">XERJ / Data map</p><h1>A map of what’s indexed.</h1><p class=\"intro\">An offline inventory of the selected catalog datasets.</p></header><aside aria-label=\"Scope and sharing notes\">");+ for note in &self.notes {+ let _ = write!(out, "<p>{}</p>", escape(note));+ }+ out.push_str("</aside>");+ for section in &self.sections {+ let _ = write!(+ out,+ "<section><h2>{}</h2><p>{}</p>",+ escape(§ion.title),+ escape(§ion.note)+ );+ if section.rows.is_empty() {+ out.push_str("<p class=\"empty\">No entries available.</p>");+ } else {+ out.push_str("<div class=\"table-wrap\" tabindex=\"0\"><table><thead><tr>");+ for h in §ion.headers {+ let _ = write!(out, "<th scope=\"col\">{}</th>", escape(h));+ }+ out.push_str("</tr></thead><tbody>");+ for row in §ion.rows {+ out.push_str("<tr>");+ for cell in row {+ let _ = write!(out, "<td>{}</td>", escape(cell));+ }+ out.push_str("</tr>");+ }+ out.push_str("</tbody></table></div>");+ }+ out.push_str("</section>");+ }+ out.push_str(+ "<section><h2>Questions to explore</h2><p>Commands use POSIX shell quoting.</p>",+ );+ for (q, command) in &self.questions {+ let _ = write!(+ out,+ "<h3>{}</h3><pre><code>{}</code></pre>",+ escape(q),+ escape(command)+ );+ }+ out.push_str("</section><footer>Generated by XERJ · Local metadata, ready to review and share.</footer></main></body></html>\n");+ out+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A bounded read-only node: each unexpected endpoint/method fails the+ /// test. No corpus mutation, raw document body or external endpoint is+ /// needed to enrich a report.+ fn node(steps: Vec<(u16, &'static str, Value)>) -> (Es, std::thread::JoinHandle<()>) {+ use std::io::{BufRead, BufReader, Read};+ use std::net::TcpListener;+ use std::time::{Duration, Instant};+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ listener.set_nonblocking(true).unwrap();+ let join = std::thread::spawn(move || {+ for (status, expected, response) in steps {+ let deadline = Instant::now() + Duration::from_secs(30);+ let mut stream = loop {+ match listener.accept() {+ Ok((s, _)) => break s,+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {+ assert!(Instant::now() < deadline, "request missing: {expected}");+ std::thread::sleep(Duration::from_millis(2));+ }+ Err(e) => panic!("accept: {e}"),+ }+ };+ stream.set_nonblocking(false).unwrap();+ stream+ .set_read_timeout(Some(Duration::from_secs(10)))+ .unwrap();+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut line = String::new();+ reader.read_line(&mut line).unwrap();+ assert!(line.starts_with(expected), "{line}");+ let mut length = 0;+ loop {+ let mut header = String::new();+ reader.read_line(&mut header).unwrap();+ if header == "\r\n" || header.is_empty() {+ break;+ }+ if let Some(n) = header.to_ascii_lowercase().strip_prefix("content-length:") {+ length = n.trim().parse::<usize>().unwrap();+ }+ }+ let mut body = vec![0; length];+ reader.read_exact(&mut body).unwrap();+ if length > 0 {+ let request: Value = serde_json::from_slice(&body).unwrap();+ if request.pointer("/query/ids").is_some() {+ assert_eq!(request["_source"], json!(["ax_path", "path"]));+ assert!(request["size"].as_u64().unwrap() <= TOP as u64);+ } else {+ assert_eq!(request["size"], 0);+ }+ }+ let body = response.to_string();+ write!(stream, "HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();+ }+ });+ (Es::new(&url, None).unwrap(), join)+ }++ #[test]+ fn report_enrichment_uses_bounded_metadata_reads_and_scoped_graph_locations() {+ let (es, join) = node(vec![+ (+ 200,+ "GET /p-docs/_mapping",+ json!({"p-docs":{"mappings":{"properties":{"name":{"type":"keyword"}}}}}),+ ),+ (+ 200,+ "POST /p-docs/_search",+ json!({"aggregations":{"symbols":{"buckets":[{"key":"Store","doc_count":2}]}}}),+ ),+ (+ 200,+ "GET /q-docs/_mapping",+ json!({"q-docs":{"mappings":{"properties":{"name":{"type":"keyword"}}}}}),+ ),+ (+ 200,+ "POST /q-docs/_search",+ json!({"aggregations":{"symbols":{"buckets":[{"key":"OtherCorpusSymbol","doc_count":20}]}}}),+ ),+ (+ 200,+ "GET /_graph/p/overview?top=10",+ json!({"hubs":{"in":[{"id":"anchor","live_edges":4},{"id":"foreign","live_edges":9}]}}),+ ),+ (+ 200,+ "POST /p-docs/_search",+ json!({"hits":{"hits":[{"_id":"anchor","_source":{"ax_path":"/private/project/store.rs"}}]}}),+ ),+ ]);+ let runs = [+ json!({"prefix":"p","graph":{"brain":"p"}}),+ json!({"prefix":"q"}),+ ];+ let datasets = [+ json!({"slug":"docs","index_name":"p-docs"}),+ json!({"slug":"docs","index_name":"q-docs"}),+ ];+ let report = Report::collect(&es, &runs, &datasets, &[], true);+ join.join().unwrap();+ let body = report.markdown();+ assert!(body.contains("Store"));+ assert!(body.contains("1 nodes could not be resolved"));+ assert!(body.contains("path redacted"));+ assert!(!body.contains("private/project"));+ assert_eq!(report.questions.len(), 5);+ assert_eq!(report.questions[0].1, "xerj search --prefix 'p' 'Store'");+ assert!(report+ .questions+ .iter()+ .all(|(_, command)| !command.contains("OtherCorpusSymbol")));+ }++ #[test]+ fn optional_read_failure_is_not_misreported_as_no_graph() {+ let (es, join) = node(vec![+ (+ 403,+ "GET /p-docs/_mapping",+ json!({"error":"DENIED_SECRET"}),+ ),+ (+ 403,+ "GET /_graph/p/overview?top=10",+ json!({"error":"DENIED_SECRET"}),+ ),+ ]);+ let report = Report::collect(+ &es,+ &[json!({"prefix":"p","graph":{"brain":"p"}})],+ &[json!({"slug":"docs","index_name":"p-docs"})],+ &[],+ false,+ );+ join.join().unwrap();+ let body = report.markdown();+ assert!(body.contains("Symbol mapping unavailable"));+ assert!(body.contains("Graph overview unavailable"));+ assert!(!body.contains("Graph sections omitted"));+ assert!(!body.contains("DENIED_SECRET"));+ }++ #[test]+ fn no_graph_catalog_does_not_probe_graph_or_guess_symbol_fields() {+ let (es, join) = node(vec![(+ 200,+ "GET /p-docs/_mapping",+ json!({"p-docs":{"mappings":{"properties":{"name":{"type":"long"}}}}}),+ )]);+ let report = Report::collect(+ &es,+ &[+ json!({"prefix":"p"}),+ json!({"prefix":"p", "graph":{"brain":"old"}}),+ ],+ &[json!({"slug":"docs","index_name":"p-docs"})],+ &[],+ false,+ );+ join.join().unwrap();+ assert!(report.markdown().contains("Graph sections omitted"));+ }++ #[test]+ fn reports_escape_markup_and_redact_path_bearing_fields() {+ let ds = json!({"slug":"<script>alert(1)</script>|`x` ", "index_name":"p-docs", "record_count":3,"file_count":2,"formats":["rs","md"], "api_key":"SECRET_KEY", "body":"PRIVATE_FULL_BODY"});+ let junk = json!({"path":"/home/alice/private.rs", "format":"rs", "status":"junk", "reason":"failed at C:\\Users\\alice\\private.rs <img src=x>"});+ let raw = Report::metadata(+ std::slice::from_ref(&ds),+ std::slice::from_ref(&junk),+ false,+ );+ assert!(raw.html().contains("/home/alice/private.rs"));+ for body in [raw.html(), raw.markdown()] {+ assert!(!body.contains("<script>"));+ assert!(!body.contains("<img src=x>"));+ assert!(body.contains("<script>"));+ assert!(body.contains("|"));+ assert!(!body.contains("![remote]"));+ assert!(!body.contains("https://"));+ assert!(!body.contains("SECRET_KEY"));+ assert!(!body.contains("PRIVATE_FULL_BODY"));+ }+ let private = Report::metadata(&[ds], &[junk], true);+ for body in [private.html(), private.markdown()] {+ assert!(!body.contains("alice"));+ assert!(!body.contains("private.rs"));+ assert!(body.contains("path redacted"));+ }+ assert!(!private.html().contains("<script"));+ assert!(!private.html().contains(" src="));+ assert!(!private.html().contains("href="));+ }++ #[test]+ fn report_publication_never_overwrites_and_cleans_staging_on_failure() {+ let dir = tempfile::tempdir().unwrap();+ let output = Output {+ path: dir.path().join("map.html"),+ format: Format::Html,+ redact_paths: false,+ };+ let stage = prepare(&output).unwrap();+ std::fs::write(&output.path, "existing").unwrap();+ assert!(Report::default().publish(stage, &output).is_err());+ assert_eq!(std::fs::read_to_string(&output.path).unwrap(), "existing");+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);+ assert!(prepare(&output).is_err());+ std::fs::remove_file(&output.path).unwrap();+ let stage = prepare(&output).unwrap();+ Report::default().publish(stage, &output).unwrap();+ assert!(std::fs::read_to_string(&output.path)+ .unwrap()+ .starts_with("<!doctype html>"));+ }++ #[cfg(unix)]+ #[test]+ fn report_output_refuses_dangling_symlinks() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("map.html");+ std::os::unix::fs::symlink(dir.path().join("missing"), &path).unwrap();+ assert!(prepare(&Output {+ path,+ format: Format::Html,+ redact_paths: false+ })+ .is_err());+ }+}diff --git a/tools/map-report/README.md b/tools/map-report/README.mdnew file mode 100644index 000000000..a2ecd1b38--- /dev/null+++ b/tools/map-report/README.md@@ -0,0 +1,102 @@+# Share an offline data map++`xerj autoindex map` can export the selected node catalog as one offline HTML+file or a Markdown report. It reads the node; it never indexes, edits or+removes source data. The exported HTML has inline CSS, no JavaScript, remote+fonts or CDN dependencies. Opening either report does not need the node.++For an already indexed prefix, choose a new output filename:++```sh+xerj autoindex map --prefix myproject --html xerj-map.html --redact-paths+xerj autoindex map --prefix myproject --md xerj-map.md --redact-paths+```++Use `--url` and, when needed, `--api-key` for the original node, just as with+the ordinary catalog map. Exporting requires a running node and read access+to its catalog and selected datasets; graph enrichment also needs access to+the recorded brain. There are no additional external services.++Existing outputs, directories and output symlinks are refused. A report is+staged next to its destination and published only after rendering succeeds.+On a missing/unreadable catalog, no report is published. After a successful+write, stdout says `report: <path>`. One invocation writes one format;+`--json`, `--offset`, `--limit`, and a positional folder cannot be combined+with report output. `--dataset` and `--prefix` retain their catalog filters.+Plain map and `--json` output are unchanged when no report flag is given.++## What is in a report++- Datasets, catalog record/file counts, and format labels. Format counts are+ datasets containing that format, not counts of files of that type. Counts+ across datasets need not represent unique files or unique source records.+- Up to ten symbol names per dataset, for the first twenty catalog datasets,+ ranked by indexed definition-record frequency. These are not call counts+ or a measure of importance. Unsupported name mappings are not aggregated.+- Up to ten incoming graph hubs per brain, for at most five brains recorded+ in the latest run of each selected prefix,+ resolved to file paths only inside the selected dataset indices. Counts+ belong to individual nodes, not every record from a file. Unresolved nodes+ are omitted and counted in a note; this is not an exhaustive file-degree+ ranking. With `--dataset`, the graph's top nodes can fall outside the+ selection. Hydration is restricted to datasets of prefixes recorded for+ that brain, so another prefix cannot supply a same-ID file's path. Graph+ data is a deterministic link index. An older graph run is not used when a+ newer run for that prefix has no graph metadata.+- Skipped/junk/refused files and their catalog reasons, capped at 300+ characters per value. Duplicate files are not described as failures.+- Five suggested lexical searches, preferring observed symbol names. Generic+ fallback terms are used when there are fewer symbols. Suggestions have not+ been executed and may return no matches. On a multi-prefix map they target+ the first recorded matching prefix alphabetically. The exact commands use+ POSIX shell quoting and the search client's endpoint/auth configuration;+ set `XERJ_URL` to the source node when the default is not appropriate.++The report inherits the current map fetch limits: at most 500 dataset rows,+500 skipped-file rows and 500 catalog run records. It labels these limits+instead of claiming a full filesystem inventory. Enrichment is best effort:+mapping, symbol-count or graph read failures are shown as unavailable; they+are not proof of an empty corpus. The ordinary map's required catalog reads+still fail normally. `--no-graph` indexed corpora work without graph calls;+their reports say that graph metadata is absent.++## Review before sharing++The default report contains file paths, dataset/index/format and symbol+names, and skip reasons. Reasons can contain short source excerpts or+sensitive metadata. It does not deliberately export full document bodies,+configured API credentials or node URLs. `--redact-paths` hides the full+file-path values and omits skip reasons, including paths embedded in them.+It does **not** anonymize names of datasets, indices, formats, brains or+symbols. Review the resulting report before publishing it.++All variable text is escaped in both formats. The HTML adds a restrictive+content security policy; no catalog text becomes active markup. The node is+only contacted while generating the report, never by the exported page.++## Example and reproduction++Open the [Markdown example](sample.md), or download [the HTML example](sample.html)+and open it in a browser. Both were generated from the committed+[synthetic parcel-ledger fixture](fixture/README.md), with paths redacted.+Their counts are fixture observations, not a performance or quality benchmark.++From repository root, after a scoped binary build, this harness starts its+own temporary lexical node on a random loopback port, copies the fixture,+adds one unsupported binary file, runs dry-run estimates, and indexes it+under separate graph/no-graph prefixes. It uses a 99% disk flood watermark+only for the tiny temporary fixture on a shared development disk. No model,+personal corpus or pre-existing node is used. It removes its temporary data+when finished.++```sh+python3 tools/map-report/smoke.py --binary engine/target/ci-test/xerj+```++The harness checks both output formats, symbols, graph/no-graph notes,+redaction, no-clobber refusals, empty-catalog refusal, and byte-identical+ordinary map/JSON output before and after exports. `--samples-dir <directory>`+writes regenerated redacted samples there. `--runner <es-yaml-runner>` also+runs the compatibility suite on the same executable snapshot first.++[Validation results and review boundary](VERIFICATION.md).diff --git a/tools/map-report/VERIFICATION.md b/tools/map-report/VERIFICATION.mdnew file mode 100644index 000000000..57a1cbe3a--- /dev/null+++ b/tools/map-report/VERIFICATION.md@@ -0,0 +1,153 @@+# Map report verification (#2643)++Written by OpenAI Codex, operated by @Jarvis636431. Verified on macOS arm64,+Rust `1.97.1 (8bab26f4f 2026-07-14)`, source-built XERJ v1.0.0-rc.100.++## Scope and ancestry++Independent branch `feat/2643-map-reports` from upstream `befe92035`.+No dependency on the open CJK judge PR #2635. No engine, storage, API, MCP+schema, dependency, workflow, journal or catalog-format change. The feature+is an autoindex client read/export path. Existing no-flag map and JSON+rendering remain on their original paths.++Submission update: rebased onto upstream `6a7b390ac`, retaining #2697's+MCP batch-response fix and the merged field report #2702. The rebase does+not change the autoindex crate's source tree. The original complete-run+and executable receipts below precede a final output-only correction that+removes the Markdown report's extra terminal blank line. All seven report+tests and the scoped release build were repeated after that correction;+the effective diff was audited again after rebasing. Hosted CI on the+published feature head is separate from these local receipts.++Repository contracts consulted before implementation:++- `engine/crates/xerj-autoindex/src/catalog.rs:245-279`: dataset counts,+ format labels and query metadata.+- `engine/crates/xerj-autoindex/src/detect/mod.rs:158-170`: graph file-card+ anchor identities.+- `engine/crates/xerj-api/src/graph_api.rs:1374-1397`: overview hub shape.+- `engine/crates/xerj-autoindex/src/sessions.rs:166-170`: no-clobber staged+ publication. The report reuses `NamedTempFile::persist_noclobber`.+- `engine/crates/xerj-autoindex/src/esclient.rs:2344-2350`: filtered metadata+ searches with savings accounting disabled, avoiding full body decoding.++These are the repository's Apache-2.0 code; no peer implementation or new+third-party dependency was copied. This is client templating, not new engine+or ranking implementation.++## Tests, builds and static checks++First added the report CLI test to the original implementation and ran it:+`map_report_flags_select_export_and_refuse_ambiguous_modes` failed with+`--html: Err("unknown argument: --html")`. It passes on the candidate.++Run from `engine/` (the TMPDIR setting below is macOS-specific):++```sh+TMPDIR=/private/tmp cargo test --locked --offline --profile ci-test \+ -p xerj-autoindex -- --test-threads=2 \+ --skip content::tests::lossy_display_collisions_keep_distinct_alias_identities \+ --skip corpus_data_skip_tests::corpus_index_summary_splits_indexed_extensions_from_ignored_data \+ --skip inventory_delta_tests::a_non_utf8_excluded_name_is_matched_on_disk_via_path_id+cargo build --locked --offline --release -j 32 -p xerj-autoindex+cargo build --locked --offline --profile ci-test -j 8 -p xerj-server -p es-yaml-runner+cargo fmt --all --check+cargo clippy --locked --offline -p xerj-autoindex --all-targets --no-deps -- -D warnings -A dead_code+```++Candidate crate totals: **1,947 passed, 0 failed, 5 existing ignored,+3 explicit baseline filters**. This includes 1,902 passing library tests+and 45 passing integration tests. All seven new report tests pass. They+cover flag conflicts/missing values, escaped HTML/GFM, redaction, source+allowlisting, read-only bounded enrichment, optional 403 errors, scope+isolation, newer no-graph runs, output races, cleanup and dangling symlinks.++The three filters were reproduced on a clean detached `befe92035` worktree:+**1,895 passed, 3 failed, 2 ignored** in its library suite. The two filename+cases fail with macOS `Illegal byte sequence`; the corpus-summary case has+the same unexpected ignored-directory summary. No existing test, assertion+or committed skip was changed. The first unfiltered candidate run also hit+`/var` versus `/private/var` temporary-root comparisons; canonical TMPDIR+removes those failures without changing source or tests.++Scoped release build, final node/runner build and formatting passed.+Strict Clippy without an allowance refuses the existing unused+`content::resolve_reporting`; the command above has only the existing+command-line `dead_code` allowance and otherwise passes `-D warnings`.+Python syntax, `git diff --check` and the workflow-timeout guard passed+(41 existing jobs across 13 workflow files). No workflow was modified.++## Real private-node checks++From repository root:++```sh+python3 tools/map-report/smoke.py \+ --binary engine/target/ci-test/xerj \+ --runner engine/target/ci-test/es-yaml-runner \+ --samples-dir tools/map-report+```++The harness copies the executable before launch. The tested snapshot SHA-256+was `cf4d62083b07d02fca24ba1c0bffac3ddbf3026e2c9e2b61238770672a6d975b`.+On a fresh private node, ES-YAML reported **1,453 passed, 0 failed,+10 skipped across 233 files**, retaining 74 existing catch-lenient cases.+The runner and node exited 0. No suite or leniency rule was changed.++The same executable then indexed the committed synthetic parcel-ledger+fixture under separate graph/no-graph prefixes. The dry-run reported five+files and 1.4 KB of source; four supported files produced 12 records per+run. One injected binary was junked, so both runs succeeded with exit 3,+`ok=true reason=completed-with-junk`. No source data, pre-existing node,+personal corpus, model or external reranker was used.++HTML/Markdown exports, actual symbol names, graph/no-graph notes, path+redaction, existing-file refusal, empty-catalog refusal and byte-identical+ordinary map/JSON before and after exports passed. The final redacted+examples are `sample.html` and `sample.md`; counts are fixed-fixture+observations, not a throughput or retrieval-quality benchmark.++The same snapshot was then rerun with the expanded harness (without+`--runner`): raw paths and reasons, `--dataset docs` filtering, and distinct+HTML/Markdown file headers also passed for both prefixes. The harness and+node exited 0. The examples were regenerated by this final run.++Browser QA: rendered the HTML at 1280 x 900 and 390 x 844, inspecting the+desktop/mobile screenshots. Both had no page-level horizontal overflow;+the browser recorded zero scripts and zero external resource entries.+On the final sample, Playwright loaded its markup, switched the context+offline, and rendered that markup again: five tables, zero scripts, zero+resource entries, and a 390-pixel document in a 390-pixel viewport. This+checks offline rendering without relying on the automation host's blocked+`file://` navigation.++## Review boundary++Audited against `docs/CONTRIBUTION_REVIEW.md`:++- Effective scope is the client CLI/export module, styles, documentation+ and synthetic fixture/harness; upstream workflows and recovery paths+ remain intact.+- An existing output, including a symlink, is refused before contacting+ the node. Rendering writes into a sibling temporary file and uses+ no-clobber publication; a race leaves the prior destination unchanged.+ Failed required catalog reads leave no destination report.+- Optional enrichment failures are explicit unavailable notes, not empty+ corpus claims. No enrichment error body is copied into a report. Missing graph+ metadata does not trigger graph requests. Hydration uses source path+ fields only, scoped to the brain's selected prefixes.+- Paths and skip reasons are omitted by `--redact-paths`; other metadata+ names deliberately remain visible. HTML/GFM escaping prevents variable+ text from becoming active markup. Commands use POSIX shell quoting and+ do not contain configured endpoints or credentials.+- Durable corpus transitions, legacy-schema migration, distributed writes,+ model execution and accelerator fallbacks are not applicable: the feature+ only reads existing node data and publishes a new local report file.++Not verified: Linux/Windows execution, broad corpus relevance, large-node+latency/memory, a comprehensive global file-degree ranking, anonymity of+metadata names, or hosted CI on a published feature PR. The list bounds and+partial-report behavior are documented; no scale or quality claim is made.++Required single-file session feedback: [#2702](https://github.com/xerj-org/xerj/pull/2702).diff --git a/tools/map-report/fixture/README.md b/tools/map-report/fixture/README.mdnew file mode 100644index 000000000..26d941713--- /dev/null+++ b/tools/map-report/fixture/README.md@@ -0,0 +1,10 @@+# Parcel ledger++A small synthetic Rust project for map report verification.++The [parcel store](src/store.rs) owns in-memory records. The+[library](src/lib.rs) exposes startup and error handling. Sample+[events](data/events.csv) describe successful and refused writes.++Configuration selects the store capacity. Validation rejects empty parcel IDs.+No customer data, credentials, external model or production node is used.diff --git a/tools/map-report/fixture/data/events.csv b/tools/map-report/fixture/data/events.csvnew file mode 100644index 000000000..9ad322df5--- /dev/null+++ b/tools/map-report/fixture/data/events.csv@@ -0,0 +1,4 @@+parcel_id,status,attempts+demo-001,accepted,1+demo-002,refused,2+demo-003,accepted,1diff --git a/tools/map-report/fixture/src/lib.rs b/tools/map-report/fixture/src/lib.rsnew file mode 100644index 000000000..902a845e5--- /dev/null+++ b/tools/map-report/fixture/src/lib.rs@@ -0,0 +1,11 @@+mod store;++/// Start the parcel ledger with an explicitly bounded capacity.+pub fn startup(capacity: usize) -> store::ParcelStore {+ store::ParcelStore::new(capacity)+}++/// Validation happens before a record reaches the store.+pub fn validate_id(id: &str) -> bool {+ !id.trim().is_empty()+}diff --git a/tools/map-report/fixture/src/store.rs b/tools/map-report/fixture/src/store.rsnew file mode 100644index 000000000..772775524--- /dev/null+++ b/tools/map-report/fixture/src/store.rs@@ -0,0 +1,20 @@+/// In-memory storage used only by the synthetic map report fixture.+pub struct ParcelStore {+ capacity: usize,+ ids: Vec<String>,+}++impl ParcelStore {+ pub fn new(capacity: usize) -> Self {+ Self { capacity, ids: Vec::new() }+ }++ /// Return false when validation fails or the configured capacity is full.+ pub fn insert(&mut self, id: String) -> bool {+ if id.trim().is_empty() || self.ids.len() >= self.capacity {+ return false;+ }+ self.ids.push(id);+ true+ }+}diff --git a/tools/map-report/sample.html b/tools/map-report/sample.htmlnew file mode 100644index 000000000..28398ecf2--- /dev/null+++ b/tools/map-report/sample.html@@ -0,0 +1,4 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>XERJ data map</title><style>:root{color-scheme:light;--ink:#18324a;--muted:#485d6e;--accent:#145d86;--paper:#fff;--line:#cbdbe6;--wash:#eff5f9}+*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.65 "Avenir Next","Segoe UI",sans-serif}main{max-width:1120px;margin:auto;padding:56px 40px}header{border-left:7px solid var(--accent);padding-left:28px;margin-bottom:36px}.brand{font-weight:700;color:var(--accent);margin:0 0 12px}h1{font-size:clamp(2rem,5vw,3.6rem);line-height:1.12;letter-spacing:-.035em;margin:0 0 20px;max-width:760px}.intro{font-size:1.15rem;color:var(--muted)}aside{background:var(--wash);padding:16px 24px;border-radius:8px;font-size:.9rem}p{max-width:78ch}section{margin:42px 0}h2{font-size:1.5rem;margin:0 0 10px}h3{font-size:1rem;font-weight:600;margin-top:24px}section>p{color:var(--muted);font-size:.92rem}.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:8px}table{width:100%;border-collapse:collapse;text-align:left;font-size:.9rem}th{background:var(--wash);font-weight:600;white-space:nowrap}td,th{padding:12px 16px;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}tbody tr:last-child td{border:0}tbody tr:nth-child(even){background:#f8fbfd}pre{background:var(--wash);border-left:3px solid var(--accent);padding:16px 20px;white-space:pre-wrap;overflow-wrap:anywhere}code{font:14px/1.7 "SFMono-Regular",Consolas,monospace}.empty{font-style:italic}footer{margin-top:60px;border-top:1px solid var(--line);padding-top:20px;font-size:.85rem;color:var(--muted)}:focus-visible{outline:3px solid var(--accent);outline-offset:4px}@media(max-width:600px){main{padding:28px 18px}header{padding-left:18px}aside{padding:12px 16px}td,th{padding:10px 12px}}@media print{main{padding:0}body{font-size:11pt}.table-wrap{overflow:visible}section{break-inside:avoid}aside{background:none}pre{white-space:pre-wrap}}+</style></head><body><main><header><p class="brand">XERJ / Data map</p><h1>A map of what’s indexed.</h1><p class="intro">An offline inventory of the selected catalog datasets.</p></header><aside aria-label="Scope and sharing notes"><p>File paths and skip reasons are redacted. Dataset/index/format and symbol names remain; review these before sharing.</p><p>Catalog snapshot, not a live inventory: at most 500 datasets and 500 skipped-file entries. Counts are per dataset; files shared across datasets are not deduplicated. Lists and enrichments are bounded and may be incomplete.</p><p>Suggested searches are unexecuted lexical probes, not guaranteed answers. Commands use your search client's endpoint/auth settings; select the original node with XERJ_URL if needed. On a multi-prefix map, suggestions target the first prefix alphabetically.</p></aside><section><h2>Datasets</h2><p>2 catalog dataset entries shown.</p><div class="table-wrap" tabindex="0"><table><thead><tr><th scope="col">Dataset</th><th scope="col">Index</th><th scope="col">Records</th><th scope="col">Files</th><th scope="col">Formats</th></tr></thead><tbody><tr><td>docs</td><td>mapfixture-docs</td><td>9</td><td>3</td><td>code, txt-prose</td></tr><tr><td>data</td><td>mapfixture-data</td><td>3</td><td>1</td><td>csv</td></tr></tbody></table></div></section><section><h2>File families</h2><p>Catalog format labels. A dataset can contain more than one format; these are dataset counts, not file counts.</p><div class="table-wrap" tabindex="0"><table><thead><tr><th scope="col">Format</th><th scope="col">Datasets containing format</th></tr></thead><tbody><tr><td>code</td><td>1</td></tr><tr><td>csv</td><td>1</td></tr><tr><td>txt-prose</td><td>1</td></tr></tbody></table></div></section><section><h2>Skipped and refused files</h2><p>Catalog exclusions include skipped, junk and refused files. An empty list does not prove every file was indexed.</p><div class="table-wrap" tabindex="0"><table><thead><tr><th scope="col">Path</th><th scope="col">Format</th><th scope="col">Status</th><th scope="col">Reason</th></tr></thead><tbody><tr><td>[path redacted]</td><td>binary</td><td>junk</td><td>[reason omitted: may contain paths]</td></tr></tbody></table></div></section><section><h2>Top symbols</h2><p>Up to 10 names per dataset, for the first 20 datasets. Counts are indexed definition records, not calls or relevance. Only keyword-mapped name fields are aggregated.</p><div class="table-wrap" tabindex="0"><table><thead><tr><th scope="col">Index</th><th scope="col">Symbol</th><th scope="col">Definition records</th></tr></thead><tbody><tr><td>mapfixture-docs</td><td>ParcelStore</td><td>1</td></tr><tr><td>mapfixture-docs</td><td>insert</td><td>1</td></tr><tr><td>mapfixture-docs</td><td>new</td><td>1</td></tr><tr><td>mapfixture-docs</td><td>startup</td><td>1</td></tr><tr><td>mapfixture-docs</td><td>store</td><td>1</td></tr><tr><td>mapfixture-docs</td><td>validate_id</td><td>1</td></tr></tbody></table></div></section><section><h2>Most-linked files — fixture</h2><p>Top 10 incoming graph nodes, hydrated only from the selected datasets. Edge counts belong to each node, not a sum over all records in a file. At most 5 brains are inspected. Relationships are deterministic links, not semantic understanding.</p><div class="table-wrap" tabindex="0"><table><thead><tr><th scope="col">File</th><th scope="col">Incoming live edges</th></tr></thead><tbody><tr><td>[path redacted]</td><td>3</td></tr><tr><td>[path redacted]</td><td>2</td></tr><tr><td>[path redacted]</td><td>2</td></tr><tr><td>[path redacted]</td><td>1</td></tr></tbody></table></div></section><section><h2>Questions to explore</h2><p>Commands use POSIX shell quoting.</p><h3>Where is ParcelStore described or implemented?</h3><pre><code>xerj search --prefix 'mapfixture' 'ParcelStore'</code></pre><h3>Where is insert described or implemented?</h3><pre><code>xerj search --prefix 'mapfixture' 'insert'</code></pre><h3>Where is new described or implemented?</h3><pre><code>xerj search --prefix 'mapfixture' 'new'</code></pre><h3>Where is startup described or implemented?</h3><pre><code>xerj search --prefix 'mapfixture' 'startup'</code></pre><h3>Where is store described or implemented?</h3><pre><code>xerj search --prefix 'mapfixture' 'store'</code></pre></section><footer>Generated by XERJ · Local metadata, ready to review and share.</footer></main></body></html>diff --git a/tools/map-report/sample.md b/tools/map-report/sample.mdnew file mode 100644index 000000000..5070bca3e--- /dev/null+++ b/tools/map-report/sample.md@@ -0,0 +1,84 @@+# XERJ data map++An offline inventory of the selected catalog datasets.++File paths and skip reasons are redacted. Dataset/index/format and symbol names remain; review these before sharing.++Catalog snapshot, not a live inventory: at most 500 datasets and 500 skipped-file entries. Counts are per dataset; files shared across datasets are not deduplicated. Lists and enrichments are bounded and may be incomplete.++Suggested searches are unexecuted lexical probes, not guaranteed answers. Commands use your search client's endpoint/auth settings; select the original node with XERJ_URL if needed. On a multi-prefix map, suggestions target the first prefix alphabetically.++## Datasets++2 catalog dataset entries shown.++| Dataset | Index | Records | Files | Formats |+| --- | --- | --- | --- | --- |+| docs | mapfixture-docs | 9 | 3 | code, txt-prose |+| data | mapfixture-data | 3 | 1 | csv |++## File families++Catalog format labels. A dataset can contain more than one format; these are dataset counts, not file counts.++| Format | Datasets containing format |+| --- | --- |+| code | 1 |+| csv | 1 |+| txt-prose | 1 |++## Skipped and refused files++Catalog exclusions include skipped, junk and refused files. An empty list does not prove every file was indexed.++| Path | Format | Status | Reason |+| --- | --- | --- | --- |+| [path redacted] | binary | junk | [reason omitted: may contain paths] |++## Top symbols++Up to 10 names per dataset, for the first 20 datasets. Counts are indexed definition records, not calls or relevance. Only keyword-mapped name fields are aggregated.++| Index | Symbol | Definition records |+| --- | --- | --- |+| mapfixture-docs | ParcelStore | 1 |+| mapfixture-docs | insert | 1 |+| mapfixture-docs | new | 1 |+| mapfixture-docs | startup | 1 |+| mapfixture-docs | store | 1 |+| mapfixture-docs | validate_id | 1 |++## Most-linked files — fixture++Top 10 incoming graph nodes, hydrated only from the selected datasets. Edge counts belong to each node, not a sum over all records in a file. At most 5 brains are inspected. Relationships are deterministic links, not semantic understanding.++| File | Incoming live edges |+| --- | --- |+| [path redacted] | 3 |+| [path redacted] | 2 |+| [path redacted] | 2 |+| [path redacted] | 1 |++## Questions to explore++Commands below use POSIX shell quoting.++Where is ParcelStore described or implemented?++<pre><code>xerj search --prefix 'mapfixture' 'ParcelStore'</code></pre>++Where is insert described or implemented?++<pre><code>xerj search --prefix 'mapfixture' 'insert'</code></pre>++Where is new described or implemented?++<pre><code>xerj search --prefix 'mapfixture' 'new'</code></pre>++Where is startup described or implemented?++<pre><code>xerj search --prefix 'mapfixture' 'startup'</code></pre>++Where is store described or implemented?++<pre><code>xerj search --prefix 'mapfixture' 'store'</code></pre>diff --git a/tools/map-report/smoke.py b/tools/map-report/smoke.pynew file mode 100644index 000000000..2a5475da2--- /dev/null+++ b/tools/map-report/smoke.py@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""Exercise #2643 on synthetic files and an isolated, temporary lexical node.++Optional --samples-dir copies the redacted graph reports there after validation.+No existing node/index or user corpus is read, indexed or deleted.+"""+import argparse+import hashlib+import json+import os+from pathlib import Path+import shutil+import signal+import socket+import subprocess+import tempfile+import time+from urllib.request import build_opener, ProxyHandler+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--binary', type=Path, required=True)+ parser.add_argument('--samples-dir', type=Path)+ parser.add_argument('--runner', type=Path)+ args = parser.parse_args()+ repo = Path(__file__).resolve().parents[2]+ source = args.binary.resolve(strict=True)+ runner = args.runner.resolve(strict=True) if args.runner else None+ samples = args.samples_dir.resolve() if args.samples_dir else None+ env = {k: v for k, v in os.environ.items() if not k.startswith('XERJ_')+ and k.lower() not in ('http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')}+ env.update(XERJ_DISABLE_FEEDBACK='true', XERJ_NUM_CPUS='4')+ opener = build_opener(ProxyHandler({}))+ with tempfile.TemporaryDirectory(prefix='xerj-map-report-') as temp:+ root = Path(temp)+ binary = root / ('xerj.exe' if os.name == 'nt' else 'xerj')+ shutil.copyfile(source, binary)+ binary.chmod(0o700)+ print('Executable SHA-256:', hashlib.sha256(binary.read_bytes()).hexdigest(), flush=True)+ fixture = root / 'fixture'+ shutil.copytree(Path(__file__).parent / 'fixture', fixture)+ (fixture / 'unsupported.bin').write_bytes(b'\0\xff\0\xfe' * 32)+ config = root / 'node.toml'+ config.write_text('[server]\nauto_port = false\n\n[limits]\ndisk_flood_stage_percent = 99\n\n[rerank]\nenabled = false\n')+ env['XERJ_CONFIG'] = str(config)+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', 0))+ port = sock.getsockname()[1]+ assert port <= 65533+ url = f'http://127.0.0.1:{port}'++ def run(command, accepted=(0,), timeout=180):+ result = subprocess.run([str(x) for x in command], cwd=root, env=env,+ capture_output=True, text=True, timeout=timeout)+ assert result.returncode in accepted, (command, result.returncode, result.stdout, result.stderr)+ return result++ def cli(*command, accepted=(0,)):+ return run([binary, *command, '--url', url], accepted=accepted)++ def map_command(prefix, *flags, accepted=(0,)):+ return cli('autoindex', 'map', '--prefix', prefix, *flags, accepted=accepted)++ print(run([binary, '--version']).stdout.strip(), flush=True)+ with (root / 'node.log').open('w') as log:+ node = subprocess.Popen([str(binary), '--insecure', '--port', str(port),+ '--data-dir', str(root / 'data'), '--embed-mode', 'lexical'],+ cwd=root, env=env, stdout=log, stderr=log)+ try:+ deadline = time.monotonic() + 60+ while True:+ assert node.poll() is None, (root / 'node.log').read_text()+ try:+ with opener.open(url + '/_cluster/health', timeout=2):+ break+ except OSError:+ if time.monotonic() > deadline:+ raise TimeoutError('node readiness')+ time.sleep(0.1)+ if runner:+ print(run([runner, '--url', url, '--dir', repo / 'engine/tests/es-compat-yaml/yaml'],+ timeout=900).stdout, flush=True)+ preview = cli('autoindex', fixture, '--dry-run', '--no-semantic', '--no-graph',+ '--state-dir', root / 'preview')+ print('Dry-run estimate:', preview.stdout + preview.stderr, flush=True)+ for prefix, no_graph in [('mapplain', True), ('mapfixture', False)]:+ started = time.monotonic()+ flags = ['--no-graph'] if no_graph else []+ indexed = cli('autoindex', fixture, '--prefix', prefix, '--state-dir', root / prefix,+ '--no-semantic', '--workers', '2', '--yes', *flags, accepted=(0, 3))+ lines = (indexed.stdout + indexed.stderr).splitlines()+ for line in lines:+ if line.startswith(('xerj-bar ', 'xerj-done ')):+ print(line, flush=True)+ assert any(line.startswith('xerj-done ok=true') for line in lines), lines+ assert not any('datasets_refused=' in line for line in lines), lines+ print(f'Indexed {prefix} in {time.monotonic() - started:.2f}s', flush=True)+ before_json = json.loads(map_command(prefix, '--json').stdout)+ before_text = map_command(prefix).stdout+ paths = {}+ for flag, ext in [('--html', 'html'), ('--md', 'md')]:+ path = root / f'{prefix}.{ext}'+ map_command(prefix, flag, path, '--redact-paths')+ body = path.read_text()+ assert 'ParcelStore' in body, body+ assert 'Skipped and refused files' in body+ assert 'path redacted' in body+ assert str(root) not in body+ assert 'unsupported.bin' not in body+ assert 'xerj search --prefix' in body+ assert body.count('Where is ') == 5+ if no_graph:+ assert 'Graph sections omitted' in body+ assert 'Most-linked files' not in body+ else:+ assert 'Most-linked files' in body+ assert 'Incoming live edges' in body+ assert 'overview unavailable' not in body+ if ext == 'html':+ assert body.startswith('<!doctype html>')+ assert '<script' not in body and 'src=' not in body and 'href=' not in body+ else:+ assert body.startswith('# XERJ data map\n')+ original = path.read_bytes()+ refused = map_command(prefix, flag, path, accepted=(1,))+ assert 'already exists' in refused.stderr+ assert path.read_bytes() == original+ paths[ext] = path+ raw_path = root / f'{prefix}-raw.html'+ map_command(prefix, '--html', raw_path)+ raw_body = raw_path.read_text()+ assert 'unsupported.bin' in raw_body+ assert '[reason omitted:' not in raw_body+ selected = root / f'{prefix}-docs.html'+ map_command(prefix, '--dataset', 'docs', '--html', selected, '--redact-paths')+ assert f'{prefix}-docs' in selected.read_text()+ assert f'{prefix}-data' not in selected.read_text()+ assert json.loads(map_command(prefix, '--json').stdout) == before_json+ assert map_command(prefix).stdout == before_text+ missing = root / f'{prefix}-missing.html'+ failure = map_command('missing-corpus', '--html', missing, accepted=(1,))+ assert not missing.exists(), failure+ print(f'PASS {prefix}: HTML/Markdown, raw/redacted paths, dataset scope, graph state, no clobber, unchanged map/JSON, empty-catalog refusal', flush=True)+ if not no_graph and samples:+ samples.mkdir(parents=True, exist_ok=True)+ for ext, path in paths.items():+ shutil.copyfile(path, samples / f'sample.{ext}')+ print('PASS isolated map report lifecycle', flush=True)+ finally:+ if node.poll() is None:+ node.send_signal(signal.SIGTERM)+ try:+ node.wait(timeout=30)+ except subprocess.TimeoutExpired:+ node.kill()+ node.wait()+ raise+ assert node.returncode == 0, (root / 'node.log').read_text()+++if __name__ == '__main__':+ main()