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.

feat(autoindex): relay progress to an agent's user as a drawn bar

xerj-org36b9c1f20552
diff --git a/AGENTS.md b/AGENTS.md
index b41181e4d..193d7a764 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -49,6 +49,45 @@ cannot push at all: [.github/AI_CONTRIBUTIONS.md](./.github/AI_CONTRIBUTIONS.md)
- **Git discipline:** non-trivial changes land with full commit bodies (motivation, before/after numbers, root cause, file pointers) — the git history is the project's engineering log; read it before re-deriving decisions.
- **Review discipline:** before submitting or updating a non-trivial change, run the applicable audit in [docs/CONTRIBUTION_REVIEW.md](./docs/CONTRIBUTION_REVIEW.md). In particular, audit the effective diff and ancestry, preserve existing workflows and recovery paths, test failure atomicity and durable-state transitions, and support user-visible or performance claims with repository-visible evidence.
+## Running an index on someone's machine
+
+`xerj autoindex` is the one command that can occupy a person's laptop for
+minutes while your tool output stays invisible to them. The binary is built to
+be driven by you on their behalf, so the loop is fixed:
+
+1. **Estimate.** `xerj autoindex <folder> --dry-run` walks, sniffs and samples
+ everything and indexes nothing. Report its job-size line
+ (`autoindex: 1995 files (518 MB) under /path`) and give a *range*, never a
+ confident single number for a machine you have not measured.
+2. **Ask, if it is big.** Where the binary has the estimate gate, a run whose
+ estimated upper bound exceeds `--max-minutes` stops before writing
+ anything, prints a JSON decision request on stdout and exits `4`; you put
+ its options to your user and answer with `--approve proceed|fast|cancel`
+ (`--yes` aliases `proceed`). Where it does not — check `--help` — *you* are
+ the gate. Either way, say that stopping is safe: the resume journal plus
+ idempotent `_id`s mean an aborted run resumes and never duplicates.
+3. **Relay the bar.** On a pipe (you), each tick writes two lines in one write:
+ `xerj-bar …` is a self-contained display line meant to be shown to a person
+ **verbatim** — a drawn bar, percent, items, rate, ETA and the file it is
+ waiting on — spaced at most one per 15 s, plus one per phase change and
+ never two closer than 2 s, so it will not flood your transcript.
+ `xerj-progress key=value …` is the machine record on the
+ `--progress-interval` cadence (5 s by default); parse that one.
+ `--progress json` keeps one JSON object per line and carries the same
+ rendered string in a `bar` field.
+4. **Close the loop.** Wait for the single `xerj-done ok=… exit=… reason=…
+ wall=…s` line (it is printed in every progress mode except `none`), then
+ tell the user the **real** elapsed time and what landed.
+
+Exit codes: `0` complete · `3` completed-with-junk — **this is success** · `2`
+usage · `1` any error at all (read the `error:` line before acting) · `4`
+needs a decision (gate above; answer with `--approve`, never a retry). Percent,
+ETA and the drawn bar are honest or absent: `unknown` / `[????…]` when there is
+no denominator, and a full bar only at a real 100%. The full contract, with
+verbatim samples and the failure modes, is under "Running an index for a human"
+in [landing/llms.txt](./landing/llms.txt) (published at
+https://xerj.org/llms.txt).
+
## Where to look
| You want | Go to |
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index 4136e817a..733836ba2 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -164,9 +164,22 @@ pub fn print_help() {
(A run killed by a signal cannot print one either; a missing\n\
terminal line after the process is gone means it died, not that it\n\
finished.)\n\
- --progress plain emits `xerj-progress phase=… pct=… eta_s=…` lines;\n\
+ --progress plain writes TWO lines per tick, in one write:\n\
+ xerj-bar [######################--] 93.4% | index | 8082/8083 items | eta 7s\n\
+ xerj-progress phase=index basis=bytes pct=93.4 items=8082/8083 eta_s=7.2 …\n\
+ `xerj-bar` is the DISPLAY line — self-contained, meant to be shown\n\
+ to a person verbatim by whatever is relaying the run. It is spaced\n\
+ at most one per 15s, plus one per phase change and never two closer\n\
+ than 2s, so it does not flood a transcript. Short phases therefore\n\
+ draw fewer bars than transitions — read the machine line for those.\n\
+ `xerj-progress` is the MACHINE line and keeps\n\
+ the --progress-interval cadence; parse that one. --progress json\n\
+ stays one object per line and carries the same rendered string in\n\
+ a `bar` field.\n\
`pct`/`eta_s` are the literal word `unknown` (JSON null) whenever they\n\
- cannot be computed honestly, never a filler number.\n\
+ cannot be computed honestly, never a filler number — and the drawn\n\
+ bar obeys the same rule: `[????…]` when there is no denominator,\n\
+ and a full bar only at a real 100%.\n\
\n\
RESUME POLICY:\n\
A durable plan supports no-op resume and same-path content replacement.\n\
diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
index 6cc7a4f29..63e0cc0b9 100644
--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs
@@ -2149,6 +2149,36 @@ fn a_run_reports_progress_through_every_phase_and_closes_the_stream() {
"every progress line carries a percent and an ETA field (possibly `unknown`):\n{stream}"
);
+ // ...and the same run hands the agent something it can show a person.
+ // Asserted on the REAL pipeline rather than on a hand-built snapshot.
+ //
+ // This corpus indexes in ~0.3 s, so it is also the end-to-end proof of the
+ // burst floor: every one of its phase changes falls inside `BAR_MIN_GAP`,
+ // and a run that short must therefore relay ONE display line, not one per
+ // phase. The machine lines above already proved every phase is on the
+ // stream — the relay is deliberately quieter than the record.
+ let bars: Vec<&str> = stream
+ .lines()
+ .filter(|line| line.starts_with("xerj-bar "))
+ .collect();
+ assert_eq!(
+ bars.len(),
+ 1,
+ "a sub-2s run relays exactly one bar, whatever its phase count:\n{stream}"
+ );
+ assert!(
+ bars[0].starts_with("xerj-bar [") && bars[0].contains(']'),
+ "the display line carries a drawn bar:\n{stream}"
+ );
+ // The display line is derived, never a second source of truth: it may not
+ // claim completion while the machine line still reports work outstanding.
+ assert!(
+ !bars.iter().any(|line| line.contains("[####")
+ && line.contains("----]")
+ && line.contains("100.0%")),
+ "a partly-drawn bar cannot be labelled 100%:\n{stream}"
+ );
+
let done = stream
.lines()
.find(|line| line.starts_with("xerj-done "))
diff --git a/engine/crates/xerj-autoindex/src/progress.rs b/engine/crates/xerj-autoindex/src/progress.rs
index eb3d7a5da..723b82c7e 100644
--- a/engine/crates/xerj-autoindex/src/progress.rs
+++ b/engine/crates/xerj-autoindex/src/progress.rs
@@ -19,6 +19,38 @@
//! quality gate below is satisfied; otherwise the field is literally
//! `unknown` (`null` in JSON) rather than a comforting number.
//!
+//! # The two lines of the stream surface
+//!
+//! An AI coding agent is the main consumer of the non-terminal surface, and it
+//! has two jobs at once: parse the run, and tell a human what is happening. A
+//! key=value record serves the first and reads as noise in a chat transcript;
+//! a drawn bar serves the second and is miserable to parse. Both were tried in
+//! one line — `xerj-progress bar=[####----] phase=… pct=…` — and the result
+//! satisfies neither: an agent relaying it verbatim pastes twelve internal
+//! fields at its user, and one that strips them is back to rendering its own
+//! bar from `pct`, which is exactly the work this module exists to do once.
+//!
+//! So a tick on [`Surface::Plain`] writes **two lines, in one write**:
+//!
+//! ```text
+//! xerj-bar [######################--] 93.4% | index | 8082/8083 items | 6.6MB/s | eta 7s | waiting on …/tests/util/europarl.lines.txt.gz(9.2MB)
+//! xerj-progress phase=index basis=bytes pct=93.4 items=8082/8083 bytes=136376668/146072142 rate=6965552.1 eta_s=7.2 eta_quality=good … waiting_on=lucene/…/europarl.lines.txt.gz(9.2MB)
+//! ```
+//!
+//! (a real pair, from a 28.8 s / 8,083-file / 253 MB run)
+//!
+//! `xerj-bar` is the relayable view: self-contained, safe to surface verbatim,
+//! and never carrying a number the machine line does not also carry.
+//! `xerj-progress` is unchanged — every reader written against it keeps
+//! working, which is why the bar is a new line rather than a new shape for the
+//! old one. The stream stays parseable because every record is identified by
+//! its leading token; a reader consumes `xerj-progress` / `xerj-done` and
+//! skips what it does not know. `--progress json` keeps its promise of one
+//! object per line by carrying the same rendered string in a `bar` field
+//! instead of beside it.
+//!
+//! The two lines are paced independently — see [`AGENT_BAR_INTERVAL`].
+//!
//! ETA is derived from **bytes**, not from file count. File count is a badly
//! skewed proxy for work — in the corpus that produced #241 the largest single
//! file held 40.4% of all bytes, so a files-done ETA collapses to ~0 while
@@ -60,11 +92,37 @@ const ETA_MAX_STEP: f64 = 0.20;
const STRAGGLER_MAX: usize = 3;
/// Fallback terminal width when `COLUMNS` is unset.
const DEFAULT_COLUMNS: usize = 100;
+/// Cells in the drawn bar on the stream surface.
+const BAR_CELLS: usize = 24;
+/// Cells in the drawn bar on a terminal, where the bar shares a single line
+/// with every other field and the line is truncated to the window.
+const TTY_BAR_CELLS: usize = 12;
+/// Longest straggler description carried on the display line before its middle
+/// is elided. A path is the only unbounded field on that line.
+const DISPLAY_STRAGGLER_MAX: usize = 44;
/// Live-redraw cadence on a terminal.
pub const TTY_INTERVAL: Duration = Duration::from_secs(1);
/// Line cadence for pipes, agents and CI.
pub const STREAM_INTERVAL: Duration = Duration::from_secs(5);
+/// Minimum spacing between two `xerj-bar` display lines.
+///
+/// The two lines of the stream surface are paced independently on purpose.
+/// `xerj-progress` is a machine record and keeps [`STREAM_INTERVAL`], because
+/// that interval is the documented upper bound on silence — lengthening it
+/// would weaken a contract callers rely on. `xerj-bar` is a line an agent
+/// relays *verbatim to a person*, and a person does not want to be told the
+/// same thing every five seconds: at the 5 s default a 30-minute index would
+/// put 360 bars in the transcript, and at this spacing it puts 120. Fifteen
+/// seconds is short enough that a human being read to never wonders whether
+/// the job died, and long enough that the relay is not the loudest thing in
+/// the conversation. It is a judgement about reading, not a measured optimum.
+pub const AGENT_BAR_INTERVAL: Duration = Duration::from_secs(15);
+/// Floor under the burst a phase change can produce: no two display lines
+/// closer together than this. A phase transition is allowed to jump the
+/// spacing above — that is the news worth interrupting for — but a run whose
+/// phases are all short must not turn the relay into a wall of `0.0%` lines.
+pub const BAR_MIN_GAP: Duration = Duration::from_secs(2);
/// `--progress` as the user wrote it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -260,6 +318,13 @@ struct State {
in_flight: Vec<(u64, String, u64)>,
next_seq: u64,
tty_width: usize,
+ /// When the last `xerj-bar` display line was written; `None` before the
+ /// first one.
+ last_bar_at: Option<Instant>,
+ /// A phase change is waiting to be shown. Cleared only when a bar actually
+ /// goes out, so a transition the burst floor swallowed is still drawn on
+ /// the next tick rather than lost.
+ bar_owed: bool,
}
struct Snapshot {
@@ -316,6 +381,8 @@ impl Progress {
in_flight: Vec::new(),
next_seq: 0,
tty_width: 0,
+ last_bar_at: None,
+ bar_owed: false,
}),
stopped: Mutex::new(false),
wake: Condvar::new(),
@@ -383,6 +450,9 @@ impl Progress {
state.rate = None;
state.shown_eta = None;
state.in_flight.clear();
+ // A phase change is the news a relayed bar exists to carry, so it
+ // jumps the display spacing — subject only to the burst floor.
+ state.bar_owed = true;
}
self.items_done.store(0, Ordering::Relaxed);
self.bytes_done.store(0, Ordering::Relaxed);
@@ -635,6 +705,47 @@ impl Progress {
(self.interval * 3).max(Duration::from_secs(15))
}
+ /// Spacing between display bars: at least [`AGENT_BAR_INTERVAL`], and
+ /// never tighter than the tick that produces them — an interval wider than
+ /// the spacing simply draws on every tick.
+ fn bar_interval(&self) -> Duration {
+ self.interval.max(AGENT_BAR_INTERVAL)
+ }
+
+ /// Claim the next display-bar slot, if this tick owns it.
+ ///
+ /// Three rules, in order: the first line of a run always draws; a phase
+ /// change draws as soon as [`BAR_MIN_GAP`] allows; otherwise the spacing
+ /// is [`bar_interval`](Self::bar_interval).
+ ///
+ /// The floor exists because a phase change is *not* rate-limited by the
+ /// tick. A measured 11.8 s run of this tool crossed nine phases and drew
+ /// eight bars, five of them inside the first second — bounded in total but
+ /// a burst in a transcript. A pending transition is not dropped when the
+ /// floor swallows it; it stays owed and draws on the next tick, so the
+ /// human still learns the phase changed.
+ fn bar_slot(&self) -> bool {
+ let now = Instant::now();
+ let target = self.bar_interval();
+ let mut state = self.state.lock().unwrap();
+ let due = match state.last_bar_at {
+ None => true,
+ Some(previous) => {
+ let elapsed = now.duration_since(previous);
+ if state.bar_owed {
+ elapsed >= BAR_MIN_GAP
+ } else {
+ bar_due(elapsed, self.interval, target)
+ }
+ }
+ };
+ if due {
+ state.last_bar_at = Some(now);
+ state.bar_owed = false;
+ }
+ due
+ }
+
fn emit(&self) {
if !self.enabled() {
return;
@@ -645,9 +756,21 @@ impl Progress {
Surface::Json => self
.sink
.write(format!("{}\n", render_json(&snapshot)).as_bytes()),
- Surface::Plain => self
- .sink
- .write(format!("{}\n", render_plain(&snapshot)).as_bytes()),
+ Surface::Plain => {
+ // Both lines of a tick go out in ONE write. They are two views
+ // of a single snapshot, and a pipe splits a write only above
+ // PIPE_BUF (4 KiB on Linux) — well beyond either line — so a
+ // reader never sees a bar torn from the record it describes.
+ let mut out = String::new();
+ if self.bar_slot() {
+ out.push_str("xerj-bar ");
+ out.push_str(&render_bar_line(&snapshot, BAR_CELLS));
+ out.push('\n');
+ }
+ out.push_str(&render_plain(&snapshot));
+ out.push('\n');
+ self.sink.write(out.as_bytes());
+ }
Surface::Tty => {
let body = render_tty(&snapshot);
let width = columns();
@@ -811,8 +934,126 @@ fn fmt_secs(seconds: f64) -> String {
}
}
+/// Is this tick the one that owes a display bar?
+///
+/// Half a tick of tolerance, because ticks land on a timer with jitter: at a
+/// 5 s tick and a 15 s target the third tick can measure 14.998 s, and a bare
+/// `>=` would push every bar to the fourth tick and turn a 15 s spacing into
+/// 20 s. Pure so the spacing rule can be tested without sleeping.
+fn bar_due(elapsed: Duration, tick: Duration, target: Duration) -> bool {
+ elapsed + tick / 2 >= target
+}
+
+/// The drawn bar itself.
+///
+/// **Filled cells are floored, never rounded**, and a completely filled bar is
+/// reserved for a percent that has actually reached 100. Rounding 99.6% up to
+/// a full bar would draw "done" over work that is still running, which is the
+/// same class of comforting lie as an invented ETA. With no denominator the
+/// track is drawn as `?` rather than as an empty bar: an empty bar reads as
+/// 0%, and 0% is a claim this code cannot support.
+///
+/// ASCII `#`/`-` rather than `█`/`░`. `indicatif` defaults to the block pair
+/// (`indicatif-0.17.11/src/style.rs:92`, MIT — read for the technique, not
+/// copied) and offers ASCII sets such as `#>-` / `=>-` for terminals that
+/// cannot render blocks (`:821`, `:933`). This surface is the one that goes to
+/// pipes, CI logs, Windows consoles and an agent's transcript, so the portable
+/// set is the right default here; the flooring rule follows indicatif's own
+/// "rounding down" of filled clusters (`:185`).
+fn bar(percent: Option<f64>, cells: usize) -> String {
+ match percent {
+ None => format!("[{}]", "?".repeat(cells)),
+ Some(percent) => {
+ let clamped = percent.clamp(0.0, 100.0);
+ let mut filled = ((clamped / 100.0) * cells as f64).floor() as usize;
+ if filled >= cells && clamped < 100.0 {
+ filled = cells.saturating_sub(1);
+ }
+ let filled = filled.min(cells);
+ format!("[{}{}]", "#".repeat(filled), "-".repeat(cells - filled))
+ }
+ }
+}
+
+/// `eta 2m10s`, `eta ~2m10s (rough)`, `eta unknown`, `eta unknown (stalled)`.
+/// The word never disappears: a missing ETA field would read as a rendering
+/// fault, while `unknown` is the honest answer and is what the machine line
+/// says too.
+fn display_eta(eta: Eta) -> String {
+ match eta {
+ Eta::Good(seconds) => format!("eta {}", fmt_secs(seconds)),
+ Eta::Rough(seconds) => format!("eta ~{} (rough)", fmt_secs(seconds)),
+ Eta::Unknown => "eta unknown".to_string(),
+ Eta::Stalled => "eta unknown (stalled)".to_string(),
+ }
+}
+
+/// Keep the tail of an over-long straggler description — the end of a path
+/// carries the file name, which is what identifies it.
+///
+/// The cut snaps forward to the next path separator when there is one, so a
+/// real 27 s run's `…ene/tests/util/europarl.lines.txt.gz(9.2MB)` reads as
+/// `…/tests/util/europarl.lines.txt.gz(9.2MB)` instead of inventing a
+/// directory called `ene`.
+fn elide_start(text: &str, max: usize) -> String {
+ let count = text.chars().count();
+ if count <= max {
+ return text.to_string();
+ }
+ let tail: String = text.chars().skip(count - max.saturating_sub(1)).collect();
+ let snapped = match tail.find(['/', '\\']) {
+ Some(cut) => &tail[cut..],
+ None => tail.as_str(),
+ };
+ format!("…{snapped}")
+}
+
+/// The line an agent can relay verbatim: a drawn bar and the four things a
+/// person waiting on a job actually asks — how far, how fast, how long left,
+/// and what it is on right now.
+fn render_bar_line(snapshot: &Snapshot, cells: usize) -> String {
+ let mut line = bar(snapshot.percent, cells);
+ match snapshot.percent {
+ Some(percent) => line.push_str(&format!(" {percent:.1}%")),
+ None => line.push_str(" pct unknown"),
+ }
+ line.push_str(&format!(" | {}", snapshot.phase));
+ if snapshot.items_total > 0 {
+ line.push_str(&format!(
+ " | {}/{} items",
+ snapshot.items_done, snapshot.items_total
+ ));
+ } else if snapshot.items_done > 0 {
+ line.push_str(&format!(" | {} items", snapshot.items_done));
+ }
+ if let Some(rate) = snapshot.rate {
+ match snapshot.basis {
+ Basis::Bytes => line.push_str(&format!(" | {}/s", fmt_bytes(rate as u64))),
+ Basis::Items => line.push_str(&format!(" | {rate:.1} items/s")),
+ Basis::None => {}
+ }
+ }
+ line.push_str(&format!(" | {}", display_eta(snapshot.eta)));
+ if snapshot.waiting_on.len() == 1 {
+ line.push_str(&format!(
+ " | waiting on {}",
+ elide_start(&straggler(&snapshot.waiting_on[0]), DISPLAY_STRAGGLER_MAX)
+ ));
+ } else if snapshot.waiting_on.len() > 1 {
+ line.push_str(&format!(
+ " | waiting on {} items",
+ snapshot.waiting_on.len()
+ ));
+ }
+ line
+}
+
fn render_tty(snapshot: &Snapshot) -> String {
- let mut line = format!("{} ", snapshot.phase);
+ let mut line = format!(
+ "{} {} ",
+ snapshot.phase,
+ bar(snapshot.percent, TTY_BAR_CELLS)
+ );
match snapshot.percent {
Some(percent) => line.push_str(&format!("{percent:5.1}% ")),
None => line.push_str(" ..% "),
@@ -912,6 +1153,10 @@ fn render_json(snapshot: &Snapshot) -> String {
.collect();
serde_json::json!({
"event": "progress",
+ // The same relayable string the `xerj-bar` line carries, as a FIELD —
+ // `--progress json` promises one JSON object per line, so the display
+ // view rides inside the object instead of beside it.
+ "bar": render_bar_line(snapshot, BAR_CELLS),
"phase": snapshot.phase,
"basis": snapshot.basis.as_str(),
"pct": snapshot.percent.map(round1),
@@ -1014,6 +1259,174 @@ mod tests {
assert!(text.contains("items=0/135"), "{text}");
}
+ /// The agent-facing half of the stream: one line a harness can show a
+ /// person verbatim, immediately followed by the machine record it renders,
+ /// both from one snapshot and one write.
+ #[test]
+ fn a_tick_pairs_a_relayable_bar_with_an_unchanged_machine_line() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(3600));
+ progress.phase("index", 1922, 37_004_502);
+ let text = captured(&buffer);
+ let lines: Vec<&str> = text.lines().collect();
+ assert_eq!(lines.len(), 2, "{text}");
+ assert!(lines[0].starts_with("xerj-bar ["), "{text}");
+ // The parse target is untouched — a reader that matched this prefix
+ // before this change matches exactly the same fields after it.
+ assert!(
+ lines[1].starts_with("xerj-progress phase=index basis=bytes pct="),
+ "{text}"
+ );
+ assert!(lines[0].contains("| index |"), "{text}");
+ assert!(lines[0].contains("eta unknown"), "{text}");
+ }
+
+ /// A drawn bar is a claim about how much is done, so it obeys the same
+ /// rule as the percent it accompanies: floored, and never full until the
+ /// work actually is.
+ #[test]
+ fn the_bar_is_floored_and_a_full_bar_means_complete() {
+ assert_eq!(bar(Some(0.0), 10), "[----------]");
+ assert_eq!(bar(Some(41.2), 10), "[####------]");
+ // 9.99 of 10 cells: floors to 9, and the guard keeps the last cell
+ // empty rather than drawing a finished job.
+ assert_eq!(bar(Some(99.9), 10), "[#########-]");
+ assert_eq!(bar(Some(100.0), 10), "[##########]");
+ // Out-of-range input cannot produce a bar of the wrong width.
+ assert_eq!(bar(Some(140.0), 10).chars().count(), 12);
+ assert_eq!(bar(Some(-3.0), 10), "[----------]");
+ }
+
+ /// With no denominator there is nothing to draw, and an empty bar would
+ /// read as 0% — a number this code has not earned.
+ #[test]
+ fn an_unknown_percent_draws_question_marks_not_an_empty_bar() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(3600));
+ progress.phase("walk", 0, 0);
+ let display = captured(&buffer)
+ .lines()
+ .next()
+ .expect("a bar line")
+ .to_string();
+ assert!(display.contains("[????"), "{display}");
+ assert!(display.contains("pct unknown"), "{display}");
+ assert!(!display.contains('#'), "{display}");
+ assert!(!display.contains('%'), "{display}");
+ }
+
+ /// Two cadences, on purpose: the machine line keeps the interval that
+ /// bounds silence, the relayed line is spaced so it does not flood a
+ /// transcript. Driven by moving the clock rather than by sleeping.
+ #[test]
+ fn display_bars_are_spaced_while_the_machine_line_keeps_its_interval() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ progress.phase("index", 100, 1000);
+ for _ in 0..3 {
+ progress.tick();
+ }
+ let text = captured(&buffer);
+ let bars = text.lines().filter(|l| l.starts_with("xerj-bar ")).count();
+ let records = text
+ .lines()
+ .filter(|l| l.starts_with("xerj-progress "))
+ .count();
+ assert_eq!(records, 4, "every tick records: {text}");
+ assert_eq!(bars, 1, "only the phase transition owed a bar: {text}");
+
+ // Age the last bar past the spacing and the next tick draws again.
+ progress.state.lock().unwrap().last_bar_at = Some(Instant::now() - Duration::from_secs(20));
+ progress.tick();
+ let text = captured(&buffer);
+ assert_eq!(
+ text.lines().filter(|l| l.starts_with("xerj-bar ")).count(),
+ 2,
+ "{text}"
+ );
+
+ // The spacing rule itself, at the shipped defaults: the third 5 s tick
+ // owes the bar, the first two do not, and jitter cannot push it to the
+ // fourth.
+ let tick = STREAM_INTERVAL;
+ assert!(!bar_due(Duration::from_secs(5), tick, AGENT_BAR_INTERVAL));
+ assert!(!bar_due(Duration::from_secs(10), tick, AGENT_BAR_INTERVAL));
+ assert!(bar_due(
+ Duration::from_millis(14_998),
+ tick,
+ AGENT_BAR_INTERVAL
+ ));
+ // An interval wider than the spacing draws on every tick instead of
+ // skipping one and going silent for two minutes.
+ let slow = Duration::from_secs(60);
+ assert!(bar_due(
+ Duration::from_secs(60),
+ slow,
+ slow.max(AGENT_BAR_INTERVAL)
+ ));
+ }
+
+ /// A phase change jumps the spacing — but a run whose phases are all short
+ /// must not turn the relay into a wall of `0.0%` lines. Measured on a real
+ /// 11.8 s run: nine phases, five of them inside the first second.
+ #[test]
+ fn a_burst_of_short_phases_cannot_flood_the_relay() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ for phase in ["walk", "hash", "scan", "prepare", "graph", "index"] {
+ progress.phase(phase, 10, 100);
+ }
+ let text = captured(&buffer);
+ assert_eq!(
+ text.lines()
+ .filter(|l| l.starts_with("xerj-progress "))
+ .count(),
+ 6,
+ "every transition is still on the machine line: {text}"
+ );
+ assert_eq!(
+ text.lines().filter(|l| l.starts_with("xerj-bar ")).count(),
+ 1,
+ "six phases inside the 2s floor draw one line, not six: {text}"
+ );
+
+ // The swallowed transition is owed, not dropped: once the floor has
+ // passed, the next tick shows the phase the run is actually in.
+ progress.state.lock().unwrap().last_bar_at = Some(Instant::now() - BAR_MIN_GAP);
+ progress.tick();
+ let display = captured(&buffer)
+ .lines()
+ .rfind(|l| l.starts_with("xerj-bar "))
+ .expect("a bar line")
+ .to_string();
+ assert!(display.contains("| index |"), "{display}");
+ }
+
+ /// What the run is waiting on is the most useful thing on the line and the
+ /// only unbounded field on it.
+ #[test]
+ fn the_relayed_line_names_the_file_and_keeps_a_long_path_bounded() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(3600));
+ progress.phase("index", 3, 30_000_000);
+ let _guard = progress.file(
+ "vendor/github.com/example/very/deeply/nested/module/benches/hdfs.json",
+ 23_488_102,
+ );
+ progress.state.lock().unwrap().last_bar_at = None;
+ progress.tick();
+ let display = captured(&buffer)
+ .lines()
+ .rfind(|line| line.starts_with("xerj-bar "))
+ .expect("a bar line")
+ .to_string();
+ assert!(display.contains("waiting on …/"), "{display}");
+ assert!(display.contains("hdfs.json(22.4MB)"), "{display}");
+ // Snapped to a component boundary, so the elision never invents a
+ // directory name out of the middle of one.
+ assert_eq!(
+ elide_start("a/bbbbbbbbbb/cccccccccc/dddddddddd/ee.txt(1.0KB)", 30),
+ "…/dddddddddd/ee.txt(1.0KB)"
+ );
+ // A last component longer than the budget still yields its tail.
+ assert_eq!(elide_start("aaaaaaaaaaaaaaaa.txt", 10), "…aaaaa.txt");
+ }
+
#[test]
fn percent_is_bytes_based_when_bytes_are_known() {
let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(3600));
@@ -1096,6 +1509,42 @@ mod tests {
assert_eq!(last["files"], 1922);
}
+ /// `--progress json` promises one object per line, so the relayable view
+ /// has to arrive as a field. A JSON consumer must not have to re-derive a
+ /// bar to show its user the same thing a plain consumer sees.
+ #[test]
+ fn json_carries_the_bar_as_a_field_and_stays_one_object_per_line() {
+ let (progress, buffer) = Progress::capture(Surface::Json, Duration::from_secs(3600));
+ progress.phase("index", 4, 1000);
+ for _ in 0..3 {
+ progress.item_done(330);
+ }
+ progress.tick();
+ let text = captured(&buffer);
+ for line in text.lines() {
+ serde_json::from_str::<serde_json::Value>(line)
+ .unwrap_or_else(|e| panic!("{line}: {e}"));
+ }
+ let last: serde_json::Value = serde_json::from_str(text.lines().last().unwrap()).unwrap();
+ let rendered = last["bar"].as_str().expect("a bar field");
+ assert!(rendered.starts_with("[##"), "{rendered}");
+ assert!(rendered.contains("99.0%"), "{rendered}");
+ assert!(rendered.contains("| index | 3/4 items"), "{rendered}");
+ }
+
+ /// The human at a terminal asked for this too — same helper, narrower bar,
+ /// still inside the width the line is truncated to.
+ #[test]
+ fn the_terminal_line_draws_the_same_bar() {
+ let (progress, buffer) = Progress::capture(Surface::Tty, Duration::from_secs(3600));
+ progress.phase("index", 1000, 1_000_000);
+ progress.item_done(500_000);
+ progress.tick();
+ let text = captured(&buffer);
+ assert!(text.contains("index [######------]"), "{text:?}");
+ assert!(text.contains(" 50.0%"), "{text:?}");
+ }
+
/// Exit 3 is success. The stream must say so in words, because an agent
/// reading a bare `3` reads failure.
#[test]
diff --git a/landing/llms.txt b/landing/llms.txt
index cefcab348..2c9f2adc4 100644
--- a/landing/llms.txt
+++ b/landing/llms.txt
@@ -69,6 +69,35 @@ Verified (all numbers trace to recorded runs, 2026-07-09): 80/81 ground-truth ch
If you are an AI coding agent driving XERJ on a person's machine, indexing is the one operation that can occupy their laptop for minutes. They cannot see your tool output — they see you go quiet. Treat it as a job you are running on their behalf: **estimate, tell them, ask if it is big, report progress while it runs, report the real time when it finishes.**
+**The loop, in order.** Each step is a real command with a defined output shape, so you can wire it once instead of improvising every time.
+
+1. **Estimate** — `xerj autoindex <folder> --dry-run` prints the job size (`autoindex: 1995 files (518 MB) under /path`) and the plan, and indexes nothing. Turn it into a *range* for the user (see "Estimate honestly" below).
+2. **Ask, if it is big — and on a binary with the estimate gate (see "Version check" below), it makes you.** Where the gate exists: when the estimate's upper bound exceeds `--max-minutes` and you passed no `--approve`, the run **stops before indexing anything**, writes one JSON decision request to **stdout**, and exits **`4`** (its own code — `1` stays the catch-all for real failures). Nothing has been written to the server at that point.
+3. **Put the options to your user, then answer** — re-invoke the *identical* command plus `--approve proceed` (alias `--yes`), `--approve fast` (adds `--no-semantic --no-graph`), or `--approve cancel` (indexes nothing, exits `0`). "narrower" is not an `--approve` answer: it means re-running against a subdirectory, because `autoindex` has no `--exclude` flag. **An agent that auto-approves without asking has defeated the one mechanism in the tool that protects the person whose laptop this is.**
+4. **Run it and relay** — pass the `xerj-bar` display line through to your user as it arrives (below). Do not paraphrase it into "still working".
+5. **Close the loop** — wait for the single `xerj-done …` line, then report the **measured** wall time and what landed, and offer `xerj autoindex map` as the briefing.
+
+**The decision payload.** One JSON document on stdout, so you never scrape prose (the same information is also printed as human lines for whoever is at the terminal). The keys below are the real ones; the **values are illustrative** and the long `cost` strings are cut — a real payload's numbers come from your user's machine:
+
+```
+{"xerj":"autoindex-decision-request","exit_code":4,"root":"/Users/x/data",
+ "reason":"estimated 6–11 min; its upper bound 11 min exceeds --max-minutes 10",
+ "estimate":{"low_seconds":372.4,"high_seconds":648.1,"basis":"…","workers":8,
+ "planned_files":8083,"planned_bytes":146072142,"coverage":0.93,
+ "families":[…],"unmeasured_families":[…],"excludes":[…]},
+ "estimate_text":"6–11 min","max_minutes":10,
+ "priority_order":[…],"heaviest_directories":[…],
+ "options":[{"id":"proceed","invoke":"--approve proceed (or --yes)","effect":"index everything as planned","cost":"6–11 min"},
+ {"id":"fast","invoke":"--approve fast","effect":"adds --no-semantic --no-graph: …","cost":"speed-up NOT measured by this run. …"},
+ {"id":"narrower","invoke":"re-run as `xerj autoindex <subdirectory>` …","effect":"index only the part that matters","cost":"…"},
+ {"id":"cancel","invoke":"--approve cancel","effect":"index nothing, exit 0","cost":"none — nothing has been written yet"}],
+ "how_to_answer":"re-invoke the identical command with --approve <id> …"}
+```
+
+Two honesty notes the payload states about itself and you should pass on: the estimate is a **range** measured on *that* machine during the dry pass, never a single confident number; and it covers **client-side extraction only** — server-side indexing, embedding and merge time are excluded (`excludes` says so), so treat it as a floor with a shape.
+
+**Version check.** The gate, `--approve`, `--max-minutes` and exit `4` land together in the change that introduces them; no *released* binary through v1.0.0-rc.14 has them, and there a long index simply starts. `xerj autoindex --help` is the authority for the binary in front of you: if it lists `--approve`, steps 2–3 apply; if it does not, **you** are the gate — estimate, ask, and only then run.
+
- **Plan before you index.** `xerj autoindex <folder> --dry-run` walks, sniffs and samples every file, prints the plan, and indexes nothing. The line to report is the job size — `autoindex: 40 files (0 MB) under /path` — followed by the datasets it would create and the junk/skipped counts. Do not read it as the *first* line: a `bulk HTTP request timeout: Ns` line is printed before it, and both go to stderr. It needs a running node. Report the job-size line to your user before you commit their machine to anything. A dry run is read-only for the *index*, not for the disk: it creates the run's state dir, takes an exclusive lock on it and appends a journal record — so it fails if a real run of the same folder is already live, and a dry run before the first real run makes that run announce "resuming from journal".
- **Estimate honestly, from two signals.** (a) The dry run performs the full phase-A pass **only when no plan is frozen yet**; if the journal already holds one — because an earlier run was interrupted — it reuses that plan, returns in under a second and prints the *old* numbers. Treat a suspiciously fast dry run as "no new estimate", and point `--state-dir` at a fresh directory if you need a real one. (b) Recorded reference throughput on one machine: 518 MB / 1,995 files → ~38–51 s; 33.7k records/s on 923 MB (server-bound). Hardware varies widely — Apple Silicon laptops, cold caches, and PDF-heavy or SQL-dump-heavy corpora are much slower per byte than source code. Give the user a range and say it is an estimate; never state a confident single number you have not measured on their machine.
- **If it is going to be long, ask instead of deciding for them.** Present the real trade-off:
@@ -76,14 +105,26 @@ If you are an AI coding agent driving XERJ on a person's machine, indexing is th
* **Fast** — `--no-semantic --no-graph`: skips embedding-backed body fields and relationship detection. You still get typed, queryable BM25 + keyword indices over the same files — a better-than-grep experience for a fraction of the time. (Note: XERJ's default embedder is lexical feature-hashing, not neural, so `--no-semantic` costs you less than the word "semantic" suggests unless the node runs `--embed-mode neural`.)
* **Narrower** — index the subdirectory that matters, or skip `node_modules`/`vendor`/`target`/build outputs. Usually the biggest win available.
* Also useful when their machine must stay usable: `--workers N` and `--pdf-workers N` (which accepts 1–4 only). They bound the **client-side extractor**, not the server — indexing itself runs in the node process, so do not promise a user these cap the machine's total CPU.
-- **Read the progress stream — it is designed for you.** `autoindex` writes its RESULT to stdout and its LIVENESS to stderr, so `--json` stdout stays one clean parseable document while stderr narrates. When stderr is not a terminal (you), you get one line per interval, by default every 5 s: `xerj-progress phase=index basis=bytes pct=1.9 items=250/251 bytes=693420/37004502 rate=152775.9 eta_s=unknown eta_quality=unknown since_progress_s=5.0 phase_elapsed_s=9.5 elapsed_s=10.0 waiting_on=big-events.jsonl(34.6MB)` (a real line from the run that verified this). Use `--progress json` for one JSON object per line, `--progress-interval SECS` to change the cadence, `--progress none` (or `--quiet`) to silence it. Relay `pct`, `eta_s` and `waiting_on` to your user as they arrive.
+- **Read the progress stream — it is designed for you.** `autoindex` writes its RESULT to stdout and its LIVENESS to stderr, so `--json` stdout stays one clean parseable document while stderr narrates. When stderr is not a terminal — which is you — a tick writes **two lines, in one write**: a display line to hand to your user, and the machine line to parse.
+
+```
+xerj-bar [######################--] 93.4% | index | 8082/8083 items | 6.6MB/s | eta 7s | waiting on …/tests/util/europarl.lines.txt.gz(9.2MB)
+xerj-progress phase=index basis=bytes pct=93.4 items=8082/8083 bytes=136376668/146072142 rate=6965552.1 eta_s=7.2 eta_quality=good since_progress_s=0.0 phase_elapsed_s=18.8 elapsed_s=20.0 waiting_on=lucene/lucene/test-framework/src/resources/org/apache/lucene/tests/util/europarl.lines.txt.gz(9.2MB)
+```
+
+(one real pair from the 28.8 s / 8,083-file / 253 MB run that verified this; the display line abbreviates the path the machine line gives in full)
+
+ * **`xerj-bar` is the line for your user — relay it verbatim.** It is self-contained (drawn bar, percent, phase, items, rate, ETA, and the file it is waiting on) and it is spaced: **at most one per 15 s**, plus one per phase change, and never two closer than 2 s apart — so relaying every one of them will not flood a conversation. Do not rebuild your own bar out of `pct`; this one already refuses to lie (see below).
+ * **`xerj-progress` is the line for you — parse this one.** Unchanged, one per `--progress-interval` (5 s by default, and that interval remains the guaranteed upper bound on silence). Match on the leading token and skip lines you do not recognise: the stream also carries `xerj-bar`, unprefixed human notes, and finally `xerj-done`.
+ * **`--progress json` stays one JSON object per line** and carries the same rendered display string in a `bar` field, so a JSON consumer relays the identical thing. `--progress-interval SECS` changes the machine cadence (the bar never draws more often than once per 15 s, but if you set an interval *wider* than 15 s it rides every tick). `--progress none` (or `--quiet`) silences the whole stream.
+ * **The drawn bar is honest too.** No denominator yet → `[????????????????????????] pct unknown`, never an empty bar that reads as 0%. Filled cells are floored, and a completely filled bar appears only at a real 100% — 99.9% still shows an unfilled last cell.
* **`pct` and `eta_s` are honest or absent.** Both can be the literal string `unknown` (JSON `null`) — before a denominator exists, before the estimate has settled, or when nothing has completed recently (`eta_quality=stalled`, meaning one big file is still streaming). Never invent a number to fill the gap; report `waiting_on` instead, which names the file it is actually on.
* **Percent is bytes-based, not file-based.** `items=250/251` with `pct=1.9` is normal and correct: in that measured corpus one 34.6 MB file held 98% of the bytes, so 250 of 251 files done really was 1.9% of the work. A file-count percent would have claimed 99.6% and then sat there.
* **Every run that reaches an exit ends with one terminal line — in every progress mode except `none`** — `xerj-done ok=true exit=3 reason=completed-with-junk wall=57.6s files=1922 records=115139`, and `ok=false … reason=aborted` on the error path. In those modes, wait for it rather than inferring completion from silence. **Do not wait for it under `--quiet` (an alias for `--progress none`)**: quiet prints no progress and no terminal line at all — a successful quiet run writes zero bytes to stderr, and a failing one writes only its `error:` line — so a quiet run is one you poll with `xerj autoindex status --state-dir <dir>` or judge by its exit code. A run killed by a signal cannot print one either, so a process that is gone with no terminal line died; it did not finish.
- **You can still poll from outside.** Start the run in the background with an explicit `--state-dir <dir>`, then poll `xerj autoindex status --state-dir <dir>` with the *same* directory — it prints `N files done, M records, in progress` (or `FINISHED`) plus live per-index doc counts. Passing no `--state-dir` to `status` prints one line per journal under `~/.xerj/autoindex`, including unrelated runs from weeks ago, which is how an agent ends up reporting someone else's progress. `status` has **no** `--json` (only `map` does); parse its text, or poll `GET /_cat/indices` / `GET /ax-*/_count` for machine-readable counts.
- **Stopping is safe, so offer it.** The resume journal plus idempotent `_id`s mean an interrupted run resumes where it stopped and never duplicates. A user may abort a long index without losing the work already done.
-- **Read the exit code correctly.** `0` complete · **`3` completed-with-junk — this is SUCCESS**, junk records are recorded and never fatal; do not report it as a failure · `2` usage error · `1` **any error at all** — it is the catch-all for every failure, so read the `error:` line on stderr before you act. Endpoint-unreachable is only the most common one; a bulk failure, an index-creation conflict, a journal-config mismatch, a state-dir lock conflict, corruption or a disk error all exit 1 too, and restarting the node "because 1 means it is down" will not fix any of them.
-- **Close the loop.** When it finishes, tell the user the actual elapsed time, how many records landed, and what they can now ask — `xerj autoindex map` is the briefing to summarize from.
+- **Read the exit code correctly.** `0` complete · **`3` completed-with-junk — this is SUCCESS**, junk records are recorded and never fatal; do not report it as a failure · `2` usage error · `1` **any error at all** — it is the catch-all for every failure, so read the `error:` line on stderr before you act. Endpoint-unreachable is only the most common one; a bulk failure, an index-creation conflict, a journal-config mismatch, a state-dir lock conflict, corruption or a disk error all exit 1 too, and restarting the node "because 1 means it is down" will not fix any of them. Those four are every code a binary through v1.0.0-rc.14 returns; **`4` means "needs a decision"** — the estimate gate at the top of this section stopped the run before writing anything, and the answer is `--approve`, never a retry. A binary without the gate never returns it.
+- **Close the loop.** When it finishes, tell the user the actual elapsed time — the `wall=` field of the `xerj-done` line is the measured number, so quote that rather than your own estimate — how many records landed, and what they can now ask; `xerj autoindex map` is the briefing to summarize from.
## Use cases