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): estimate on the user's machine, ask before a long run, index what matters first
xerj-org91c1f9cae818
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7851c4917..cc9bce3a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,8 +7,74 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **`autoindex` estimates the job on the user's own machine and hands the+ decision back before it takes their laptop.** Phase A already reads and+ parses every file to sniff and sample it, so it now *times* that work per+ format family and turns it into a range with its basis printed next to it —+ `code 500 files 749.3 MB at 11.7 MB/s measured over 500 file(s) → 64.2 s` —+ rather than a constant calibrated on someone else's hardware. A family is+ priced only from files phase A **provably** read end to end (whole-file+ parsers always; streaming parsers only when the file was under the sampling+ byte cap *and* stopped short of the record cap; never `sqlite`, never+ gzip), and everything else is named under `unmeasured_families` with its+ bytes instead of being priced at another family's rate. If nothing could be+ measured there is no number at all and no gate. The two ends are the+ classical list-scheduling bounds (Graham, 1969) over the phase-B worker+ count that #240's resource policy chose.+ The number is a **floor**, labelled as one on every surface: it covers+ client-side extraction only, because measuring the server, the network or+ embedding would mean writing to the index the estimate exists to ask+ permission for. Measured on a 68 MB source tree the floor was 0.1 s against+ a real 8.9 s run; on a 793 MB one, 64.2 s against ~350 s. The gate therefore+ under-asks and never over-asks, and says so where a reader would otherwise+ mistake silence for a promise.+- **`--max-minutes` (default 10) stops the run and asks instead of deciding.**+ Past the threshold with no answer, autoindex indexes nothing, writes a JSON+ decision request to stdout and exits **4** — a code of its own, because exit+ 1 is already the catch-all for every real failure and an agent must be able+ to tell "choose something" from "your endpoint is down". The payload carries+ the estimate and its basis, file/byte counts, the per-band work order, the+ heaviest directories with real byte counts (flagged when they match the+ vendored/generated rule), and four options: `proceed`, `fast`, `narrower`,+ `cancel`. Answer with `--approve <id>` (`--yes` = proceed), which skips the+ gate; `--max-minutes 0` disables it. A person at a terminal gets the same+ facts as prose plus a prompt; a piped or agent-driven run is **never**+ blocked on stdin, and an unanswerable prompt is a cancel, never consent.+ `--approve fast` really applies `--no-semantic --no-graph`, and `--approve+ narrower` is refused with instructions rather than accepted and ignored+ (#204). The `fast` option states no speed-up factor: it reports the datasets+ and file count it changes and says plainly that this run did not measure the+ factor.+ The gate governs the phase-B route. An **incremental reconcile of an already+ committed generation** (a `--no-graph` re-run over a folder that already has+ one) processes only what changed and publishes from a sealed snapshot, so+ `--max-minutes` does not apply there — and that route now *says so* on+ stderr rather than accepting the flag and quietly not honouring it.+### Changed+- **`autoindex` indexes what matters first.** Phase B's queue was sorted by+ size alone — right about scheduling, silent about value, so a user who+ stopped early got whatever was largest, which on a source tree is+ `node_modules`. Work is now ordered by value band (source and documents →+ configuration → structured data → logs and line files → vendored, generated+ and minified paths), with the old biggest-first rule kept *inside* each band+ so a large file still runs alongside its band instead of becoming the tail;+ a single-worker run goes smallest-first, where there is no tail to hide in.+ One exception keeps the new order from costing wall clock: a file whose own+ extraction outlasts everything ranked above it (`size × workers > the rest`)+ starts first regardless of band. The bands, their file/byte counts and the+ reason each sits where it does are printed with the plan and included in the+ decision payload as `priority_order` — an unexplained order is+ indistinguishable from an arbitrary one. Verified live on a 28 MB mixed+ corpus at two workers: the first second of phase B was spent on+ `src/mod_*.rs`, and the 1.7 MB `node_modules/**` files — the largest in the+ corpus, and therefore *first* under the old rule — drained last.+ Bytes-based progress and its percent are unaffected: reordering does not+ change the denominator.+- **`autoindex` parses each PDF once per fresh run instead of twice.** Phase Aalready paid a *complete* parse for every PDF — `extract::extract` routes`Family::Pdf` straight to the isolated worker and drops the sampling limit,diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 85196c78c..9d3e0c54f 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -1,9 +1,14 @@//! Hand-rolled arg parser (house style of xerj-server — no clap).+use crate::gate::{Approval, DEFAULT_MAX_MINUTES};use crate::progress::ProgressMode;use std::path::PathBuf;use std::time::Duration;+/// Largest `--max-minutes` accepted: one week. Past that the flag is a typo,+/// and `--max-minutes 0` already exists to mean "never ask".+pub const MAX_MAX_MINUTES: u64 = 7 * 24 * 60;+/// Largest `--bulk-mb` accepted. Past this a single bulk body stops being a/// unit of work and starts being a memory incident on the server.pub const MAX_BULK_MB: usize = 24;@@ -38,6 +43,12 @@ pub struct IndexCfg {/// Disable edge detection entirely (no `.xerj-memory-*-edges` writes).pub no_graph: bool,pub dry_run: bool,+ /// Stop and ask before indexing when phase A's measured estimate exceeds+ /// this many minutes. `0` disables the gate outright.+ pub max_minutes: u64,+ /// An answer to a previous decision request. `None` means "nobody has+ /// answered yet", which is what arms the gate.+ pub approve: Option<Approval>,pub json: bool,pub quiet: bool,/// Progress surface. Orthogonal to `json`: `--json` shapes *stdout* (the@@ -84,7 +95,13 @@ a --no-graph state directory written before the generation format must be rebuil--state-dir and --prefix; graph-enabled journals keep the existing crash-resume behaviour";pub fn print_help() {- println!(+ println!("{}", help_text());+}++/// The help text as a value, so tests can assert that a documented flag is+/// still documented instead of trusting a `println!`.+pub fn help_text() -> String {+ format!("xerj autoindex — point it at any folder and make the contents AI-searchable, zero config\n\\n\USAGE:\n\@@ -121,6 +138,14 @@ pub fn print_help() {.xerj-memory-<NAME>-edges (default: folder name slug)\n\--no-graph skip relationship detection (wikilinks, local links,\n\section order, directory chains) — no edges are written\n\+ --max-minutes <N> stop and ask before indexing if phase A's MEASURED estimate\n\+ is longer than this (default 10; 0 disables the gate;\n\+ max 10080). See ESTIMATE + DECISION GATE below.\n\+ --approve <ID> answer a decision request: proceed | fast | cancel.\n\+ `fast` also applies --no-semantic --no-graph. `narrower`\n\+ is NOT accepted here — it means re-running against a\n\+ subdirectory, which this flag cannot do.\n\+ --yes, -y alias for --approve proceed\n\--dry-run walk+sniff+infer, print the plan, index nothing\n\--json machine-readable RESULT on stdout (map: raw catalog docs).\n\Orthogonal to --progress, which owns stderr.\n\@@ -199,6 +224,32 @@ pub fn print_help() {bar obeys the same rule: `[????…]` when there is no denominator,\n\and a full bar only at a real 100%.\n\\n\+ ESTIMATE + DECISION GATE:\n\+ Phase A already reads and parses every file to sniff and sample it, so it\n\+ measures throughput per format family ON THIS MACHINE. autoindex turns that\n\+ into a RANGE (never one confident number) for the indexing phase and prints\n\+ the basis with it. Families phase A never read end to end are named and left\n\+ OUT of the arithmetic instead of being priced at some other family's rate;\n\+ if nothing could be measured, it says so and does not gate.\n\+ The range covers CLIENT-SIDE EXTRACTION only — server indexing, embedding\n\+ and network time are not in it, which is why the gate compares the upper end.\n\+ If that upper end is longer than --max-minutes and no --approve/--yes was\n\+ given, nothing is indexed: a JSON decision request goes to stdout and the\n\+ process exits 4 (a code of its own — 1 is the catch-all for real failures).\n\+ Answer by re-running the same command with --approve proceed|fast|cancel.\n\+ A person at a terminal is prompted instead; a piped or agent-driven run is\n\+ never blocked on stdin.\n\+ \n\+ WORK ORDER:\n\+ Phase B drains source and documents first, then configuration, then\n\+ structured data, then logs and line files, and vendored/generated/minified\n\+ paths last — so stopping early, or searching while it runs, still gives you\n\+ the files you cared about. Inside a band the biggest file starts first (with\n\+ several workers it then runs alongside the rest instead of becoming the\n\+ tail); a single-worker run goes smallest-first instead. One exception: a file\n\+ so large that it outlasts everything ranked above it starts first whatever\n\+ band it is in. The full breakdown is printed with the plan.\n\+ \n\RESUME POLICY:\n\{resume_policy_help}.\n\On a graph-enabled or pre-generation journal the durable plan supports no-op\n\@@ -217,12 +268,15 @@ pub fn print_help() {Validate before switching readers; explicitly clean the shared\n\autoindex-catalog and old target only after validation.\n\\n\- EXIT CODES: 0 complete; 3 completed-with-junk (junk recorded, never fatal);\n\+ EXIT CODES: 0 complete (also: gate answered with --approve cancel);\n\+ 3 completed-with-junk (junk recorded, never fatal);\n\+ 4 NEEDS A DECISION — the estimate exceeded --max-minutes and\n\+ nothing was indexed; a JSON decision request is on stdout;\n\2 usage; 1 endpoint/journal failure, a refused corpus removal, or a\n\refused unsafe state transition\n",fresh_help = FRESH_HELP,resume_policy_help = RESUME_POLICY_HELP- );+ )}pub fn parse(args: Vec<String>) -> Result<Cmd, String> {@@ -252,6 +306,10 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {let mut brain: Option<String> = None;let mut no_graph = false;let mut dry_run = false;+ let mut max_minutes = DEFAULT_MAX_MINUTES;+ let mut max_minutes_explicit = false;+ let mut approve: Option<Approval> = None;+ let mut approve_explicit = false;let mut json = false;let mut quiet = false;let mut progress: Option<ProgressMode> = None;@@ -355,6 +413,53 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {brain = Some(name);}"--no-graph" => no_graph = true,+ "--max-minutes" => {+ max_minutes_explicit = true;+ max_minutes = it+ .next()+ .ok_or("--max-minutes needs a number of minutes (0 disables the gate)")?+ .parse()+ .map_err(|_| {+ format!("--max-minutes needs an integer from 0 to {MAX_MAX_MINUTES}")+ })?;+ if max_minutes > MAX_MAX_MINUTES {+ return Err(format!(+ "--max-minutes must be from 0 to {MAX_MAX_MINUTES} (0 disables the gate)"+ ));+ }+ }+ "--approve" => {+ let raw = it.next().ok_or(+ "--approve needs one of: proceed, fast, cancel (narrower means re-running \+ against a subdirectory)",+ )?;+ let parsed = Approval::parse(&raw)?;+ // Two different answers in one invocation is not something to+ // resolve in either side's favour.+ if let Some(previous) = approve {+ if previous != parsed {+ return Err(format!(+ "--approve {} and --approve {} contradict each other; pass one",+ previous.as_str(),+ parsed.as_str()+ ));+ }+ }+ approve = Some(parsed);+ approve_explicit = true;+ }+ "--yes" | "-y" => {+ if let Some(previous) = approve {+ if previous != Approval::Proceed {+ return Err(format!(+ "--yes means --approve proceed and contradicts --approve {}; pass one",+ previous.as_str()+ ));+ }+ }+ approve = Some(Approval::Proceed);+ approve_explicit = true;+ }"--dry-run" => dry_run = true,"--json" => json = true,"--md" => json = false,@@ -424,7 +529,29 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {);}+ // `--approve fast` is not a hint: it is the answer "index everything, but+ // without the two expensive features", and the run has to actually apply+ // them. Accepting the word and indexing semantically anyway is precisely+ // the accepted-and-silently-ignored class from #204.+ if approve == Some(Approval::Fast) {+ no_semantic = true;+ no_graph = true;+ }+ if approve == Some(Approval::Cancel) && dry_run {+ return Err(+ "--approve cancel and --dry-run contradict each other: a dry run already indexes \+ nothing. Drop one of the two"+ .into(),+ );+ }+match (sub.as_deref(), folder) {+ (Some("map"), _) | (Some("status"), _) if max_minutes_explicit || approve_explicit => {+ Err(format!(+ "--max-minutes/--approve/--yes apply only to indexing, not `autoindex {}`",+ sub.as_deref().unwrap_or_default()+ ))+ }(Some("map"), _) | (Some("status"), _) if progress_explicit => Err(format!("--progress/--progress-interval apply only to indexing, not `autoindex {}`",sub.as_deref().unwrap_or_default()@@ -472,6 +599,8 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {brain,no_graph,dry_run,+ max_minutes,+ approve,json,quiet,progress,@@ -484,7 +613,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {#[cfg(test)]mod tests {- use super::{parse, Cmd, Duration, ProgressMode};+ use super::{parse, Approval, Cmd, Duration, ProgressMode, DEFAULT_MAX_MINUTES};fn index(args: &[&str]) -> super::IndexCfg {match parse(args.iter().map(|s| s.to_string()).collect()).unwrap() {@@ -690,6 +819,130 @@ mod tests {assert!(parse(["map", "--quiet"].into_iter().map(str::to_string).collect()).is_ok());}+ /// The owner's threshold, verbatim: "if estimated more than 10min work+ /// needs to ask AI back what to do".+ #[test]+ fn the_gate_defaults_to_ten_minutes_and_to_unanswered() {+ let cfg = index(&["data"]);+ assert_eq!(DEFAULT_MAX_MINUTES, 10);+ assert_eq!(cfg.max_minutes, 10);+ assert_eq!(cfg.approve, None, "an unanswered run is what arms the gate");+ assert_eq!(index(&["data", "--max-minutes", "45"]).max_minutes, 45);+ // 0 is the documented "never ask" value, not a rejected one.+ assert_eq!(index(&["data", "--max-minutes", "0"]).max_minutes, 0);+ }++ #[test]+ fn an_unusable_max_minutes_is_refused_not_clamped() {+ for args in [+ vec!["data", "--max-minutes"],+ vec!["data", "--max-minutes", "soon"],+ vec!["data", "--max-minutes", "-1"],+ vec!["data", "--max-minutes", "10081"],+ ] {+ let rendered = args.join(" ");+ let err = parse(args.into_iter().map(str::to_string).collect())+ .expect_err(&format!("`{rendered}` must be refused"));+ assert!(err.contains("--max-minutes"), "{err}");+ }+ assert_eq!(+ index(&["data", "--max-minutes", "10080"]).max_minutes,+ 10080+ );+ }++ /// `--approve fast` is an instruction, not a label: the run must really+ /// drop semantic fields and edges. Accepting it and indexing everything+ /// anyway is the #204 defect class.+ #[test]+ fn approve_fast_actually_applies_the_flags_it_names() {+ let cfg = index(&["data", "--approve", "fast"]);+ assert_eq!(cfg.approve, Some(Approval::Fast));+ assert!(cfg.no_semantic, "--approve fast must set --no-semantic");+ assert!(cfg.no_graph, "--approve fast must set --no-graph");+ // The other two answers change nothing about what gets indexed.+ let proceed = index(&["data", "--approve", "proceed"]);+ assert_eq!(proceed.approve, Some(Approval::Proceed));+ assert!(!proceed.no_semantic && !proceed.no_graph);+ assert_eq!(+ index(&["data", "--approve", "cancel"]).approve,+ Some(Approval::Cancel)+ );+ }++ #[test]+ fn yes_is_an_alias_for_approve_proceed() {+ for flag in ["--yes", "-y"] {+ assert_eq!(index(&["data", flag]).approve, Some(Approval::Proceed));+ }+ // Agreeing with yourself twice is fine; disagreeing is not.+ assert_eq!(+ index(&["data", "--yes", "--approve", "proceed"]).approve,+ Some(Approval::Proceed)+ );+ assert!(err(&["data", "--approve", "cancel", "--yes"]).contains("--yes"));+ for contradiction in [+ vec!["data", "--yes", "--approve", "cancel"],+ vec!["data", "--approve", "fast", "--approve", "cancel"],+ ] {+ assert!(err(&contradiction).contains("contradict each other"));+ }+ }++ /// `narrower` is a real option in the decision request and an impossible+ /// one for this flag: it means running against a different folder.+ #[test]+ fn approve_refuses_the_answer_it_cannot_carry_out() {+ let refused = err(&["data", "--approve", "narrower"]);+ assert!(refused.contains("subdirectory"), "{refused}");+ assert!(err(&["data", "--approve", "maybe"]).contains("proceed, fast, cancel"));+ assert!(err(&["data", "--approve"]).contains("--approve"));+ }++ #[test]+ fn cancel_and_dry_run_are_refused_rather_than_silently_merged() {+ let err = err(&["data", "--approve", "cancel", "--dry-run"]);+ assert!(err.contains("already indexes nothing"), "{err}");+ // A dry run may still be told what threshold to report against.+ assert_eq!(+ index(&["data", "--dry-run", "--max-minutes", "3"]).max_minutes,+ 3+ );+ }++ #[test]+ fn gate_flags_are_rejected_for_non_index_subcommands() {+ for args in [+ vec!["map", "--max-minutes", "5"],+ vec!["status", "--approve", "proceed"],+ vec!["--yes", "map"],+ ] {+ let err = parse(args.into_iter().map(str::to_string).collect()).unwrap_err();+ assert!(err.contains("apply only to indexing"), "{err}");+ }+ }++ /// A flag the engine honours but never mentions is only half-shipped, and+ /// the exit code is the one thing an agent cannot discover by trying.+ #[test]+ fn the_help_documents_the_gate_its_exit_code_and_the_work_order() {+ let help = super::help_text();+ for expected in [+ "--max-minutes",+ "--approve <ID>",+ "--yes, -y",+ "0 disables the gate",+ "ESTIMATE + DECISION GATE:",+ "exits 4",+ "4 NEEDS A DECISION",+ "WORK ORDER:",+ "vendored/generated/minified",+ "CLIENT-SIDE EXTRACTION only",+ ] {+ assert!(help.contains(expected), "help is missing {expected:?}");+ }+ }+#[test]fn bulk_timeout_is_rejected_for_non_index_subcommands_in_any_position() {for args in [diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rsindex 59174c85a..4dff48020 100644--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs@@ -273,6 +273,12 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {no_semantic: true,brain: Some("notes".into()),no_graph: false,+ // The gate is switched off in these fixtures on purpose: they assert+ // indexing, resume and edge behaviour, and a timing-derived stop would+ // make them depend on how loaded the runner was. The gate's own+ // behaviour is covered in `gate_tests` and `cli::tests`.+ max_minutes: 0,+ approve: None,dry_run: false,json: false,quiet: true,diff --git a/engine/crates/xerj-autoindex/src/estimate.rs b/engine/crates/xerj-autoindex/src/estimate.rsnew file mode 100644index 000000000..4ffc2d0e8--- /dev/null+++ b/engine/crates/xerj-autoindex/src/estimate.rs@@ -0,0 +1,655 @@+//! How long the rest of this run will take, measured on **this** machine.+//!+//! The rule this module exists to obey: never state a number we did not+//! measure here. A constant calibrated on the maintainers' box is worthless on+//! an Apple Silicon laptop with a cold page cache, and a single confident+//! figure is worse than no figure at all — so this produces a *range* with its+//! basis attached, or it produces nothing and says why.+//!+//! # What is measured+//!+//! Phase A already reads and parses every file to sniff and sample it. That is+//! free evidence, and [`Meter`] collects it: for each file whose extraction+//! phase A **provably ran to completion over the whole file**, it records+//! (family, bytes, elapsed). Files that phase A only partially read contribute+//! nothing to the rate — a partial read timed against a full size would invent+//! throughput the machine never demonstrated.+//!+//! "Provably complete" is decided by [`exact_scan_bytes`], not by assumption:+//!+//! * whole-file extractors (`json`, `html`, `yaml`, `txt-prose`, `code`,+//! `docx`, `pdf`) call `read_whole`/parse the entire container before they+//! emit anything, so a non-junk scan read every byte;+//! * streaming extractors (`jsonl`, `csv`, `logs`, `txt-lines`, `xml`,+//! `sqldump`) stop at whichever of the sampling byte cap or the record cap+//! comes first, so they count only when the file was under the byte cap+//! *and* produced fewer records than the cap — i.e. hit EOF;+//! * `sqlite` is row-capped per table with no byte relationship at all, and+//! gzipped files spend their time on the decompressed stream while `size` is+//! the compressed one, so neither is ever measured.+//!+//! # What the range means+//!+//! Per family, `rate = measured_bytes / measured_seconds`. Per planned file,+//! `work_i = bytes_i / rate_family`. With `W` phase-B workers the makespan of+//! that work is bounded by the classical list-scheduling result (Graham, 1969):+//!+//! ```text+//! low = max(Σ work_i / W, max work_i) // nothing can beat this+//! high = Σ work_i / W + (1 - 1/W) · max work_i+//! ```+//!+//! Both ends therefore come from measured throughput plus arithmetic; neither+//! is a fudge factor.+//!+//! # This is a FLOOR, and it is labelled as one everywhere+//!+//! The range covers **client-side extraction only**. The server's own+//! indexing, embedding and merge time, the network, the NDJSON rendering and+//! relationship detection are not modelled, because autoindex cannot measure+//! any of them without writing to the index — which is exactly the thing the+//! estimate exists to ask permission for. A probe write would buy a better+//! number at the cost of the property that makes stopping safe ("nothing of+//! yours has been touched"), so it is not taken.+//!+//! Two consequences, both stated in the output rather than buried here:+//!+//! * The number is a **lower bound**, not a prediction. Measured on a+//! 68 MB source tree (120 Rust files, 40 Markdown, 15 YAML, 6 log files) on+//! a 32-core box: extraction floor 0.1 s, real wall clock 8.9 s. The floor+//! was ~2% of the truth, because for text families the run is dominated by+//! transport and by the server. It is far closer for PDF/DOCX/SQLite+//! corpora, where client-side parsing genuinely is the job.+//! * So the gate **under-asks and never over-asks**. When it fires, the run is+//! certainly too long; when it does not fire, that is not a promise the run+//! is short — and [`Estimate::headline`] and the decision payload say so in+//! those words. Inventing a multiplier to close the gap would make the gate+//! fire on a number nobody measured, which is the one thing this file exists+//! to prevent.+//!+//! Prior art consulted: quickwit's `ThroughputCalculator`+//! (`quickwit/quickwit-cli/src/tool.rs:977-1012`, Apache-2.0) keeps a windowed+//! `VecDeque<(Instant, u64)>` and reports bytes/s — and stops there, offering+//! no ETA. ClickHouse's `ProgressIndication`+//! (`ClickHouse/src/Common/ProgressIndication.cpp:118-119,223-227`,+//! Apache-2.0) computes `bytes × 1e9 / elapsed_ns` and refuses to draw a bar+//! until 500 ms have passed, so a number is never shown before it is earned.+//! meilisearch's `milli::progress` reports named steps and no ETA whatsoever.+//! None of the three estimates a job *before* running it; that part is ours,+//! and the conservatism above is the price of doing it at all.++use crate::sniff::Family;+use serde::Serialize;+use std::collections::BTreeMap;+use std::sync::Mutex;+use std::time::Duration;++/// Sampling byte cap for the line-oriented streaming families (mirrors+/// `crate::SAMPLE_LIMIT_BYTES`).+const SAMPLE_LIMIT_BYTES: u64 = 4 << 20;+/// Sampling byte cap for SQL dumps (mirrors `crate::SQLDUMP_SAMPLE_LIMIT`).+const SQLDUMP_SAMPLE_LIMIT: u64 = 64 << 20;++/// Bytes phase A **provably** read in full for this file, or `None` when the+/// read was or may have been partial.+///+/// `records` is the number of records the sampler accepted, `sample` the+/// per-group cap it stops at, `gzip` whether the source is compressed.+pub fn exact_scan_bytes(+ family: Family,+ gzip: bool,+ size: u64,+ records: u64,+ sample: usize,+) -> Option<u64> {+ if gzip {+ // `size` is compressed bytes; the parser spent its time on the+ // inflated stream. There is no honest rate to derive from that pair.+ return None;+ }+ let hit_eof = records < sample as u64;+ match family {+ // read_whole()/full-container parsers: a non-junk scan read all of it.+ Family::Json+ | Family::Html+ | Family::Yaml+ | Family::TxtProse+ | Family::Code+ | Family::Docx+ | Family::Pdf => Some(size),+ // Streaming, byte-capped and record-capped.+ Family::Jsonl | Family::Csv | Family::Logs | Family::TxtLines => {+ (size <= SAMPLE_LIMIT_BYTES && hit_eof).then_some(size)+ }+ // Streaming, record-capped only (no byte limit is passed).+ Family::Xml => hit_eof.then_some(size),+ // Grouped: the sink never stops it early, so only the byte cap applies.+ Family::SqlDump => (size <= SQLDUMP_SAMPLE_LIMIT).then_some(size),+ // Row-capped per table; bytes read bear no fixed relation to `size`.+ Family::Sqlite => None,+ // Never extracted at all.+ Family::Binary => None,+ }+}++#[derive(Debug, Default, Clone, Copy)]+struct Acc {+ files: u64,+ bytes: u64,+ nanos: u128,+}++/// Thread-safe collector for phase-A throughput evidence.+///+/// One short lock per scanned file. Phase A spends milliseconds to seconds per+/// file, so the contention is not measurable next to the work it is timing.+#[derive(Debug, Default)]+pub struct Meter {+ inner: Mutex<BTreeMap<&'static str, Acc>>,+}++impl Meter {+ pub fn new() -> Self {+ Self::default()+ }++ /// Record one file whose extraction phase A ran end to end.+ pub fn record(&self, family: Family, bytes: u64, elapsed: Duration) {+ if bytes == 0 {+ // A zero-byte file times the syscall, not the throughput.+ return;+ }+ let mut inner = self.inner.lock().unwrap();+ let acc = inner.entry(family.as_str()).or_default();+ acc.files += 1;+ acc.bytes += bytes;+ acc.nanos += elapsed.as_nanos();+ }++ /// Measured throughput per family. Families with no usable evidence are+ /// simply absent — never present with a guessed rate.+ pub fn rates(&self) -> BTreeMap<&'static str, MeasuredRate> {+ self.inner+ .lock()+ .unwrap()+ .iter()+ .filter_map(|(family, acc)| {+ if acc.nanos == 0 || acc.bytes == 0 {+ return None;+ }+ let seconds = acc.nanos as f64 / 1e9;+ Some((+ *family,+ MeasuredRate {+ files: acc.files,+ bytes: acc.bytes,+ bytes_per_sec: acc.bytes as f64 / seconds,+ },+ ))+ })+ .collect()+ }+}++/// Throughput actually observed for one family during phase A.+#[derive(Debug, Clone, Copy, Serialize)]+pub struct MeasuredRate {+ /// Files this rate was measured over (whole-file reads only).+ pub files: u64,+ /// Bytes those files contained.+ pub bytes: u64,+ pub bytes_per_sec: f64,+}++/// One planned phase-B file, as the estimator sees it.+#[derive(Debug, Clone)]+pub struct PlannedFile {+ pub family: String,+ pub bytes: u64,+}++/// Per-family arithmetic behind the range.+#[derive(Debug, Clone, Serialize)]+pub struct FamilyEstimate {+ pub family: String,+ pub planned_files: u64,+ pub planned_bytes: u64,+ pub measured_files: u64,+ pub measured_bytes: u64,+ pub bytes_per_sec: f64,+ pub seconds_of_work: f64,+}++/// A family with planned bytes and no usable measurement.+#[derive(Debug, Clone, Serialize)]+pub struct UnmeasuredFamily {+ pub family: String,+ pub planned_files: u64,+ pub planned_bytes: u64,+ pub reason: &'static str,+}++/// The estimate, or the honest absence of one.+#[derive(Debug, Clone, Serialize)]+pub struct Estimate {+ /// What kind of number this is. A constant, present so an agent parsing+ /// the payload cannot read `low_seconds` as a prediction of wall clock.+ pub kind: &'static str,+ /// Lower bound in seconds — `None` when nothing could be measured.+ pub low_seconds: Option<f64>,+ /// Upper bound in seconds — `None` when nothing could be measured.+ pub high_seconds: Option<f64>,+ /// One sentence naming what the numbers came from, or why there are none.+ pub basis: String,+ pub workers: usize,+ pub planned_files: u64,+ pub planned_bytes: u64,+ /// Planned bytes belonging to a family with a measured rate.+ pub covered_bytes: u64,+ /// `covered_bytes / planned_bytes`, or `None` when there are no bytes.+ pub coverage: Option<f64>,+ pub families: Vec<FamilyEstimate>,+ pub unmeasured_families: Vec<UnmeasuredFamily>,+ /// Costs deliberately outside the model, named so nobody has to guess.+ pub excludes: Vec<&'static str>,+}++impl Estimate {+ /// Build the estimate from the planned work and the phase-A evidence.+ ///+ /// `workers` is the phase-B worker count the resource policy (#240)+ /// settled on — this module does not re-derive parallelism.+ pub fn compute(+ planned: &[PlannedFile],+ rates: &BTreeMap<&'static str, MeasuredRate>,+ workers: usize,+ ) -> Self {+ let workers = workers.max(1);+ let planned_bytes: u64 = planned.iter().map(|f| f.bytes).sum();+ let planned_files = planned.len() as u64;++ let mut per_family: BTreeMap<&str, (u64, u64)> = BTreeMap::new();+ for file in planned {+ let entry = per_family.entry(file.family.as_str()).or_default();+ entry.0 += 1;+ entry.1 += file.bytes;+ }++ let mut families = Vec::new();+ let mut unmeasured_families = Vec::new();+ let mut covered_bytes = 0u64;+ let mut total_work = 0f64;+ for (family, (files, bytes)) in &per_family {+ match rates.get(family) {+ Some(rate) if rate.bytes_per_sec > 0.0 => {+ let seconds = *bytes as f64 / rate.bytes_per_sec;+ covered_bytes += *bytes;+ total_work += seconds;+ families.push(FamilyEstimate {+ family: (*family).to_string(),+ planned_files: *files,+ planned_bytes: *bytes,+ measured_files: rate.files,+ measured_bytes: rate.bytes,+ bytes_per_sec: rate.bytes_per_sec,+ seconds_of_work: seconds,+ });+ }+ _ => unmeasured_families.push(UnmeasuredFamily {+ family: (*family).to_string(),+ planned_files: *files,+ planned_bytes: *bytes,+ reason: "phase A never read a file of this family end to end on this run, so \+ no throughput was measured for it",+ }),+ }+ }+ families.sort_by(|a, b| {+ b.seconds_of_work+ .total_cmp(&a.seconds_of_work)+ .then_with(|| a.family.cmp(&b.family))+ });+ unmeasured_families.sort_by(|a, b| {+ b.planned_bytes+ .cmp(&a.planned_bytes)+ .then_with(|| a.family.cmp(&b.family))+ });++ // The longest single job — no amount of parallelism divides it.+ let longest = planned+ .iter()+ .filter_map(|file| {+ rates+ .get(file.family.as_str())+ .filter(|rate| rate.bytes_per_sec > 0.0)+ .map(|rate| file.bytes as f64 / rate.bytes_per_sec)+ })+ .fold(0f64, f64::max);++ let coverage = (planned_bytes > 0).then(|| covered_bytes as f64 / planned_bytes as f64);++ if families.is_empty() {+ return Self {+ kind: ESTIMATE_KIND,+ low_seconds: None,+ high_seconds: None,+ basis: if planned_files == 0 {+ "nothing to index".to_string()+ } else {+ format!(+ "no estimate: phase A did not read any of the {planned_files} planned \+ file(s) end to end, so no throughput was measured on this machine. \+ Families seen: {}",+ unmeasured_families+ .iter()+ .map(|f| f.family.as_str())+ .collect::<Vec<_>>()+ .join(", ")+ )+ },+ workers,+ planned_files,+ planned_bytes,+ covered_bytes,+ coverage,+ families,+ unmeasured_families,+ excludes: EXCLUDES.to_vec(),+ };+ }++ let parallel = total_work / workers as f64;+ let low = parallel.max(longest);+ let high = parallel + longest * (1.0 - 1.0 / workers as f64);++ let measured_files: u64 = families.iter().map(|f| f.measured_files).sum();+ let measured_bytes: u64 = families.iter().map(|f| f.measured_bytes).sum();+ let basis = format!(+ "measured on this machine during phase A: {measured_files} file(s) / {} read end to \+ end across {} family/families, scheduled over {workers} worker(s). Covers {} of the \+ {} planned ({}). Client-side extraction only.",+ human_bytes(measured_bytes),+ families.len(),+ human_bytes(covered_bytes),+ human_bytes(planned_bytes),+ match coverage {+ Some(fraction) => format!("{:.0}% of planned bytes", fraction * 100.0),+ None => "no planned bytes".to_string(),+ }+ );++ Self {+ kind: ESTIMATE_KIND,+ low_seconds: Some(low),+ high_seconds: Some(high),+ basis,+ workers,+ planned_files,+ planned_bytes,+ covered_bytes,+ coverage,+ families,+ unmeasured_families,+ excludes: EXCLUDES.to_vec(),+ }+ }++ /// The bound the gate compares against: the top of the range. The whole+ /// range is a floor, so taking its upper end is the least+ /// under-conservative reading available.+ pub fn gate_seconds(&self) -> Option<f64> {+ self.high_seconds+ }++ /// `14.2 min–19.8 min`, or an honest sentence when there is no number.+ /// Bare — always print it through [`Estimate::headline`] where a reader+ /// could mistake it for a prediction.+ pub fn range_text(&self) -> String {+ match (self.low_seconds, self.high_seconds) {+ (Some(low), Some(high)) => format!("{}–{}", human_secs(low), human_secs(high)),+ _ => "no estimate (see basis)".to_string(),+ }+ }++ /// The range with what it is stapled to it. Every surface that shows a+ /// user or an agent a number uses this, because "14 min" and "at least+ /// 14 min" are different promises and only the second one is true.+ pub fn headline(&self) -> String {+ match self.low_seconds {+ Some(_) => format!(+ "at least {} — a MEASURED FLOOR for client-side extraction, not a prediction of \+ the whole run: server indexing, embedding and network time are not in it",+ self.range_text()+ ),+ None => format!("no estimate — {}", self.basis),+ }+ }++ /// The estimate re-run over a subset of the planned work, so an option+ /// like "index only this subdirectory" can be costed with the same+ /// measured rates instead of a new guess.+ pub fn recompute_subset(+ &self,+ planned: &[PlannedFile],+ rates: &BTreeMap<&'static str, MeasuredRate>,+ ) -> Self {+ Self::compute(planned, rates, self.workers)+ }+}++/// Stamped on every [`Estimate`]: this is a lower bound on client-side+/// extraction, never a prediction of the run's wall clock.+pub const ESTIMATE_KIND: &str = "client-side-extraction-floor";++const EXCLUDES: &[&str] = &[+ "server-side indexing, embedding and merge time (autoindex cannot measure it without writing)",+ "network round trips to the endpoint",+ "relationship detection and edge writes (--no-graph removes these)",+ "families with no end-to-end read in phase A, listed under unmeasured_families",+];++/// `1.4 GB`, `812.0 MB`, `4.0 KB`, `37 B`.+pub fn human_bytes(bytes: u64) -> String {+ const UNITS: [(&str, u64); 3] = [("GB", 1 << 30), ("MB", 1 << 20), ("KB", 1 << 10)];+ for (unit, scale) in UNITS {+ if bytes >= scale {+ return format!("{:.1} {unit}", bytes as f64 / scale as f64);+ }+ }+ format!("{bytes} B")+}++/// `3.2 s`, `4.7 min`, `1.9 h`.+pub fn human_secs(seconds: f64) -> String {+ if seconds < 90.0 {+ format!("{seconds:.1} s")+ } else if seconds < 5400.0 {+ format!("{:.1} min", seconds / 60.0)+ } else {+ format!("{:.1} h", seconds / 3600.0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rate(family: &'static str, bytes_per_sec: f64) -> (&'static str, MeasuredRate) {+ (+ family,+ MeasuredRate {+ files: 10,+ bytes: 1 << 20,+ bytes_per_sec,+ },+ )+ }++ fn planned(family: &str, bytes: u64, count: usize) -> Vec<PlannedFile> {+ (0..count)+ .map(|_| PlannedFile {+ family: family.to_string(),+ bytes,+ })+ .collect()+ }++ /// The two bounds are Graham's, computed from measured throughput and+ /// nothing else.+ #[test]+ fn the_range_is_the_scheduling_bound_on_measured_work() {+ // 4 files × 100 bytes at 100 B/s = 1 s each, 4 s of work, 2 workers.+ let rates = BTreeMap::from([rate("code", 100.0)]);+ let estimate = Estimate::compute(&planned("code", 100, 4), &rates, 2);+ let low = estimate.low_seconds.unwrap();+ let high = estimate.high_seconds.unwrap();+ // parallel = 4/2 = 2; longest = 1.+ assert!((low - 2.0).abs() < 1e-9, "{low}");+ assert!((high - 2.5).abs() < 1e-9, "{high}");+ assert!(low <= high);+ assert_eq!(estimate.coverage, Some(1.0));+ assert!(estimate.basis.contains("measured on this machine"));+ }++ /// One dominant file cannot be divided by the worker count. The lower+ /// bound has to say so, or the gate under-asks on exactly the corpus that+ /// most deserves a question.+ #[test]+ fn one_enormous_file_sets_the_floor_however_many_workers_there_are() {+ let rates = BTreeMap::from([rate("sqldump", 1.0)]);+ let mut work = planned("sqldump", 1_000, 1);+ work.extend(planned("sqldump", 1, 100));+ let estimate = Estimate::compute(&work, &rates, 64);+ // total work 1100 s over 64 workers = 17.2 s, but one job is 1000 s.+ assert!(estimate.low_seconds.unwrap() >= 1000.0);+ assert!(estimate.high_seconds.unwrap() >= estimate.low_seconds.unwrap());+ }++ /// The rule that keeps this module honest: no measurement, no number.+ #[test]+ fn an_unmeasurable_corpus_produces_no_number_at_all() {+ let estimate = Estimate::compute(&planned("pdf", 5_000, 3), &BTreeMap::new(), 8);+ assert_eq!(estimate.low_seconds, None);+ assert_eq!(estimate.high_seconds, None);+ assert!(estimate.gate_seconds().is_none());+ assert!(+ estimate.basis.starts_with("no estimate:"),+ "{}",+ estimate.basis+ );+ assert!(estimate.basis.contains("pdf"));+ assert_eq!(estimate.coverage, Some(0.0));+ assert_eq!(estimate.unmeasured_families.len(), 1);+ assert_eq!(estimate.range_text(), "no estimate (see basis)");+ }++ /// Partial coverage is reported as partial, not silently extrapolated onto+ /// the families nobody timed.+ #[test]+ fn unmeasured_families_are_named_and_excluded_from_the_arithmetic() {+ let rates = BTreeMap::from([rate("code", 1_000.0)]);+ let mut work = planned("code", 1_000, 1);+ work.extend(planned("sqlite", 9_000, 1));+ let estimate = Estimate::compute(&work, &rates, 1);+ assert_eq!(estimate.covered_bytes, 1_000);+ assert_eq!(estimate.planned_bytes, 10_000);+ assert_eq!(estimate.coverage, Some(0.1));+ assert_eq!(estimate.unmeasured_families[0].family, "sqlite");+ assert!(estimate.basis.contains("10%"));+ // The sqlite bytes contribute NO seconds — an estimate that quietly+ // priced them at the code rate would be a fabrication.+ assert!((estimate.low_seconds.unwrap() - 1.0).abs() < 1e-9);+ }++ #[test]+ fn an_empty_plan_says_so_instead_of_dividing_by_zero() {+ let estimate = Estimate::compute(&[], &BTreeMap::new(), 8);+ assert_eq!(estimate.basis, "nothing to index");+ assert_eq!(estimate.coverage, None);+ assert_eq!(estimate.low_seconds, None);+ }++ #[test]+ fn a_subset_is_costed_with_the_same_measured_rates() {+ let rates = BTreeMap::from([rate("code", 100.0)]);+ let full = Estimate::compute(&planned("code", 100, 10), &rates, 1);+ let half = full.recompute_subset(&planned("code", 100, 5), &rates);+ assert_eq!(half.workers, full.workers);+ assert!((half.low_seconds.unwrap() * 2.0 - full.low_seconds.unwrap()).abs() < 1e-9);+ }++ /// Only reads phase A can prove were complete may be timed.+ #[test]+ fn exact_scan_bytes_admits_only_provably_complete_reads() {+ // Whole-file parsers: always the full size.+ for family in [+ Family::Json,+ Family::Html,+ Family::Yaml,+ Family::TxtProse,+ Family::Code,+ Family::Docx,+ Family::Pdf,+ ] {+ assert_eq!(exact_scan_bytes(family, false, 900, 500, 500), Some(900));+ }+ // Streaming + byte-capped: under the cap AND short of the record cap.+ assert_eq!(+ exact_scan_bytes(Family::Jsonl, false, 1 << 10, 10, 500),+ Some(1 << 10)+ );+ // Hit the record cap → the tail of the file was never read.+ assert_eq!(+ exact_scan_bytes(Family::Jsonl, false, 1 << 10, 500, 500),+ None+ );+ // Over the sampling byte cap → truncated read.+ assert_eq!(exact_scan_bytes(Family::Csv, false, 8 << 20, 3, 500), None);+ // XML has no byte cap, only the record cap.+ assert_eq!(+ exact_scan_bytes(Family::Xml, false, 8 << 20, 3, 500),+ Some(8 << 20)+ );+ // SQL dumps are grouped: the sink never stops them, only the byte cap.+ assert_eq!(+ exact_scan_bytes(Family::SqlDump, false, 1 << 20, 9_999, 500),+ Some(1 << 20)+ );+ assert_eq!(+ exact_scan_bytes(Family::SqlDump, false, 128 << 20, 1, 500),+ None+ );+ // Never measurable.+ assert_eq!(exact_scan_bytes(Family::Sqlite, false, 100, 1, 500), None);+ assert_eq!(exact_scan_bytes(Family::Binary, false, 100, 1, 500), None);+ // Compressed: `size` is not the number of bytes the parser worked on.+ assert_eq!(exact_scan_bytes(Family::Json, true, 100, 1, 500), None);+ }++ #[test]+ fn the_meter_reports_only_families_it_actually_timed() {+ let meter = Meter::new();+ meter.record(Family::Code, 1_000, Duration::from_millis(10));+ meter.record(Family::Code, 1_000, Duration::from_millis(10));+ // Zero-byte files time a syscall, not throughput.+ meter.record(Family::Json, 0, Duration::from_millis(5));+ let rates = meter.rates();+ assert_eq!(rates.len(), 1);+ let code = rates["code"];+ assert_eq!((code.files, code.bytes), (2, 2_000));+ // 2000 bytes in 20 ms = 100_000 B/s.+ assert!((code.bytes_per_sec - 100_000.0).abs() < 1.0, "{code:?}");+ assert!(Meter::new().rates().is_empty());+ }++ #[test]+ fn human_renderings_are_stable() {+ assert_eq!(human_bytes(37), "37 B");+ assert_eq!(human_bytes(4 << 10), "4.0 KB");+ assert_eq!(human_bytes(3 << 20), "3.0 MB");+ assert_eq!(human_bytes(2 << 30), "2.0 GB");+ assert_eq!(human_secs(3.24), "3.2 s");+ assert_eq!(human_secs(282.0), "4.7 min");+ assert_eq!(human_secs(6840.0), "1.9 h");+ }+}diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex a18f5ad3e..a1a87bcbf 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -522,6 +522,12 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {// incremental non-graph behavior has its own HTTP suite.brain: None,no_graph: false,+ // The gate is switched off in these fixtures on purpose: they assert+ // indexing, resume and edge behaviour, and a timing-derived stop would+ // make them depend on how loaded the runner was. The gate's own+ // behaviour is covered in `gate_tests` and `cli::tests`.+ max_minutes: 0,+ approve: None,dry_run: false,json: false,quiet: true,@@ -2674,6 +2680,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":budget: &budget,capacity_warning: None,progress: &progress,+ meter: &crate::estimate::Meter::new(),},100,1,@@ -2758,6 +2765,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":budget: &budget,capacity_warning: None,progress: &progress,+ meter: &crate::estimate::Meter::new(),},100,1,@@ -2833,6 +2841,7 @@ fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {budget: &budget,capacity_warning: None,progress: &progress,+ meter: &crate::estimate::Meter::new(),},100,1,diff --git a/engine/crates/xerj-autoindex/src/gate.rs b/engine/crates/xerj-autoindex/src/gate.rsnew file mode 100644index 000000000..a76c79d82--- /dev/null+++ b/engine/crates/xerj-autoindex/src/gate.rs@@ -0,0 +1,693 @@+//! The 10-minute gate: hand the decision back instead of taking the machine.+//!+//! `landing/llms.txt` already tells an agent driving XERJ on someone's laptop+//! to *estimate, tell them, ask if it is big, report progress*. That was+//! advice, and advice is ignorable. This module is the binary enforcing it:+//! when phase A's measured estimate ([`crate::estimate`]) exceeds+//! `--max-minutes` (default 10) and nobody has approved the run, autoindex+//! stops before it touches the index and emits a decision request instead.+//!+//! Three properties the design turns on:+//!+//! * **A distinct exit code.** [`EXIT_NEEDS_DECISION`] is 4, never 1. Exit 1+//! is autoindex's catch-all for every real failure, so an agent that could+//! only see 1 would have to parse prose to tell "your endpoint is down" from+//! "I need you to choose". Anything that has to be distinguished+//! programmatically gets its own code.+//! * **Never block on stdin.** The prompt is offered only when stdin is a+//! terminal — i.e. only when a person is actually there to type. A run+//! started by an agent, a CI job, or a pipe emits the payload and exits;+//! waiting for an answer that cannot arrive is how an agent deadlocks, and+//! it is a failure mode nobody can see from the outside.+//! * **Options carry their measured cost, or say they were not measured.**+//! `narrower` names the heaviest directories in this corpus with real byte+//! counts and re-costs the run without them using the same measured rates.+//! `fast` does NOT claim a speed-up factor: `--no-semantic --no-graph`+//! removes server-side embedding and client-side edge detection, and this+//! run measured neither. It states the scope it changes and admits the+//! factor is unmeasured, which is the only honest thing to print.++use crate::estimate::{human_bytes, human_secs, Estimate, MeasuredRate, PlannedFile};+use crate::order;+use serde::Serialize;+use serde_json::{json, Value};+use std::collections::BTreeMap;+use std::io::IsTerminal;++/// "I need a decision before I spend your machine." Deliberately not 1 (every+/// error), not 2 (usage), not 3 (completed-with-junk).+pub const EXIT_NEEDS_DECISION: i32 = 4;++/// Default gate threshold in minutes, from the owner's own framing: "if+/// estimated more than 10min work needs to ask AI back what to do".+pub const DEFAULT_MAX_MINUTES: u64 = 10;++/// An answer to a decision request, carried by `--approve`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Approval {+ /// Index everything as planned.+ Proceed,+ /// Index everything, but with `--no-semantic --no-graph`.+ Fast,+ /// Index nothing and exit cleanly.+ Cancel,+}++impl Approval {+ pub fn as_str(self) -> &'static str {+ match self {+ Approval::Proceed => "proceed",+ Approval::Fast => "fast",+ Approval::Cancel => "cancel",+ }+ }++ /// Parse an `--approve` value.+ ///+ /// `narrower` is refused on purpose. It is a real option in the decision+ /// request, but it is not something this flag can carry out: making a run+ /// narrower means pointing autoindex at a different folder, and accepting+ /// `--approve narrower` would mean accepting an instruction and then+ /// indexing the whole tree anyway — the accepted-and-silently-ignored+ /// class this repository keeps re-finding (#204).+ pub fn parse(raw: &str) -> Result<Self, String> {+ match raw {+ "proceed" => Ok(Approval::Proceed),+ "fast" => Ok(Approval::Fast),+ "cancel" => Ok(Approval::Cancel),+ "narrower" => Err(+ "--approve narrower cannot be honoured here: 'narrower' means running autoindex \+ against a smaller folder, which this run cannot decide for you. Re-run it as \+ `xerj autoindex <subdirectory>` (the decision request lists the heaviest \+ directories and what each one costs)"+ .to_string(),+ ),+ other => Err(format!(+ "--approve {other} is not one of: proceed, fast, cancel (narrower means re-running \+ against a subdirectory — see the decision request)"+ )),+ }+ }+}++/// Is this run long enough to be worth a question?+///+/// Three ways to answer no, and each matters:+/// * `max_minutes == 0` — the documented opt-out. A caller that says "never+/// ask" is obeyed exactly.+/// * no estimate — phase A measured nothing it could price honestly, and a+/// gate cannot fire on a number that does not exist. Stopping a run on an+/// invented threshold breach would be the worst possible version of this+/// feature.+/// * under the threshold.+///+/// The comparison is against the **upper** bound: the estimate deliberately+/// leaves out server, network and embedding time, so its lower end is a floor+/// that would let long runs through unasked.+pub fn over_threshold(estimate: &Estimate, max_minutes: u64) -> bool {+ if max_minutes == 0 {+ return false;+ }+ estimate+ .gate_seconds()+ .is_some_and(|seconds| seconds > (max_minutes * 60) as f64)+}++/// Weight of one directory in the corpus — measured, never sampled.+#[derive(Debug, Clone, Serialize)]+pub struct DirectoryWeight {+ /// Root-relative directory, or `"."` for files directly under the root.+ pub path: String,+ pub files: u64,+ pub bytes: u64,+ /// Share of planned bytes, 0.0–1.0.+ pub share: f64,+ /// Why this path looks like it can be dropped, when it does.+ pub looks_generated: Option<String>,+}++/// Aggregate planned bytes by first path segment, heaviest first.+pub fn heaviest_directories(files: &[(String, u64)], top_n: usize) -> Vec<DirectoryWeight> {+ let total: u64 = files.iter().map(|(_, bytes)| bytes).sum();+ let mut by_dir: BTreeMap<&str, (u64, u64)> = BTreeMap::new();+ for (rel, bytes) in files {+ let segment = rel.split_once('/').map(|(head, _)| head).unwrap_or(".");+ let entry = by_dir.entry(segment).or_default();+ entry.0 += 1;+ entry.1 += bytes;+ }+ let mut weights: Vec<DirectoryWeight> = by_dir+ .into_iter()+ .map(|(path, (files, bytes))| DirectoryWeight {+ path: path.to_string(),+ files,+ bytes,+ share: if total > 0 {+ bytes as f64 / total as f64+ } else {+ 0.0+ },+ looks_generated: order::vendored_reason(&format!("{path}/x"))+ .map(|hit| format!("matches the vendored/generated rule '{hit}'")),+ })+ .collect();+ weights.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.path.cmp(&b.path)));+ weights.truncate(top_n);+ weights+}++/// Everything the caller has to know to answer, assembled once.+pub struct DecisionRequest<'a> {+ pub root: String,+ pub estimate: &'a Estimate,+ pub max_minutes: u64,+ pub bands: Vec<order::BandSummary>,+ pub heaviest: Vec<DirectoryWeight>,+ /// Estimate with every heaviest-directory entry that looks generated+ /// removed — costed with the same measured rates.+ pub without_generated: Option<(Vec<String>, String)>,+ /// Datasets phase A inferred a `semantic_text` field for. `fast` removes+ /// the server-side embedding work for exactly these.+ pub semantic_datasets: Vec<String>,+ pub total_datasets: usize,+ /// Files relationship detection would run over under the current flags.+ pub graph_files: u64,+}++impl DecisionRequest<'_> {+ /// The machine-readable payload. One JSON document on stdout, so an agent+ /// never has to scrape prose.+ pub fn to_json(&self) -> Value {+ json!({+ "xerj": "autoindex-decision-request",+ "exit_code": EXIT_NEEDS_DECISION,+ "root": self.root,+ "reason": self.reason(),+ "estimate": self.estimate,+ "estimate_text": self.estimate.headline(),+ "max_minutes": self.max_minutes,+ "priority_order": self.bands,+ "heaviest_directories": self.heaviest,+ "options": self.options(),+ "how_to_answer":+ "re-invoke the identical command with --approve <id> (--yes is an alias for \+ --approve proceed). Without an answer nothing has been indexed and nothing has \+ been changed on the server.",+ })+ }++ /// Why the run stopped, in one sentence, for both renderings.+ pub fn reason(&self) -> String {+ match self.estimate.gate_seconds() {+ Some(seconds) => format!(+ "the measured extraction floor alone is {}; its upper end {} already exceeds \+ --max-minutes {}. The real run is longer than this — server, network and \+ embedding time are not in the number",+ self.estimate.range_text(),+ human_secs(seconds),+ self.max_minutes+ ),+ None => "no estimate was possible".to_string(),+ }+ }++ fn options(&self) -> Value {+ let narrower = match &self.without_generated {+ Some((names, text)) => format!(+ "drop {} ({}) and the same measured rates put the run at {text}",+ names.join(", "),+ human_bytes(+ self.heaviest+ .iter()+ .filter(|d| d.looks_generated.is_some())+ .map(|d| d.bytes)+ .sum::<u64>()+ ),+ ),+ None => "no single directory dominates this corpus".to_string(),+ };+ json!([+ {+ "id": "proceed",+ "invoke": "--approve proceed (or --yes)",+ "effect": "index everything as planned",+ "cost": self.estimate.headline(),+ },+ {+ "id": "fast",+ "invoke": "--approve fast",+ "effect": "adds --no-semantic --no-graph: no semantic_text body fields, no \+ relationship edges. You still get typed BM25 + keyword indices over \+ the same files.",+ "cost": format!(+ "speed-up NOT measured by this run. It removes server-side embedding for {} \+ of {} inferred dataset(s) ({}) and relationship detection over {} file(s). \+ XERJ's default embedder is lexical feature-hashing, so unless the node runs \+ --embed-mode neural the embedding saving is smaller than the word 'semantic' \+ suggests.",+ self.semantic_datasets.len(),+ self.total_datasets,+ if self.semantic_datasets.is_empty() {+ "none".to_string()+ } else {+ self.semantic_datasets.join(", ")+ },+ self.graph_files,+ ),+ },+ {+ "id": "narrower",+ "invoke": "re-run as `xerj autoindex <subdirectory>` — --approve cannot carry \+ this out, autoindex has no --exclude flag",+ "effect": "index only the part that matters",+ "cost": narrower,+ "heaviest_directories": self.heaviest,+ },+ {+ "id": "cancel",+ "invoke": "--approve cancel",+ "effect": "index nothing, exit 0",+ "cost": "none — nothing has been written yet",+ },+ ])+ }++ /// The same information as prose, for a person reading a terminal.+ pub fn prose(&self) -> Vec<String> {+ let mut lines = vec![+ format!("autoindex: STOPPING BEFORE INDEXING — {}", self.reason()),+ format!(" root: {}", self.root),+ format!(+ " corpus: {} files, {}",+ self.estimate.planned_files,+ human_bytes(self.estimate.planned_bytes)+ ),+ format!(" estimate: {}", self.estimate.headline()),+ format!(" basis: {}", self.estimate.basis),+ ];+ for family in &self.estimate.families {+ lines.push(format!(+ " {:<10} {:>6} files {:>10} at {}/s measured over {} file(s)",+ family.family,+ family.planned_files,+ human_bytes(family.planned_bytes),+ human_bytes(family.bytes_per_sec as u64),+ family.measured_files,+ ));+ }+ for family in &self.estimate.unmeasured_families {+ lines.push(format!(+ " {:<10} {:>6} files {:>10} NOT in the estimate — {}",+ family.family,+ family.planned_files,+ human_bytes(family.planned_bytes),+ family.reason,+ ));+ }+ lines.push(" not included in the estimate:".to_string());+ for exclude in &self.estimate.excludes {+ lines.push(format!(" - {exclude}"));+ }+ if !self.heaviest.is_empty() {+ lines.push(" heaviest directories:".to_string());+ for dir in &self.heaviest {+ lines.push(format!(+ " {:<24} {:>6} files {:>10} ({:.0}%){}",+ dir.path,+ dir.files,+ human_bytes(dir.bytes),+ dir.share * 100.0,+ match &dir.looks_generated {+ Some(reason) => format!(" ← {reason}"),+ None => String::new(),+ }+ ));+ }+ }+ lines.push(" options:".to_string());+ let options = self.options();+ if let Some(options) = options.as_array() {+ for option in options {+ lines.push(format!(+ " {:<9} {}",+ option["id"].as_str().unwrap_or_default(),+ option["effect"].as_str().unwrap_or_default()+ ));+ lines.push(format!(+ " cost: {}",+ option["cost"].as_str().unwrap_or_default()+ ));+ }+ }+ lines.push(+ " answer by re-running the same command with --approve proceed|fast|cancel (--yes = \+ proceed). Nothing has been indexed."+ .to_string(),+ );+ lines+ }+}++/// Is there a human who can answer right now?+///+/// Both halves matter: stdin is where an answer would come from, stderr is+/// where the question is printed. A run with a redirected stdin has nobody to+/// ask, and blocking on it is the deadlock this gate exists to avoid.+pub fn can_prompt() -> bool {+ std::io::stdin().is_terminal() && std::io::stderr().is_terminal()+}++/// Read one answer from a terminal. `None` means "no answer" — EOF, an+/// unreadable stdin, or three unrecognised replies — and the caller must treat+/// that as cancel rather than as consent.+pub fn read_answer(+ input: &mut impl std::io::BufRead,+ mut echo: impl FnMut(&str),+) -> Option<Approval> {+ for _ in 0..3 {+ echo(" answer [p]roceed / [f]ast / [c]ancel (narrower = re-run on a subdirectory): ");+ let mut line = String::new();+ match input.read_line(&mut line) {+ Ok(0) | Err(_) => return None,+ Ok(_) => {}+ }+ match line.trim().to_ascii_lowercase().as_str() {+ "p" | "proceed" | "y" | "yes" => return Some(Approval::Proceed),+ "f" | "fast" => return Some(Approval::Fast),+ "c" | "cancel" | "n" | "no" | "q" => return Some(Approval::Cancel),+ "" => echo(" no answer read; type p, f or c"),+ other => echo(&format!(" '{other}' is not one of p, f, c")),+ }+ }+ None+}++/// Cost the run again with the generated-looking heavy directories removed —+/// same measured rates, no new guess. `None` when nothing looks droppable.+pub fn without_generated_directories(+ estimate: &Estimate,+ rates: &BTreeMap<&'static str, MeasuredRate>,+ heaviest: &[DirectoryWeight],+ files: &[(String, String, u64)],+) -> Option<(Vec<String>, String)> {+ let dropped: Vec<String> = heaviest+ .iter()+ .filter(|dir| dir.looks_generated.is_some())+ .map(|dir| dir.path.clone())+ .collect();+ if dropped.is_empty() {+ return None;+ }+ let kept: Vec<PlannedFile> = files+ .iter()+ .filter(|(rel, _, _)| {+ let segment = rel.split_once('/').map(|(head, _)| head).unwrap_or(".");+ !dropped.iter().any(|d| d == segment)+ })+ .map(|(_, family, bytes)| PlannedFile {+ family: family.clone(),+ bytes: *bytes,+ })+ .collect();+ Some((+ dropped,+ estimate.recompute_subset(&kept, rates).range_text(),+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rates() -> BTreeMap<&'static str, MeasuredRate> {+ BTreeMap::from([(+ "code",+ MeasuredRate {+ files: 4,+ bytes: 4_000,+ bytes_per_sec: 1_000.0,+ },+ )])+ }++ fn estimate(files: usize, bytes: u64) -> Estimate {+ let planned: Vec<PlannedFile> = (0..files)+ .map(|_| PlannedFile {+ family: "code".into(),+ bytes,+ })+ .collect();+ Estimate::compute(&planned, &rates(), 4)+ }++ /// The point of the whole module: "needs a decision" must be+ /// distinguishable from "something broke" without parsing English.+ #[test]+ fn the_decision_exit_code_is_not_any_existing_one() {+ for taken in [0, 1, 2, 3] {+ assert_ne!(EXIT_NEEDS_DECISION, taken);+ }+ }++ /// The threshold rule itself, including the two ways it must decline to+ /// fire. A gate that stopped a run on a number nobody measured would be+ /// worse than no gate.+ #[test]+ fn the_threshold_fires_on_the_upper_bound_and_never_on_an_absent_one() {+ // 100 files × 1000 B at 1000 B/s over 4 workers = 25 s of work,+ // longest job 1 s → high ≈ 25.75 s.+ let quick = estimate(100, 1_000);+ assert!(quick.high_seconds.unwrap() < 60.0);+ assert!(!over_threshold(&quick, 1));++ // 100 files × 20 kB at the same rate = 20 s each, 2000 s of work over+ // 4 workers → 500 s + a 15 s tail: past one minute, under ten.+ let slow = estimate(100, 20_000);+ let high = slow.high_seconds.unwrap();+ assert!(high > 60.0 && high < 600.0, "{high}");+ assert!(over_threshold(&slow, 1));+ assert!(!over_threshold(&slow, 10));++ // The documented opt-out is obeyed exactly.+ assert!(!over_threshold(&slow, 0));++ // No measurement, no gate — under any threshold.+ let unmeasured = Estimate::compute(+ &[PlannedFile {+ family: "sqlite".into(),+ bytes: 1 << 40,+ }],+ &BTreeMap::new(),+ 4,+ );+ assert!(unmeasured.gate_seconds().is_none());+ for minutes in [1, 10, 10_080] {+ assert!(!over_threshold(&unmeasured, minutes));+ }+ }++ #[test]+ fn approve_accepts_the_three_it_can_carry_out_and_refuses_the_one_it_cannot() {+ assert_eq!(Approval::parse("proceed"), Ok(Approval::Proceed));+ assert_eq!(Approval::parse("fast"), Ok(Approval::Fast));+ assert_eq!(Approval::parse("cancel"), Ok(Approval::Cancel));+ // #204: accepting this and indexing everything anyway is the bug.+ let refused = Approval::parse("narrower").unwrap_err();+ assert!(refused.contains("cannot be honoured"), "{refused}");+ assert!(refused.contains("subdirectory"), "{refused}");+ let unknown = Approval::parse("later").unwrap_err();+ assert!(unknown.contains("proceed, fast, cancel"), "{unknown}");+ // Case and spelling are not guessed at.+ assert!(Approval::parse("Proceed").is_err());+ assert!(Approval::parse("").is_err());+ }++ #[test]+ fn the_payload_carries_the_estimate_the_counts_the_bands_and_the_options() {+ let estimate = estimate(10, 1_000);+ let request = DecisionRequest {+ root: "/data".into(),+ estimate: &estimate,+ max_minutes: 10,+ bands: order::summarize(&[order::Item {+ index: 0,+ band: order::Band::SourceAndDocs,+ bytes: 10_000,+ }]),+ heaviest: heaviest_directories(+ &[+ ("node_modules/a.js".to_string(), 9_000),+ ("src/main.rs".to_string(), 1_000),+ ],+ 5,+ ),+ without_generated: Some((vec!["node_modules".into()], "1.0 s–1.0 s".into())),+ semantic_datasets: vec!["docs".into()],+ total_datasets: 3,+ graph_files: 10,+ };+ let payload = request.to_json();+ assert_eq!(payload["xerj"], "autoindex-decision-request");+ assert_eq!(payload["exit_code"], EXIT_NEEDS_DECISION);+ assert_eq!(payload["estimate"]["planned_files"], 10);+ // An agent reading this must not be able to mistake the floor for a+ // prediction of the run — the machine-readable kind says which it is,+ // and the human-readable line repeats it in words.+ assert_eq!(+ payload["estimate"]["kind"],+ crate::estimate::ESTIMATE_KIND,+ "the payload must name what kind of number this is"+ );+ let estimate_text = payload["estimate_text"].as_str().unwrap();+ assert!(estimate_text.starts_with("at least "), "{estimate_text}");+ assert!(estimate_text.contains("MEASURED FLOOR"), "{estimate_text}");+ assert!(+ payload["reason"]+ .as_str()+ .unwrap()+ .contains("The real run is longer than this"),+ "{}",+ payload["reason"]+ );+ assert_eq!(payload["estimate"]["planned_bytes"], 10_000);+ assert_eq!(payload["priority_order"][0]["band"], "source-and-docs");+ assert!(payload["priority_order"][0]["why"]+ .as_str()+ .unwrap()+ .contains("searches for first"));++ let options = payload["options"].as_array().unwrap();+ let ids: Vec<&str> = options.iter().map(|o| o["id"].as_str().unwrap()).collect();+ assert_eq!(ids, ["proceed", "fast", "narrower", "cancel"]);+ // The honest-claims rule, asserted: `fast` states its scope and admits+ // the factor is not measured, instead of printing an invented "3×".+ let fast = options[1]["cost"].as_str().unwrap();+ assert!(fast.contains("NOT measured"), "{fast}");+ assert!(fast.contains("1 of 3 inferred dataset(s)"), "{fast}");+ assert!(fast.contains("lexical feature-hashing"), "{fast}");+ // `narrower` names the directory and re-costs it with measured rates.+ let narrower = options[2]["cost"].as_str().unwrap();+ assert!(narrower.contains("node_modules"), "{narrower}");+ // …and it never claims --approve can do it.+ assert!(options[2]["invoke"]+ .as_str()+ .unwrap()+ .contains("subdirectory"));++ // The prose carries the same facts for a human.+ let prose = request.prose().join("\n");+ assert!(prose.contains("STOPPING BEFORE INDEXING"));+ assert!(prose.contains("node_modules"));+ assert!(prose.contains("Nothing has been indexed."));+ assert!(prose.contains("not included in the estimate:"));+ }++ #[test]+ fn the_heaviest_directories_are_measured_and_flagged() {+ let dirs = heaviest_directories(+ &[+ ("node_modules/a/b.js".to_string(), 700),+ ("node_modules/c.js".to_string(), 100),+ ("src/main.rs".to_string(), 150),+ ("README.md".to_string(), 50),+ ],+ 5,+ );+ assert_eq!(dirs[0].path, "node_modules");+ assert_eq!((dirs[0].files, dirs[0].bytes), (2, 800));+ assert!((dirs[0].share - 0.8).abs() < 1e-9);+ assert!(dirs[0].looks_generated.is_some());+ assert_eq!(dirs[1].path, "src");+ assert!(dirs[1].looks_generated.is_none());+ // Root-level files are their own bucket, not silently merged.+ assert_eq!(dirs[2].path, ".");+ assert_eq!(dirs[2].bytes, 50);+ assert!(heaviest_directories(&[], 5).is_empty());+ }++ #[test]+ fn dropping_the_generated_directories_is_recosted_not_guessed() {+ let files = vec![+ (+ "node_modules/a.js".to_string(),+ "code".to_string(),+ 9_000u64,+ ),+ ("src/main.rs".to_string(), "code".to_string(), 1_000),+ ];+ let planned: Vec<PlannedFile> = files+ .iter()+ .map(|(_, family, bytes)| PlannedFile {+ family: family.clone(),+ bytes: *bytes,+ })+ .collect();+ let estimate = Estimate::compute(&planned, &rates(), 1);+ let heaviest = heaviest_directories(+ &files+ .iter()+ .map(|(rel, _, bytes)| (rel.clone(), *bytes))+ .collect::<Vec<_>>(),+ 5,+ );+ let (dropped, text) =+ without_generated_directories(&estimate, &rates(), &heaviest, &files).unwrap();+ assert_eq!(dropped, ["node_modules"]);+ // 1000 bytes at the measured 1000 B/s on one worker = 1.0 s.+ assert!(text.starts_with("1.0 s–1.0 s"), "{text}");+ // Nothing droppable → no invented saving.+ let clean = vec![("src/main.rs".to_string(), "code".to_string(), 1_000u64)];+ let clean_dirs = heaviest_directories(&[("src/main.rs".to_string(), 1_000)], 5);+ assert!(without_generated_directories(&estimate, &rates(), &clean_dirs, &clean).is_none());+ }++ /// A non-answer is a cancel. Treating EOF as consent would turn every+ /// piped run into an unattended full index — the exact outcome the gate+ /// exists to prevent.+ #[test]+ fn an_unanswerable_prompt_never_returns_consent() {+ let mut echoed = Vec::new();+ let answer = read_answer(&mut std::io::Cursor::new(b""), |line| {+ echoed.push(line.to_string())+ });+ assert_eq!(answer, None);+ assert_eq!(+ echoed.len(),+ 1,+ "EOF must not re-prompt forever: {echoed:?}"+ );++ // Three unrecognised answers and it gives up rather than looping.+ let mut count = 0;+ let answer = read_answer(&mut std::io::Cursor::new(b"x\ny\n\nz\nq\n"), |_| count += 1);+ // 'y' is an accepted spelling of proceed, so this stops at line 2.+ assert_eq!(answer, Some(Approval::Proceed));+ assert!(count >= 2);++ let mut noise = 0;+ assert_eq!(+ read_answer(&mut std::io::Cursor::new(b"a\nb\nc0\nd\n"), |_| noise += 1),+ None+ );+ }++ #[test]+ fn every_spelling_of_an_answer_maps_to_one_decision() {+ for (input, expected) in [+ ("p\n", Approval::Proceed),+ ("PROCEED\n", Approval::Proceed),+ (" yes \n", Approval::Proceed),+ ("f\n", Approval::Fast),+ ("Fast\n", Approval::Fast),+ ("c\n", Approval::Cancel),+ ("no\n", Approval::Cancel),+ ("q\n", Approval::Cancel),+ ] {+ assert_eq!(+ read_answer(&mut std::io::Cursor::new(input.as_bytes()), |_| {}),+ Some(expected),+ "{input:?}"+ );+ }+ }+}diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 6db75e62a..ee06803b6 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -405,6 +405,10 @@ fn cfg(root: &Path, state_dir: &Path, url: &str, semantic: bool) -> IndexCfg {no_semantic: !semantic,brain: None,no_graph: true,+ // Gate off: these fixtures assert reconcile behaviour, not a+ // timing-derived stop. See `gate_tests` and `cli::tests`.+ max_minutes: 0,+ approve: None,dry_run: false,json: false,quiet: true,diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex 205487df3..9c8905b4b 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -11,12 +11,15 @@ pub mod correlate;pub mod dataset;pub mod detect;pub mod esclient;+pub mod estimate;pub mod extract;+pub mod gate;mod generation_catalog;#[cfg(test)]mod generation_catalog_http_tests;pub mod ids;pub mod infer;+pub mod order;pub mod pool;pub mod progress;mod reconcile_plan;@@ -171,6 +174,7 @@ fn project_reconcile_plan(cfg: &IndexCfg,state_dir: &Path,pr: &Progress,+ meter: &estimate::Meter,) -> Result<Plan> {let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);let ctx = PhaseAContext {@@ -178,6 +182,7 @@ fn project_reconcile_plan(budget: &budget,capacity_warning: None,progress: pr,+ meter,};pr.phase("scan",@@ -663,6 +668,10 @@ struct PhaseAContext<'a> {budget: &'a std::sync::Arc<extract::pdf::ExtractionSpoolBudget>,capacity_warning: Option<&'a str>,progress: &'a Progress,+ /// Throughput evidence for the pre-index estimate. Phase A already parses+ /// every file; timing that parse is the only way to price the run on the+ /// machine it will actually run on rather than on ours.+ meter: &'a estimate::Meter,}fn scan_file(@@ -750,15 +759,23 @@ fn scan_file((entry.1 as usize) < sample}};+ // Timed span: the extraction itself, nothing around it. The PDF spool's+ // post-parse `content::verify` re-read is deliberately outside it — phase+ // B never repeats that read, so charging it here would price a cost the+ // estimate is trying to predict away.+ let extraction_started = Instant::now();+ let extraction_elapsed;let extraction = if sn.family == Family::Pdf {- match extract::pdf::extract_and_spool(+ let parsed = extract::pdf::extract_and_spool(path,state_dir,size,digest,pdf_spool_budget,&mut sink,- ) {+ );+ extraction_elapsed = extraction_started.elapsed();+ match parsed {Ok((stats, spool, fallback)) => {// The inventory digest was computed before Phase A. Only hand// bytes to Phase B when the source still matches that exact@@ -794,7 +811,9 @@ fn scan_file(Err(error) => Err(error),}} else {- extract::extract(path, &sn, limit, &mut sink)+ let parsed = extract::extract(path, &sn, limit, &mut sink);+ extraction_elapsed = extraction_started.elapsed();+ parsed};match extraction {Ok(stats) => {@@ -815,6 +834,21 @@ fn scan_file(}}}+ // Throughput evidence, but only where the read was provably complete: the+ // sampler stops at whichever of the byte cap or the record cap comes+ // first, and timing a partial read against the full file size would invent+ // a rate this machine never demonstrated. `exact_scan_bytes` owns that+ // judgement; a junked file is never timed at all, because phase B will+ // not process it.+ if out.junk.is_none() {+ let sampled = groups.values().map(|(_, records, _)| *records).max();+ if let Some(bytes) = sampled.and_then(|records| {+ estimate::exact_scan_bytes(sn.family, sn.gzip, size, records, sample)+ }) {+ ctx.meter.record(sn.family, bytes, extraction_elapsed);+ }+ }+out.sketches = groups.into_iter().map(|(group, (fields, records, key_fields))| GroupSketch {@@ -841,11 +875,13 @@ mod clustering_key_tests {// reuse: a zero budget keeps these cases on the plain parse path.let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);let progress = Progress::silent();+ let meter = estimate::Meter::new();let ctx = PhaseAContext {state_dir: dir,budget: &budget,capacity_warning: None,progress: &progress,+ meter: &meter,};scan_file(&path, size, "d0", &ctx, 500, 2)}@@ -948,6 +984,12 @@ mod phase_a_grouping_tests {no_semantic: false,brain: None,no_graph: true,+ // The gate is switched off in these fixtures on purpose: they assert+ // indexing, resume and edge behaviour, and a timing-derived stop would+ // make them depend on how loaded the runner was. The gate's own+ // behaviour is covered in `gate_tests` and `cli::tests`.+ max_minutes: 0,+ approve: None,dry_run: true,json: false,quiet: true,@@ -967,11 +1009,13 @@ mod phase_a_grouping_tests {// file on the plain parse path so no artifact is ever retained.let budget = extract::pdf::ExtractionSpoolBudget::new(0, 0);let progress = Progress::silent();+ let meter = estimate::Meter::new();let ctx = PhaseAContext {state_dir: root,budget: &budget,capacity_warning: None,progress: &progress,+ meter: &meter,};build_phase_a(root,@@ -1415,6 +1459,31 @@ fn build_mapping(specs: &[infer::FieldSpec]) -> Value {// ─── the main run ────────────────────────────────────────────────────────+/// Files phase B still has work for: planned, with a real content key, and+/// either never finished or finished against different bytes.+///+/// This predicate is evaluated twice per run — once to price the work for the+/// pre-index estimate, once to build the real queue — against two different+/// snapshots of `journal.done`. The two agree by construction: between the two+/// calls the only thing that removes a key from `done` is `file_replace_start`,+/// which is driven from `content_changed`, and for a key in `content_changed`+/// this predicate ignores `done` altogether. Keeping it in one function is what+/// makes "the estimate priced what the run then did" true rather than hoped.+fn pending_for_phase_b(+ keys: &[String],+ plan: &Plan,+ done: &std::collections::HashSet<String>,+ content_changed: &std::collections::HashSet<String>,+) -> Vec<usize> {+ (0..keys.len())+ .filter(|&i| {+ !keys[i].is_empty()+ && plan.files.contains_key(&keys[i])+ && !(done.contains(&keys[i]) && !content_changed.contains(&keys[i]))+ })+ .collect()+}+fn select_resume_plan_keys(files: &[walk::FileEntry],content_keys: &[String],@@ -2119,6 +2188,10 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.unwrap_or_else(|| progress::default_interval(surface)),);let ticker = pr.spawn_ticker();+ // One throughput meter for the whole run: both phase-A routes (the legacy+ // scan and the generated route's `project_reconcile_plan`) feed it, so the+ // estimate is built from whatever this invocation actually parsed.+ let scan_meter = estimate::Meter::new();// What this run decided to take from the machine, before it takes it.pr.note(&format!("autoindex: {} scan threads, {} index workers, {} pdf workers, --bulk-mb {} [{}]",@@ -2296,7 +2369,8 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.committed_manifest.as_ref().context("branch guard proved a committed manifest")?;- let plan = project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr)?;+ let plan =+ project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr, &scan_meter)?;let unchanged = serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)?;println!("{}", serde_json::to_string_pretty(&plan)?);// stdout is the RESULT, stderr is PROGRESS: the projection above is@@ -2338,7 +2412,24 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.as_ref().context("generated journal lost its committed manifest")?.clone();- let plan = project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr)?;+ let plan =+ project_reconcile_plan(&inventory, &base.plan, &cfg, &state_dir, &pr, &scan_meter)?;+ // Say out loud that the decision gate is not on this route. It is an+ // incremental reconcile of an already-committed generation, so the work+ // is the *changed* set and is published from a sealed snapshot rather+ // than through the phase-B queue the estimate prices. Accepting+ // `--max-minutes` here and quietly not applying it would be the+ // accepted-and-ignored class from #204 — so the run states the+ // exemption instead of leaving the caller to discover it.+ if cfg.max_minutes > 0 && cfg.approve.is_none() {+ pr.note(&format!(+ "gate: --max-minutes {} does not apply to an incremental reconcile of committed \+ generation {} — only files that changed are processed, and they are published \+ from a sealed snapshot rather than through the queue the estimate prices. Use \+ --dry-run to see the projected plan before committing to it",+ cfg.max_minutes, base.generation+ ));+ }if serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)? {if let Some(expected) = &base.execution {let (schema_identity, index_identity) = generation_contract_identities(&plan)?;@@ -2675,6 +2766,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {budget: &pdf_spool_budget,capacity_warning: pdf_spool_capacity_warning.as_deref(),progress: &pr,+ meter: &scan_meter,};let mut plan: Plan = if let Some(p) = journal.plan.clone().filter(|_| !genesis_recovery) {p@@ -2757,6 +2849,196 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.map(|junk| junk.file_key.clone()).collect();+ // ── estimate → work order → decision gate ────────────────────────────+ //+ // Everything below happens BEFORE the first remote mutation: no index has+ // been created, no mapping upgraded, no plan persisted, no document+ // written. That placement is the whole point — a run that stops here has+ // cost the user a read of their folder and nothing else.+ let pending = pending_for_phase_b(&keys, &plan, &journal.done_keys(), &content_changed);+ let scan_rates = scan_meter.rates();+ let planned_for_estimate: Vec<estimate::PlannedFile> = pending+ .iter()+ .map(|&i| estimate::PlannedFile {+ family: plan.files[&keys[i]].family.clone(),+ bytes: files[i].size,+ })+ .collect();+ let run_estimate = estimate::Estimate::compute(&planned_for_estimate, &scan_rates, cfg.workers);+ let work_items: Vec<order::Item> = pending+ .iter()+ .map(|&i| order::Item {+ index: i,+ band: order::band_from_family_str(&files[i].rel, &plan.files[&keys[i]].family),+ bytes: files[i].size,+ })+ .collect();+ let bands = order::summarize(&work_items);+ let rel_bytes: Vec<(String, u64)> = pending+ .iter()+ .map(|&i| (files[i].rel.clone(), files[i].size))+ .collect();+ let rel_family_bytes: Vec<(String, String, u64)> = pending+ .iter()+ .map(|&i| {+ (+ files[i].rel.clone(),+ plan.files[&keys[i]].family.clone(),+ files[i].size,+ )+ })+ .collect();+ let heaviest = gate::heaviest_directories(&rel_bytes, 5);++ pr.note(&format!("estimate: {}", run_estimate.headline()));+ pr.note(&format!("estimate: basis — {}", run_estimate.basis));+ for family in &run_estimate.families {+ pr.note(&format!(+ " estimate: {:<10} {:>5} files {:>9} at {}/s measured over {} file(s) / {} → {}",+ family.family,+ family.planned_files,+ estimate::human_bytes(family.planned_bytes),+ estimate::human_bytes(family.bytes_per_sec as u64),+ family.measured_files,+ estimate::human_bytes(family.measured_bytes),+ estimate::human_secs(family.seconds_of_work),+ ));+ }+ for family in &run_estimate.unmeasured_families {+ pr.note(&format!(+ " estimate: {:<10} {:>5} files {:>9} NOT priced — {}",+ family.family,+ family.planned_files,+ estimate::human_bytes(family.planned_bytes),+ family.reason,+ ));+ }+ for exclude in &run_estimate.excludes {+ pr.note(&format!(" estimate excludes: {exclude}"));+ }+ pr.note(&format!(+ "work order: {} — {} inside each band at {} worker(s); a file that outlasts everything \+ above it starts first regardless of band",+ bands+ .iter()+ .map(|band| format!(+ "{} ({} files, {})",+ band.band,+ band.files,+ estimate::human_bytes(band.bytes)+ ))+ .collect::<Vec<_>>()+ .join(" → "),+ if cfg.workers == 1 {+ "smallest first"+ } else {+ "biggest first"+ },+ cfg.workers,+ ));+ for band in &bands {+ pr.note(&format!(" {:<16} {}", band.band, band.why));+ }++ if gate::over_threshold(&run_estimate, cfg.max_minutes) {+ let semantic_datasets: Vec<String> = plan+ .datasets+ .iter()+ .filter(|dataset| dataset.semantic_field.is_some())+ .map(|dataset| dataset.slug.clone())+ .collect();+ let request = gate::DecisionRequest {+ root: root_str.clone(),+ estimate: &run_estimate,+ max_minutes: cfg.max_minutes,+ bands: bands.clone(),+ heaviest: heaviest.clone(),+ without_generated: gate::without_generated_directories(+ &run_estimate,+ &scan_rates,+ &heaviest,+ &rel_family_bytes,+ ),+ semantic_datasets,+ total_datasets: plan.datasets.len(),+ graph_files: if cfg.no_graph {+ 0+ } else {+ pending.len() as u64+ },+ };+ match cfg.approve {+ Some(answer) => pr.note(&format!(+ "gate: {} — answered with --approve {}",+ request.reason(),+ answer.as_str()+ )),+ None if cfg.dry_run => pr.note(&format!(+ "gate: a real run would STOP here and exit {} — {}",+ gate::EXIT_NEEDS_DECISION,+ request.reason()+ )),+ None => {+ for line in request.prose() {+ pr.note(&line);+ }+ // Ask only where an answer can arrive. A pipe, a CI job or an+ // agent has no one at the keyboard, and blocking on stdin+ // there is an invisible deadlock — the failure this gate was+ // added to prevent, not to introduce.+ let answer = if gate::can_prompt() {+ let stdin = std::io::stdin();+ gate::read_answer(&mut stdin.lock(), |line| pr.note(line))+ } else {+ None+ };+ match answer {+ Some(gate::Approval::Proceed) => pr.note("gate: proceeding"),+ Some(gate::Approval::Fast) => {+ // Not honourable mid-run: --no-semantic decides the+ // mappings this plan was inferred with. Saying so beats+ // silently indexing semantically anyway (#204).+ pr.note(+ "gate: 'fast' changes the inferred mappings, so it cannot be applied \+ to a plan that is already frozen. Nothing was indexed — re-run the \+ same command with --approve fast",+ );+ println!("{}", request.to_json());+ pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);+ return Ok((gate::EXIT_NEEDS_DECISION, None));+ }+ Some(gate::Approval::Cancel) => {+ pr.note("gate: cancelled — nothing was indexed");+ pr.finish(true, 0, "cancelled", &[]);+ return Ok((0, None));+ }+ None => {+ println!("{}", request.to_json());+ pr.finish(false, gate::EXIT_NEEDS_DECISION, "needs-decision", &[]);+ return Ok((gate::EXIT_NEEDS_DECISION, None));+ }+ }+ }+ }+ } else if cfg.max_minutes > 0 && run_estimate.gate_seconds().is_some() {+ // Say what the silence means. "Under the threshold" is a statement+ // about the floor, not a promise about the run, and an agent relaying+ // it to a person needs the difference.+ pr.note(&format!(+ "gate: not triggered — the measured extraction floor {} is under --max-minutes {}. \+ That is NOT a promise the run finishes in {} minutes: server, network and embedding \+ time are not measured before indexing starts",+ run_estimate.range_text(),+ cfg.max_minutes,+ cfg.max_minutes+ ));+ }+ if cfg.approve == Some(gate::Approval::Cancel) {+ pr.note("gate: --approve cancel — nothing was indexed");+ pr.finish(true, 0, "cancelled", &[]);+ return Ok((0, None));+ }+if cfg.dry_run {println!("{}", serde_json::to_string_pretty(&plan)?);pr.note("(dry run — nothing indexed)");@@ -2902,14 +3184,14 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.map(|j| j.file_key.as_str()).collect();let mut new_unplanned: Vec<JunkFile> = Vec::new();- let mut todo: Vec<usize> = Vec::new();+ // The same predicate the estimate above priced — see `pending_for_phase_b`+ // for why the two snapshots of `journal.done` cannot disagree.+ let mut todo: Vec<usize> = pending_for_phase_b(&keys, &plan, &done0, &content_changed);for i in 0..files.len() {if keys[i].is_empty() || done0.contains(&keys[i]) && !content_changed.contains(&keys[i]) {continue;}- if plan.files.contains_key(&keys[i]) {- todo.push(i);- } else if !planned_junk.contains(keys[i].as_str()) {+ if !plan.files.contains_key(&keys[i]) && !planned_junk.contains(keys[i].as_str()) {// file appeared after the plan was frozen — recorded, not fatalnew_unplanned.push(JunkFile {file_key: keys[i].clone(),@@ -3134,9 +3416,28 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {})};- // ascending by size — workers pop() from the tail, so the BIGGEST files- // start first and can't serialize the end of the run.- todo.sort_by_key(|&i| files[i].size);+ // Value first, then biggest-first inside each band — `crate::order` owns+ // the rule and the reasoning, and the bands were already printed with the+ // estimate above so the order is explained rather than asserted. The queue+ // is drained with `pop()`, so this is the start order reversed.+ //+ // This replaces a plain ascending sort by size. That rule was right about+ // scheduling (a huge file must not be left to serialise the tail) and+ // silent about value: a user who stopped early got whatever was largest,+ // which on a source tree is `node_modules`. `order` keeps the scheduling+ // property inside each band and adds a critical-path exception so a file+ // that genuinely dominates the run still starts first.+ todo = {+ let items: Vec<order::Item> = todo+ .iter()+ .map(|&i| order::Item {+ index: i,+ band: order::band_from_family_str(&files[i].rel, &plan.files[&keys[i]].family),+ bytes: files[i].size,+ })+ .collect();+ order::start_order_as_pop_queue(&items, cfg.workers)+ };let n_todo = todo.len();// Percent and ETA are bytes-based, never file-count-based. The queue is// biggest-first, so a files-done percent races to ~100% and then sitsdiff --git a/engine/crates/xerj-autoindex/src/order.rs b/engine/crates/xerj-autoindex/src/order.rsnew file mode 100644index 000000000..4f6d77b34--- /dev/null+++ b/engine/crates/xerj-autoindex/src/order.rs@@ -0,0 +1,456 @@+//! In what order phase B drains the corpus — and why that order is what it is.+//!+//! Before this module the queue was sorted by size alone (biggest first, so+//! one enormous file could not serialise the tail of the run). That is a good+//! *scheduling* rule and a useless *value* rule: a user who stops a long run+//! early, or searches while it is still going, got whatever happened to be+//! largest — very often `node_modules`.+//!+//! So the queue is now ordered on two axes, in this priority:+//!+//! 1. **Value band** ([`Band`]) — source and prose first, then configuration,+//! then structured data, then bulk line/log files, and vendored, generated+//! and minified paths last. The band is decided from the sniffed family and+//! the path, never the extension alone.+//! 2. **Biggest first inside a band** — the original rule, kept, because with+//! `W` workers the largest file in a band runs *concurrently* with the rest+//! of that band rather than ahead of it. Starting it last is what makes a+//! run end with `W-1` idle workers. With `W == 1` there is no tail to hide,+//! so a single-worker run is ordered smallest-first inside each band, which+//! is what "searchable earliest" means when nothing is concurrent.+//!+//! One exception keeps axis 1 from costing wall clock it cannot buy back:+//! a file large enough that its own extraction outlasts everything ranked+//! above it — `size × workers > (all other planned bytes)` — is on the+//! critical path of the whole run and starts first regardless of band. At most+//! `workers` files can satisfy that, so the exception cannot swallow the+//! ordering.+//!+//! Prior art for the "sort by size descending, then bucket into levels"+//! shape: tantivy's `LogMergePolicy::compute_merge_candidates`+//! (`tantivy/src/indexer/log_merge_policy.rs:94-99`, MIT) sorts segments+//! `Reverse(max_doc)` and then chunks them into log-size levels. Adapted, not+//! copied: our levels are *value* bands, and size only orders within one.+//! The critical-path exception is the standard list-scheduling observation+//! (Graham, 1969) that makespan is bounded below by the longest single job.++use crate::sniff::Family;++/// Value bands, most valuable first. The discriminant IS the rank.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub enum Band {+ /// Source code and human-authored documents: what a person actually asks+ /// questions about.+ SourceAndDocs = 0,+ /// Configuration and small structured trees — dense, high signal per byte.+ Config = 1,+ /// Structured data: rows, records, tables.+ Data = 2,+ /// Line-oriented bulk: logs and plain line files. Voluminous, low signal+ /// per byte, and rarely the reason someone indexed the folder.+ Bulk = 3,+ /// Vendored, generated or minified paths, whatever their family.+ Vendored = 4,+}++impl Band {+ /// Every band, in drain order.+ pub const ALL: [Band; 5] = [+ Band::SourceAndDocs,+ Band::Config,+ Band::Data,+ Band::Bulk,+ Band::Vendored,+ ];++ pub fn as_str(self) -> &'static str {+ match self {+ Band::SourceAndDocs => "source-and-docs",+ Band::Config => "config",+ Band::Data => "data",+ Band::Bulk => "bulk",+ Band::Vendored => "vendored",+ }+ }++ /// The reason this band sits where it sits — printed with the plan so the+ /// order is never just an assertion.+ pub fn why(self) -> &'static str {+ match self {+ Band::SourceAndDocs => "source code and documents — what a person searches for first",+ Band::Config => {+ "configuration and small structured trees — dense, high signal per byte"+ }+ Band::Data => "structured data: rows, records and tables",+ Band::Bulk => "logs and plain line files — voluminous, low signal per byte",+ Band::Vendored => {+ "vendored, generated or minified paths — indexed last so stopping early costs \+ nothing you care about"+ }+ }+ }+}++/// Directory names that mean "not written here": dependency trees, build+/// output, VCS internals, caches.+///+/// A false positive costs a file its place near the front of the queue and+/// nothing else — it is still indexed, still searchable, still complete. That+/// asymmetry is why the list can afford to include ambiguous names like+/// `build` and `out`.+const VENDORED_DIRS: &[&str] = &[+ ".cache",+ ".cargo",+ ".git",+ ".gradle",+ ".hg",+ ".mypy_cache",+ ".next",+ ".nuxt",+ ".pytest_cache",+ ".svelte-kit",+ ".svn",+ ".terraform",+ ".tox",+ ".venv",+ "Pods",+ "__pycache__",+ "bower_components",+ "build",+ "coverage",+ "dist",+ "node_modules",+ "obj",+ "out",+ "site-packages",+ "target",+ "third_party",+ "thirdparty",+ "vendor",+ "venv",+];++/// Whole-file names that are machine-written by construction.+const GENERATED_FILES: &[&str] = &[+ "Cargo.lock",+ "Gemfile.lock",+ "composer.lock",+ "go.sum",+ "package-lock.json",+ "pnpm-lock.yaml",+ "poetry.lock",+ "yarn.lock",+];++/// Suffixes that mean minified or generated content.+const GENERATED_SUFFIXES: &[&str] = &[+ ".min.js",+ ".min.css",+ ".min.mjs",+ ".map",+ ".pb.go",+ "_pb2.py",+ "_pb2_grpc.py",+ ".g.dart",+ ".generated.ts",+ ".generated.go",+];++/// Does this root-relative path (forward slashes) live in vendored, generated+/// or minified territory? Returns the segment or suffix that decided it, so+/// the plan can name the rule rather than assert the verdict.+pub fn vendored_reason(rel: &str) -> Option<&'static str> {+ for segment in rel.split('/') {+ if let Some(hit) = VENDORED_DIRS.iter().find(|d| **d == segment) {+ return Some(hit);+ }+ }+ let name = rel.rsplit('/').next().unwrap_or(rel);+ if let Some(hit) = GENERATED_FILES.iter().find(|f| **f == name) {+ return Some(hit);+ }+ GENERATED_SUFFIXES+ .iter()+ .find(|s| name.len() > s.len() && name.ends_with(**s))+ .copied()+}++/// Which band a planned file belongs to.+pub fn band(rel: &str, family: Family) -> Band {+ if vendored_reason(rel).is_some() {+ return Band::Vendored;+ }+ match family {+ Family::Code | Family::TxtProse | Family::Html | Family::Pdf | Family::Docx => {+ Band::SourceAndDocs+ }+ Family::Yaml | Family::Json | Family::Xml => Band::Config,+ Family::Csv | Family::Jsonl | Family::Sqlite | Family::SqlDump => Band::Data,+ Family::Logs | Family::TxtLines => Band::Bulk,+ // Binary never reaches phase B (phase A junks it); ranked last so a+ // future caller that does pass one cannot jump the queue with it.+ Family::Binary => Band::Vendored,+ }+}++/// `band` from the family *string* the durable plan stores. An unrecognised+/// family is ranked with the bulk band rather than promoted — an unknown+/// thing is not evidence of value.+pub fn band_from_family_str(rel: &str, family: &str) -> Band {+ if vendored_reason(rel).is_some() {+ return Band::Vendored;+ }+ match family {+ "code" | "txt-prose" | "html" | "pdf" | "docx" => Band::SourceAndDocs,+ "yaml" | "json" | "xml" => Band::Config,+ "csv" | "jsonl" | "sqlite" | "sqldump" => Band::Data,+ _ => Band::Bulk,+ }+}++/// One planned unit of phase-B work, as the ordering sees it.+#[derive(Debug, Clone, Copy)]+pub struct Item {+ /// Index into the caller's own file array — returned verbatim.+ pub index: usize,+ pub band: Band,+ pub bytes: u64,+}++/// The order phase B should *start* the work in, most valuable first.+///+/// Returns caller indices. The caller's queue pops from the tail, so it must+/// reverse this before use — [`start_order_as_pop_queue`] does exactly that.+pub fn start_order(items: &[Item], workers: usize) -> Vec<usize> {+ let workers = workers.max(1);+ let total: u128 = items.iter().map(|i| i.bytes as u128).sum();++ let mut ranked: Vec<&Item> = items.iter().collect();+ // Band first; then biggest-first, except on a single worker where there is+ // no concurrency for a big file to hide inside.+ ranked.sort_by(|a, b| {+ a.band.cmp(&b.band).then_with(|| {+ if workers == 1 {+ a.bytes.cmp(&b.bytes)+ } else {+ b.bytes.cmp(&a.bytes)+ }+ })+ });++ // Critical path: a file whose own extraction outlasts everything the other+ // workers can do in parallel decides the wall clock by itself, so it must+ // start now whatever band it is in.+ let (mut critical, rest): (Vec<&Item>, Vec<&Item>) = ranked+ .into_iter()+ .partition(|item| is_critical_path(item.bytes, total, workers));+ critical.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.index.cmp(&b.index)));++ critical+ .into_iter()+ .chain(rest)+ .map(|item| item.index)+ .collect()+}++/// `size × workers > (everything else)` — this file cannot be hidden behind+/// the rest of the run. At most `workers` files can satisfy it.+pub fn is_critical_path(bytes: u64, total_bytes: u128, workers: usize) -> bool {+ let others = total_bytes.saturating_sub(bytes as u128);+ (bytes as u128).saturating_mul(workers.max(1) as u128) > others+}++/// [`start_order`] reversed, ready for a queue that is drained with `pop()`.+pub fn start_order_as_pop_queue(items: &[Item], workers: usize) -> Vec<usize> {+ let mut order = start_order(items, workers);+ order.reverse();+ order+}++/// Per-band totals, in drain order, for the plan output.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct BandSummary {+ pub band: &'static str,+ pub why: &'static str,+ pub files: u64,+ pub bytes: u64,+}++pub fn summarize(items: &[Item]) -> Vec<BandSummary> {+ Band::ALL+ .iter()+ .filter_map(|band| {+ let (files, bytes) = items+ .iter()+ .filter(|i| i.band == *band)+ .fold((0u64, 0u64), |(files, bytes), item| {+ (files + 1, bytes + item.bytes)+ });+ (files > 0).then_some(BandSummary {+ band: band.as_str(),+ why: band.why(),+ files,+ bytes,+ })+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item(index: usize, band: Band, bytes: u64) -> Item {+ Item { index, band, bytes }+ }++ #[test]+ fn source_and_docs_drain_before_vendored_whatever_the_size() {+ // The pre-#242 rule was size alone, so the 100 MB vendored blob went+ // first and the source tree went last.+ let items = [+ item(0, Band::Vendored, 100 << 20),+ item(1, Band::SourceAndDocs, 4 << 10),+ item(2, Band::SourceAndDocs, 8 << 10),+ item(3, Band::Config, 1 << 10),+ ];+ // 8 workers: the blob is 100 MB against 13 KB of everything else, so it+ // IS the critical path and legitimately starts first.+ assert_eq!(start_order(&items, 8), vec![0, 2, 1, 3]);++ // Give the valuable bands real weight and the blob stops dominating:+ // now value order decides, biggest-first inside each band.+ let items = [+ item(0, Band::Vendored, 100 << 20),+ item(1, Band::SourceAndDocs, 400 << 20),+ item(2, Band::SourceAndDocs, 500 << 20),+ item(3, Band::Config, 300 << 20),+ ];+ assert_eq!(start_order(&items, 8), vec![2, 1, 3, 0]);+ }++ #[test]+ fn a_single_worker_runs_smallest_first_inside_a_band() {+ let items = [+ item(0, Band::SourceAndDocs, 9),+ item(1, Band::SourceAndDocs, 1),+ item(2, Band::SourceAndDocs, 5),+ ];+ // W=1: nothing is concurrent, so "searchable earliest" is literally+ // "shortest first". (9 is still critical-path — 9 > 6 — so it leads;+ // the rest is smallest-first.)+ assert_eq!(start_order(&items, 1), vec![0, 1, 2]);++ let items = [+ item(0, Band::SourceAndDocs, 4),+ item(1, Band::SourceAndDocs, 5),+ item(2, Band::SourceAndDocs, 6),+ ];+ assert_eq!(start_order(&items, 1), vec![0, 1, 2]);+ // W>1 flips it back to biggest-first inside the band.+ assert_eq!(start_order(&items, 4), vec![2, 1, 0]);+ }++ /// The exception exists so value-first ordering cannot make the run+ /// *longer*: a file that outlasts all the parallel work above it has to+ /// start at t=0 or it becomes the tail on its own.+ #[test]+ fn a_file_that_outlasts_everything_above_it_starts_first() {+ let mut items = vec![item(0, Band::Vendored, 10_000)];+ for i in 1..=20 {+ items.push(item(i, Band::SourceAndDocs, 10));+ }+ // 10_000 × 4 > 200, so the vendored blob is the critical path.+ assert_eq!(start_order(&items, 4)[0], 0);+ assert!(is_critical_path(10_000, 10_200, 4));++ // Make the source band big enough to hide it and it goes back to last.+ let mut items = vec![item(0, Band::Vendored, 10_000)];+ for i in 1..=200 {+ items.push(item(i, Band::SourceAndDocs, 10_000));+ }+ assert!(!is_critical_path(10_000, 2_010_000, 4));+ assert_eq!(*start_order(&items, 4).last().unwrap(), 0);+ }++ #[test]+ fn the_pop_queue_is_the_start_order_reversed() {+ let items = [+ item(0, Band::Bulk, 1),+ item(1, Band::SourceAndDocs, 2),+ item(2, Band::Config, 3),+ ];+ let mut queue = start_order_as_pop_queue(&items, 2);+ let mut popped = Vec::new();+ while let Some(index) = queue.pop() {+ popped.push(index);+ }+ assert_eq!(popped, start_order(&items, 2));+ }++ #[test]+ fn vendored_paths_are_recognised_by_segment_name_and_by_suffix() {+ assert_eq!(+ vendored_reason("node_modules/left-pad/index.js"),+ Some("node_modules")+ );+ assert_eq!(+ vendored_reason("engine/target/release/build.rs"),+ Some("target")+ );+ assert_eq!(vendored_reason("web/app.min.js"), Some(".min.js"));+ assert_eq!(vendored_reason("Cargo.lock"), Some("Cargo.lock"));+ assert_eq!(vendored_reason("src/main.rs"), None);+ assert_eq!(vendored_reason("docs/README.md"), None);+ // A file literally called `.map` is not a source map.+ assert_eq!(vendored_reason(".map"), None);+ // A directory that merely *contains* the word is not the word.+ assert_eq!(vendored_reason("src/vendorish/a.rs"), None);+ }++ #[test]+ fn a_vendored_path_outranks_its_family() {+ assert_eq!(band("src/main.rs", Family::Code), Band::SourceAndDocs);+ assert_eq!(+ band("node_modules/x/index.js", Family::Code),+ Band::Vendored+ );+ assert_eq!(band("app.yaml", Family::Yaml), Band::Config);+ assert_eq!(band("var/log/app.log", Family::Logs), Band::Bulk);+ assert_eq!(band("data/rows.csv", Family::Csv), Band::Data);+ // The durable plan stores the family as a string; both paths agree.+ assert_eq!(+ band_from_family_str("src/main.rs", "code"),+ Band::SourceAndDocs+ );+ assert_eq!(band_from_family_str("x/a.csv", "csv"), Band::Data);+ assert_eq!(band_from_family_str("vendor/a.rs", "code"), Band::Vendored);+ // Unknown families are not promoted on a guess.+ assert_eq!(band_from_family_str("a.weird", "martian"), Band::Bulk);+ }++ #[test]+ fn the_band_summary_covers_every_planned_byte_exactly_once() {+ let items = [+ item(0, Band::SourceAndDocs, 10),+ item(1, Band::SourceAndDocs, 20),+ item(2, Band::Vendored, 70),+ ];+ let summary = summarize(&items);+ assert_eq!(summary.len(), 2, "empty bands are not printed: {summary:?}");+ assert_eq!(summary[0].band, "source-and-docs");+ assert_eq!((summary[0].files, summary[0].bytes), (2, 30));+ assert_eq!((summary[1].files, summary[1].bytes), (1, 70));+ assert_eq!(summary.iter().map(|b| b.bytes).sum::<u64>(), 100);+ }++ #[test]+ fn an_empty_corpus_orders_without_panicking() {+ assert!(start_order(&[], 8).is_empty());+ assert!(start_order(&[], 0).is_empty());+ assert!(summarize(&[]).is_empty());+ // A zero-byte corpus must not divide by anything.+ let items = [item(0, Band::Config, 0), item(1, Band::Config, 0)];+ assert_eq!(start_order(&items, 4).len(), 2);+ }+}diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rsindex 1d4d5a70b..390528b96 100644--- a/engine/crates/xerj-server/src/brain.rs+++ b/engine/crates/xerj-server/src/brain.rs@@ -521,6 +521,13 @@ fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {brain: Some(brain.to_string()),no_graph: false,dry_run: false,+ // The estimate/decision gate is an `xerj autoindex` CLI feature, and+ // `xerj brain` has no `--approve` of its own to answer it with. Arming+ // it here would stop the run with exit 4 and instructions the caller+ // literally cannot follow — so it is off, explicitly, until `brain`+ // grows its own answer flag. The estimate itself is still printed.+ max_minutes: 0,+ approve: None,json: false,quiet: false,// `xerj brain` is a foreground command a human watches; it gets thediff --git a/landing/llms.txt b/landing/llms.txtindex 2c9f2adc4..b7a44a813 100644--- a/landing/llms.txt+++ b/landing/llms.txt@@ -100,6 +100,10 @@ Two honesty notes the payload states about itself and you should pass on: the es- **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.+- **The binary now enforces the ask — you no longer have to remember it.** Since v1.0.0-rc.15, `autoindex` measures per-format throughput **on the user's own machine** during phase A (it is already parsing every file to sniff it) and prints a range with its basis before phase B starts: `estimate: at least 64.2 s–64.2 s — a MEASURED FLOOR for client-side extraction…`, then one line per family (`code 500 files 749.3 MB at 11.7 MB/s measured over 500 file(s) → 64.2 s`). If the upper end exceeds `--max-minutes` (**default 10**) and you passed no `--approve`, it **indexes nothing**, writes a JSON decision request to stdout and exits **4** — a code of its own, so "I need a decision" is never confused with exit 1's catch-all failure. Answer by re-running the identical command with `--approve proceed|fast|cancel` (`--yes` = proceed); `--max-minutes 0` disables the gate. A person at a terminal is prompted instead, and a piped run is never blocked on stdin.+ * **The number is a floor, not a prediction, and it says so.** It covers client-side extraction only: server indexing, embedding, network and edge-writing are not measured before the run starts, because measuring them would mean writing to the index the estimate exists to ask permission for. Measured here: on a 68 MB source tree the floor was 0.1 s against a real 8.9 s run; on a 793 MB one it was 64.2 s against a real ~350 s run. **So the gate under-asks and never over-asks** — when it fires the run is certainly long, but silence is not a promise the run is short. Say that to your user rather than repeating the floor as an ETA.+ * **Families it could not time are named, not guessed at.** A family only gets a rate from files phase A provably read end to end; `sqlite` (row-capped) and gzipped files never qualify. Unpriced families appear under `unmeasured_families` with their byte counts, and `coverage` tells you what share of planned bytes the number actually covers. If nothing could be measured, there is no number and no gate — the `basis` field says so.+ * **The payload is built for you.** `{"xerj":"autoindex-decision-request","exit_code":4,"reason":…,"estimate":{…},"priority_order":[…],"heaviest_directories":[…],"options":[…]}` — `heaviest_directories` names real byte counts and flags the ones matching the vendored/generated rule, and the `narrower` option re-costs the run without them using the same measured rates. The `fast` option deliberately states **no speed-up factor**: it reports which datasets and how many files it changes and says the factor was not measured.- **If it is going to be long, ask instead of deciding for them.** Present the real trade-off:* **Full** — everything: binary/hostile format extraction (PDF, DOCX, SQLite, gzip…), inferred types, embedded body fields, relationship edges.* **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`.)@@ -123,7 +127,8 @@ xerj-progress phase=index basis=bytes pct=93.4 items=8082/8083 bytes=136376668/1* **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. 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.+- **The valuable files are indexed first, and the plan says why.** Phase B drains source and documents, then configuration, then structured data, then logs and line files, and vendored/generated/minified paths (`node_modules`, `vendor`, `target`, `dist`, `*.min.js`, lockfiles…) last — so a user who stops early, or searches while it runs, already has what they came for. The `work order:` line and the payload's `priority_order` give the per-band file and byte counts plus the reason each band sits where it does. Inside a band the biggest file starts first (with several workers it runs *alongside* the band instead of becoming the tail); a single-worker run goes smallest-first. One file large enough to outlast everything ranked above it starts first regardless of band. A misfiled path costs a file its place in the queue and nothing else — everything is still indexed.+- **Read the exit code correctly.** `0` complete (also: gate answered `--approve cancel`) · **`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, the JSON decision request is on stdout, 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