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): first-class Unity project indexing (reland of #274)
xerj-org57383ce9ac41
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b44006384..5564d15d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,126 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-_Nothing yet._+### Added++- **`xerj autoindex` understands Unity projects.** Text-serialized scenes,+ prefabs, `.asset`/`.mat`/`.anim` files become **one record per+ GameObject/Component** (`unity_class`, `unity_class_id`, `file_id`,+ `ref_guids`, `script_guid`, plus the flattened body); `.meta` sidecars become+ a guid↔asset-path table; MonoBehaviour records carry a denormalized+ `script_class`/`script_path` so "which scenes use this script?" is one query.+ Detection is by the `%YAML` + `%TAG !u! tag:unity3d.com` header and never by+ extension, so binary-serialized assets stay junk (enable Force Text+ serialization). Unity's generated directories (`Library/`, `Temp/`, `obj/`,+ `Logs/`, `UserSettings/`) are pruned and recorded only when a sibling+ `ProjectSettings/ProjectVersion.txt` proves the tree really is a Unity+ project.++ Reland of community PR #274 by **@gonchar**, brought up to current `main` and+ corrected — see Fixed below for what changed on the way in.++- **BVH motion capture** — one metadata record per clip (`joints`,+ `joint_count`, `frames`, `frame_time_s`, `duration_s`). The numeric MOTION+ block, which is most of the file, is never read: extraction stops at the+ `Frame Time:` line.++- **`--stub <glob>`** designates files that should be *referenceable but not+ parsed*: each match is indexed as one name-card record and its contents are+ never opened.++### Fixed++- **Unity assets were sampled through a 4 MiB cap, silently junking whole+ object classes.** Unity YAML is a grouped family — each `unity_class` is its+ own dataset and a class's first document can sit anywhere in a scene that+ `extract/unity.rs` itself says can exceed 200 MB. A class first appearing+ past the cap was never sampled, got no entry in the plan, and phase B then+ had nowhere to route its records: they became `file_junk` with nothing said.+ The cap is now 512 MiB for this family, **and** any record whose group was+ never sampled is now reported by name and count instead of silently counted+ as junk.++- **A `script_guid` that failed to resolve produced no counter, no warning and+ no report line.** `build_unity_guid_map` discarded `extract_meta`'s `Result`,+ so an unreadable `.meta` was indistinguishable from a script nothing+ references — on the feature's own headline query. Unreadable sidecars,+ sidecars carrying no usable guid, and unresolvable `script_guid`s are now+ each reported.++- **`script_path`/`script_class` were mapped only when the phase-A sample+ happened to contain a `script_guid`**, while phase B stamps them whenever a+ guid resolves. A cluster whose sampled window held no `m_Script` therefore+ got them dynamic-mapped at index time, feeding the field-budget overshoot in+ #312. They are now registered for every Unity cluster, and the enrichment+ runs *before* `coerce_record` rather than after it, so the fields it stamps+ are validated like every other field instead of bypassing coercion.++- **`build_unity_guid_map` ran serially, unmetered, on the critical path of+ every run** — including a resumed no-op incremental, which otherwise has no+ work to do. A real Unity project has 10k-500k `.meta` sidecars. It now runs+ on `crate::pool` under the progress meter (the unattributed-stretch pattern+ of #241).++- **A `--stub` file was named from the content path**, which under durable+ preparation is a content-addressed blob — so every stub's one and only field+ would have been titled after a blob ordinal (the #294 failure class).+ It now uses `Sniffed::logical_name`.++- **`order::band_from_family_str` disagreed with `order::band`.** The string+ form's catch-all ranked `binary` as `Bulk` where the enum form ranks it+ `Vendored`, so a resumed run could order work differently from the run that+ planned it. Both now agree for every family, pinned by a test that iterates+ the whole enum.++- **The autoindex use-case README documented three flags and behaviours that+ do not exist.** `--no-default-excludes` and `--no-gitignore` are spelled+ `--no-default-ignores` and `--no-ignore`, and `cli::parse` hard-errors on an+ unknown argument — so a reader who copied the documented invocation got an+ error instead of an index. The marker-gated pruning of `node_modules/` and+ `target/` was described but had been dropped from the branch. A test now+ parses every `--flag` named in that README and fails if the CLI would reject+ it.++- **`stub_matcher_tests::an_invalid_pattern_fails_loudly_at_startup` did not+ test its own name** — it asserted only that a *valid* pattern compiles.+ `glob_to_regex` escapes every metacharacter, so no glob can produce a+ syntactically invalid regex; the one reachable failure is the compiled-size+ limit, which `?` and `**` reach at ~10^5 characters. Over-long patterns are+ now rejected explicitly with a message naming the flag and the limit, and the+ test exercises that path.++### Changed++- **A proposed whitespace-density binary heuristic was dropped before it+ shipped.** PR #274 classified any text over 4 KiB with under 5% whitespace as+ binary, to catch raw TGA payloads. `nonblank` is built from `text.lines()`,+ so newlines are already stripped and only intra-line whitespace counts —+ which means Chinese, Japanese, Korean, Thai, Lao, Khmer and Burmese prose,+ base64 blobs, FASTA sequences and minified single-line files all scored 0%+ and would have been junked as "binary content (unknown)", worldwide, in every+ corpus. This repo's own+ `failure_resume_http_tests::legacy_key_collision_fails_before_visibility_with_scoped_guidance`+ builds a 65,537-byte fixture of one repeated ASCII letter; with the guard in+ place that run exits 3 instead of 0. High-byte payloads (what a real TGA is)+ are still caught by the windows-1252 non-ASCII test, which is additionally+ now skipped for byte sequences that decode losslessly as Shift-JIS/GBK/Big5/+ EUC-KR with a substantially ideographic result — legacy-encoded CJK prose is+ ~100% high-byte and was being junked by it. That probe deliberately reports+ only "this is text", not *which* encoding: those four share most of their+ valid double-byte space, and picking one without a statistical language model+ would replace a Chinese document with plausible-looking Japanese mojibake.++ New magic-byte signatures (PSD, TIFF, RIFF, OGG, FLAC, MP3, FBX, EXR) are+ kept — those are precise.++### Known issues++- `ref_guids` (Unity) and `joints` (BVH) are multi-valued keyword arrays, and+ #332 means array elements are joined into one FTS token, so a post-flush+ `term`/`match` on a single element does not hit. `script_guid`,+ `script_path` and `script_class` are single-valued and unaffected, so the+ documented "which scenes use this script?" query is not impacted. Fixing+ #332 is an engine-side change to the FTS writer input type.## [1.0.0-rc.16] - 2026-08-13diff --git a/README.md b/README.mdindex 33a74bed5..ddac10d63 100644--- a/README.md+++ b/README.md@@ -113,7 +113,12 @@ done in 158.1s, 593 datasets, 83103 records live, 790 junk recordsSource files go through tree-sitter, so code arrives with its symbols and linenumbers instead of as flat text. CSV, JSON, JSONL, XML, YAML, SQLite, PDF, DOCX,-HTML and common log formats are all handled.+HTML and common log formats are all handled. Unity projects get first-class+treatment: text-serialized scenes, prefabs and assets become one record per+GameObject/Component, `.meta` files become a GUID↔path table, and MonoBehaviour+records carry `script_class`/`script_path` so "which scenes use this script?"+is a single query (binary-serialized assets need Force Text to be readable;+generated dirs like `Library/` are auto-skipped and recorded).## Search itdiff --git a/demo/usecases/autoindex/README.md b/demo/usecases/autoindex/README.mdindex ce5526d4f..d806991c5 100644--- a/demo/usecases/autoindex/README.md+++ b/demo/usecases/autoindex/README.md@@ -104,8 +104,22 @@ walk → sniff → sample → infer → map → extract → bulk → correlatehint at best, never trusted. Formats covered by streaming extractors:JSON/JSONL, CSV (dialect detection: comma/semicolon/tab, decimal comma,quoted multiline fields, BOM), structured logs (nginx CLF, app logs,- syslog), SQL dumps, SQLite, PDF, DOCX, HTML, XML, YAML, plain text,- gzip-compressed variants of the above.+ syslog), SQL dumps, SQLite, PDF, DOCX, HTML, XML, YAML, Unity+ text-serialized assets (scenes/prefabs/.asset/.mat/.anim → one record per+ GameObject/Component with `unity_class`, `file_id`, guid references, and a+ denormalized `script_class`/`script_path` on MonoBehaviours; `.meta`+ sidecars → a guid↔asset-path table; detected by the `%TAG !u!` header,+ never extension — binary-serialized Unity assets stay junk, enable Force+ Text serialization; generated dirs are pruned and recorded when a sibling+ marker proves them, at any nesting depth — Unity `Library/`, `Temp/`,+ `obj/`, `Logs/`, `UserSettings/` next to+ `ProjectSettings/ProjectVersion.txt`; `--no-default-ignores` walks them;+ additionally, when the root is inside a git repository the tree's+ `.gitignore` rules are honored — the owner's own declaration of generated+ noise — with `--no-ignore` to opt out, and the user's global gitignore is+ never consulted), BVH motion capture (one metadata record per clip — skeleton+ joint names, frame count, duration; the numeric MOTION block is never+ read), plain text, gzip-compressed variants of the above.3. **Sample** — bounded per-file sampling (default 500 records,`--sample N`); inference cost does not grow with file size.4. **Infer** — field types (long/double/boolean/date/keyword/text), datediff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rsindex 290c4d811..43c8ffc07 100644--- a/engine/crates/xerj-autoindex/src/cli.rs+++ b/engine/crates/xerj-autoindex/src/cli.rs@@ -40,6 +40,9 @@ pub struct IndexCfg {pub state_dir: Option<PathBuf>,pub fresh: bool,pub follow_symlinks: bool,+ /// `--stub <glob>` patterns: matching files are indexed as one+ /// existence-only name card, contents never opened.+ pub stub_globs: Vec<String>,/// `.gitignore` / `.xerjignore` / built-in build-output rules (#276)./// `deep_count` is set from `--dry-run`.pub ignore: IgnoreOptions,@@ -86,7 +89,10 @@ pub struct StatusCfg {#[derive(Debug)]pub enum Cmd {- Index(IndexCfg),+ /// Boxed: `IndexCfg` is an order of magnitude larger than the other+ /// variants, so inlining it made every `Cmd` — including `Help` — pay for+ /// it (`clippy::large_enum_variant`).+ Index(Box<IndexCfg>),Map(MapCfg),Status(StatusCfg),Help,@@ -146,6 +152,12 @@ pub fn help_text_with(feedback: bool) -> String {bytes (default 64); excludes filesystem/manifest overhead\n\--fresh {fresh_help}\n\--follow-symlinks follow symlinks (loop-safe); off by default\n\+ --stub <GLOB> index matching files as ONE existence-only name\n\+ card (title + provenance); contents are never\n\+ opened. Repeatable. A pattern without '/'\n\+ matches file names anywhere ('*.bvh'); with '/'\n\+ it matches the root-relative path\n\+ ('unity/**/*.csv'). '**' crosses directories\n\--no-ignore index everything: no .gitignore, no .xerjignore, no\n\.git/info/exclude, no built-in defaults. Hidden files\n\(.env, .git/, .ssh) stay skipped either way — that is\n\@@ -375,6 +387,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {let mut state_dir: Option<PathBuf> = None;let mut fresh = false;let mut follow_symlinks = false;+ let mut stub_globs: Vec<String> = Vec::new();let mut no_ignore = false;let mut no_default_ignores = false;let mut max_file_gb = 2u64;@@ -468,6 +481,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {"--state-dir" => state_dir = it.next().map(PathBuf::from),"--fresh" => fresh = true,"--follow-symlinks" => follow_symlinks = true,+ "--stub" => stub_globs.push(it.next().ok_or("--stub needs a glob pattern")?),"--no-ignore" => no_ignore = true,"--no-default-ignores" => no_default_ignores = true,"--max-file-gb" => {@@ -727,7 +741,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {})),(None, Some(root)) => {let plan = crate::resources::plan(workers, pdf_workers, bulk_mb);- Ok(Cmd::Index(IndexCfg {+ Ok(Cmd::Index(Box::new(IndexCfg {root,url,api_key,@@ -744,6 +758,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {state_dir,fresh,follow_symlinks,+ stub_globs,ignore: IgnoreOptions {enabled: !no_ignore,defaults: !no_ignore && !no_default_ignores,@@ -763,7 +778,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {quiet,progress,progress_interval,- }))+ })))}_ => Ok(Cmd::Help),}@@ -838,7 +853,7 @@ mod tests {fn index(args: &[&str]) -> super::IndexCfg {match parse(args.iter().map(|s| s.to_string()).collect()).unwrap() {- Cmd::Index(cfg) => cfg,+ Cmd::Index(cfg) => *cfg,other => panic!("expected index config, got {other:?}"),}}@@ -1256,6 +1271,55 @@ mod tests {assert!(index(&["data", "--dry-run"]).ignore.deep_count);}+ /// Every `--flag` the autoindex use-case README names must be one this+ /// parser actually accepts.+ ///+ /// `parse` hard-errors `unknown argument: {other}` on anything it does+ /// not know, so a documented-but-nonexistent flag does not degrade — the+ /// command exits. The README shipped `--no-default-excludes` and+ /// `--no-gitignore`, which have never existed under those names (they are+ /// `--no-default-ignores` and `--no-ignore`), so every reader who copied+ /// the documented invocation got an error instead of an index.+ ///+ /// Flags belonging to the `xerj` SERVER binary are excluded by name —+ /// the README also shows how to start a server, and those are not this+ /// parser's vocabulary.+ #[test]+ fn every_flag_named_in_the_usecase_readme_is_a_real_autoindex_flag() {+ const SERVER_ONLY: &[&str] = &["--insecure", "--data-dir"];++ let readme = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../../demo/usecases/autoindex/README.md");+ let text = std::fs::read_to_string(&readme)+ .unwrap_or_else(|e| panic!("read {}: {e}", readme.display()));++ let mut named: Vec<String> = Vec::new();+ for tok in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '-')) {+ // `---` is a YAML document marker in the sample output, not a flag.+ if tok.starts_with("--") && tok.len() > 2 && !tok.starts_with("---") {+ let tok = tok.trim_end_matches('-');+ if !SERVER_ONLY.contains(&tok) && !named.contains(&tok.to_string()) {+ named.push(tok.to_string());+ }+ }+ }+ assert!(+ named.len() >= 5,+ "extraction found almost nothing ({named:?}) — the test would pass vacuously"+ );++ for flag in &named {+ // A flag that exists but wants a value fails on the VALUE; only an+ // unrecognised name produces "unknown argument".+ if let Err(e) = parse(["data", flag].iter().map(|s| s.to_string()).collect()) {+ assert!(+ !e.contains("unknown argument"),+ "README documents {flag}, which the CLI rejects: {e}"+ );+ }+ }+ }+/// A flag that cannot change anything is refused rather than accepted and/// quietly dropped (#204's class).#[test]diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rsindex 90f01b341..53197a00a 100644--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs@@ -35,7 +35,12 @@ impl MockEs {let (sd, ss) = (Arc::clone(&docs), Arc::clone(&stop));let join = thread::spawn(move || loop {match listener.accept() {- Ok((stream, _)) => handle(stream, &sd),+ Ok((stream, _)) => {+ // BSD/macOS: accepted sockets inherit the listener's+ // O_NONBLOCK; the handler does blocking reads.+ stream.set_nonblocking(false).unwrap();+ handle(stream, &sd)+ }Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {if *ss.lock().unwrap() {break;@@ -269,6 +274,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {state_dir: Some(state_dir.to_owned()),fresh: false,follow_symlinks: false,+ stub_globs: Vec::new(),ignore: crate::ignore_rules::IgnoreOptions::default(),max_file_gb: 1,sample: 50,diff --git a/engine/crates/xerj-autoindex/src/estimate.rs b/engine/crates/xerj-autoindex/src/estimate.rsindex 4ffc2d0e8..a580be54b 100644--- a/engine/crates/xerj-autoindex/src/estimate.rs+++ b/engine/crates/xerj-autoindex/src/estimate.rs@@ -89,6 +89,10 @@ use std::time::Duration;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;+/// Sampling byte cap for Unity assets (mirrors `crate::UNITY_SAMPLE_LIMIT`).+const UNITY_SAMPLE_LIMIT: u64 = 512 << 20;+/// Whole-file cap for `.meta` sidecars (mirrors `extract::unity::META_CAP`).+const UNITY_META_CAP: u64 = 16 << 20;/// Bytes phase A **provably** read in full for this file, or `None` when the/// read was or may have been partial.@@ -125,8 +129,21 @@ pub fn exact_scan_bytes(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),+ // Grouped like SqlDump — the sink reads on so every Unity class gets+ // sampled — so again only the byte cap can have truncated the read.+ Family::UnityYaml => (size <= UNITY_SAMPLE_LIMIT).then_some(size),+ // `read_whole` up to META_CAP: under the cap the read is complete,+ // over it the file is junked after reading only cap+1 bytes.+ Family::UnityMeta => (size <= UNITY_META_CAP).then_some(size),// Row-capped per table; bytes read bear no fixed relation to `size`.Family::Sqlite => None,+ // Deliberately partial: `bvh::extract` stops at `Frame Time:` and+ // never pulls the motion block off disk, so `size` is not the number+ // of bytes this machine demonstrated it can chew through.+ Family::Bvh => None,+ // `--stub` files are never opened. Zero bytes read for a non-zero+ // `size` would fabricate an unbounded rate.+ Family::Stub => None,// Never extracted at all.Family::Binary => None,}@@ -619,13 +636,81 @@ mod tests {exact_scan_bytes(Family::SqlDump, false, 128 << 20, 1, 500),None);+ // Unity assets are grouped like SQL dumps: byte cap only.+ assert_eq!(+ exact_scan_bytes(Family::UnityYaml, false, 1 << 20, 9_999, 500),+ Some(1 << 20)+ );+ assert_eq!(+ exact_scan_bytes(Family::UnityYaml, false, 1024 << 20, 1, 500),+ None+ );+ // `.meta` sidecars are read whole up to META_CAP.+ assert_eq!(+ exact_scan_bytes(Family::UnityMeta, false, 4 << 10, 1, 500),+ Some(4 << 10)+ );+ assert_eq!(+ exact_scan_bytes(Family::UnityMeta, false, 32 << 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);+ // BVH stops at the motion header by design, so `size` is never the+ // number of bytes it read; `--stub` files are never opened at all.+ // Either one returning `Some(size)` would invent throughput.+ assert_eq!(+ exact_scan_bytes(Family::Bvh, false, 500 << 20, 1, 500),+ None+ );+ assert_eq!(+ exact_scan_bytes(Family::Stub, false, 500 << 20, 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);}+ /// `band` and `band_from_family_str` are the SAME decision made from a+ /// live enum and from the string the durable plan persisted. They drifted+ /// silently once already: the string form's `_ => Bulk` catch-all meant a+ /// resumed run demoted every Unity asset out of the source band. Every+ /// family must agree across the two.+ #[test]+ fn the_two_band_functions_agree_for_every_family() {+ use crate::order::{band, band_from_family_str};+ for family in [+ Family::Jsonl,+ Family::Json,+ Family::Csv,+ Family::Logs,+ Family::Xml,+ Family::Html,+ Family::Yaml,+ Family::TxtProse,+ Family::TxtLines,+ Family::Pdf,+ Family::Docx,+ Family::Sqlite,+ Family::SqlDump,+ Family::Code,+ Family::UnityYaml,+ Family::UnityMeta,+ Family::Bvh,+ Family::Stub,+ Family::Binary,+ ] {+ let rel = "a/b.dat";+ assert_eq!(+ band(rel, family),+ band_from_family_str(rel, family.as_str()),+ "{} disagrees between the enum and string band functions",+ family.as_str()+ );+ }+ }+#[test]fn the_meter_reports_only_families_it_actually_timed() {let meter = Meter::new();diff --git a/engine/crates/xerj-autoindex/src/extract/bvh.rs b/engine/crates/xerj-autoindex/src/extract/bvh.rsnew file mode 100644index 000000000..86be07a93--- /dev/null+++ b/engine/crates/xerj-autoindex/src/extract/bvh.rs@@ -0,0 +1,182 @@+//! BVH motion capture — ONE metadata record per file, motion data never read.+//!+//! A BVH file is a small skeleton HIERARCHY header followed by a numeric+//! MOTION block that can run to hundreds of MB (one line per frame). The+//! frames carry no retrieval value — they are float soup — but the header+//! does: joint names make the skeleton searchable, and frame count/time give+//! the clip's duration. So this extractor streams the header, captures that+//! metadata, and STOPS as soon as the two `Frames:`/`Frame Time:` lines after+//! `MOTION` are read — the motion block is never pulled off disk.+//!+//! Emitted fields: `title`, `joints` (names, document order), `joint_count`,+//! `frames`, `frame_time_s`, `duration_s`. All extractor vocabulary+//! (`FieldOrigin::Extractor`), so every BVH file clusters into one dataset.+//!+//! KNOWN LIMITATION (engine-side, xerj-org/xerj#332): `joints` is a+//! multi-valued keyword array, and the FTS writer currently joins array+//! elements into ONE space-separated token. So after a segment flush,+//! `{"term": {"joints": "LeftHand"}}` does NOT match — there is no+//! per-element posting. `terms` and other clauses that take the stored-scan+//! path still match, and so does everything before the flush, which is why+//! this is easy to miss. "Which clips animate LeftHand?" is only a reliable+//! one-query answer once #332 lands; it is an engine API change (the FTS+//! writer input is `HashMap<String, String>`), not something this extractor+//! can work around.++use super::{ExtractStats, FieldOrigin, RawRecord, Sink};+use anyhow::Result;+use serde_json::{Map, Value};+use std::path::Path;++/// Skeleton headers are a few KB; a "header" that runs past this is not a+/// BVH we understand, and the file junks rather than streaming megabytes.+const HEADER_CAP: usize = 1 << 20;++pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {+ let mut stats = ExtractStats::default();+ let mut r = super::open_reader(path, gzip, None)?;+ let mut joints: Vec<String> = Vec::new();+ let mut frames: Option<i64> = None;+ let mut frame_time: Option<f64> = None;+ let mut in_motion = false;+ let mut consumed = 0usize;+ let mut line: Vec<u8> = Vec::new();+ loop {+ line.clear();+ let n = super::jsonl::read_capped_line(&mut r, &mut line)?;+ if n == 0 {+ break;+ }+ consumed += n;+ if consumed > HEADER_CAP {+ stats.junk += 1;+ return Ok(stats);+ }+ let text = String::from_utf8_lossy(&line);+ let t = text.trim();+ if !in_motion {+ if let Some(name) = t.strip_prefix("ROOT ").or_else(|| t.strip_prefix("JOINT ")) {+ let name = name.trim();+ if !name.is_empty() && name.len() <= 200 {+ joints.push(name.to_string());+ }+ } else if t == "MOTION" {+ in_motion = true;+ }+ continue;+ }+ if let Some(v) = t.strip_prefix("Frames:") {+ frames = v.trim().parse().ok();+ } else if let Some(v) = t.strip_prefix("Frame Time:") {+ frame_time = v.trim().parse().ok();+ }+ if frames.is_some() && frame_time.is_some() {+ break; // metadata complete — the motion block is never read+ }+ }+ if joints.is_empty() {+ stats.junk += 1;+ return Ok(stats);+ }++ let title = path+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("motion")+ .to_string();+ let mut fields = Map::new();+ fields.insert("title".into(), Value::String(title));+ fields.insert(+ "joints".into(),+ Value::Array(joints.iter().map(|j| Value::String(j.clone())).collect()),+ );+ fields.insert(+ "joint_count".into(),+ Value::Number((joints.len() as u64).into()),+ );+ if let Some(f) = frames {+ fields.insert("frames".into(), Value::Number(f.into()));+ }+ if let Some(ft) = frame_time {+ if let Some(num) = serde_json::Number::from_f64(ft) {+ fields.insert("frame_time_s".into(), Value::Number(num));+ }+ if let (Some(f), true) = (frames, ft.is_finite()) {+ if let Some(num) = serde_json::Number::from_f64(f as f64 * ft) {+ fields.insert("duration_s".into(), Value::Number(num));+ }+ }+ }+ stats.records += 1;+ sink(RawRecord {+ fields,+ locator: "bvh".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ });+ Ok(stats)+}++#[cfg(test)]+mod tests {+ use super::*;++ const SAMPLE: &str = "HIERARCHY\nROOT Hips\n{\n OFFSET 0 90 0\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n JOINT LeftUpLeg\n {\n OFFSET 8.5 0 -2.5\n CHANNELS 3 Zrotation Xrotation Yrotation\n End Site\n {\n OFFSET 6.9 0 0\n }\n }\n}\nMOTION\nFrames: 120\nFrame Time: 0.033333\n0.0 90.0 0.0 1.1 2.2 3.3 4.4 5.5 6.6\n0.1 90.1 0.1 1.2 2.3 3.4 4.5 5.6 6.7\n";++ fn run(text: &str) -> (ExtractStats, Vec<RawRecord>) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("clip.bvh");+ std::fs::write(&path, text).unwrap();+ let mut recs = Vec::new();+ let stats = extract(&path, false, &mut |r| {+ recs.push(r);+ true+ })+ .unwrap();+ (stats, recs)+ }++ #[test]+ fn one_metadata_record_per_file_and_no_motion_rows() {+ let (stats, recs) = run(SAMPLE);+ assert_eq!((stats.records, stats.junk), (1, 0));+ let r = &recs[0];+ assert_eq!(r.fields["title"], "clip.bvh");+ assert_eq!(r.fields["joints"], serde_json::json!(["Hips", "LeftUpLeg"]));+ assert_eq!(r.fields["joint_count"], 2);+ assert_eq!(r.fields["frames"], 120);+ assert_eq!(r.fields["duration_s"].as_f64().unwrap().round(), 4.0);+ assert_eq!(r.locator, "bvh");+ }++ /// The point of the format: a clip with a multi-GB motion block must cost+ /// only its header. The reader stops after `Frame Time:`, so the frames+ /// after it are never even pulled through the BufReader into the record.+ #[test]+ fn extraction_stops_at_the_motion_header_not_the_motion_data() {+ let mut text = SAMPLE.to_string();+ text.push_str(&"9.9 ".repeat(500_000));+ let (stats, recs) = run(&text);+ assert_eq!(stats.records, 1);+ assert_eq!(recs[0].fields["frames"], 120);+ }++ #[test]+ fn a_hierarchy_without_joints_is_junk_not_an_empty_record() {+ let (stats, recs) = run("HIERARCHY\nMOTION\nFrames: 1\nFrame Time: 0.03\n1 2 3\n");+ assert_eq!(stats.records, 0);+ assert_eq!(stats.junk, 1);+ assert!(recs.is_empty());+ }++ #[test]+ fn a_runaway_header_is_junk_rather_than_streamed_forever() {+ let mut text = String::from("HIERARCHY\nROOT Hips\n{\n");+ for i in 0..40_000 {+ text.push_str(&format!(" JOINT J{i}\n {{\n OFFSET 0 0 0\n"));+ }+ let (stats, _) = run(&text);+ assert_eq!(stats.records, 0);+ assert_eq!(stats.junk, 1);+ }+}diff --git a/engine/crates/xerj-autoindex/src/extract/mod.rs b/engine/crates/xerj-autoindex/src/extract/mod.rsindex f2ec60b1c..2a0e9c4f7 100644--- a/engine/crates/xerj-autoindex/src/extract/mod.rs+++ b/engine/crates/xerj-autoindex/src/extract/mod.rs@@ -2,6 +2,7 @@//! Every extractor is bounded-memory and never fatal: parse failures//! downgrade (family → txt → junk-with-metadata) and are counted.+pub mod bvh;pub mod code;pub mod csv_x;pub mod docx;@@ -13,6 +14,7 @@ pub mod pdf;pub mod sqldump;pub mod sqlite_x;pub mod txt;+pub mod unity;pub mod xml_x;pub mod yaml_x;@@ -164,6 +166,32 @@ pub fn extract(Family::Sqlite => sqlite_x::extract(path, limit_bytes.map(|_| 500), sink),Family::SqlDump => sqldump::extract(path, sn.gzip, limit_bytes, sink),Family::Code => code::extract(path, sn, sink),+ Family::UnityYaml => unity::extract_unity(path, sn.gzip, limit_bytes, sink),+ Family::UnityMeta => unity::extract_meta(path, sn.gzip, sink),+ Family::Bvh => bvh::extract(path, sn.gzip, sink),+ // `--stub`-designated file: one name card, the file is never opened.+ Family::Stub => {+ let mut stats = ExtractStats::default();+ let mut fields = Map::new();+ // The name card is this record's ENTIRE content, so it must come+ // from the logical name. Under durable preparation `path` is a+ // content-addressed blob and would title every stub `00000000`.+ let named = sn.logical_name.as_deref().unwrap_or(path);+ let title = named+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("file")+ .to_string();+ fields.insert("title".into(), Value::String(title));+ stats.records += 1;+ sink(RawRecord {+ fields,+ locator: "stub".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ });+ Ok(stats)+ }Family::Binary => Ok(ExtractStats::default()),}}@@ -230,6 +258,46 @@ fn flatten_into(key: &str, v: Value, depth: usize, out: &mut Map<String, Value>)}}+/// Convert a parsed YAML value into JSON (shared by the YAML and Unity+/// extractors). Tagged values unwrap to their inner value; non-string mapping+/// keys are stringified.+pub(crate) fn yaml_to_json(v: serde_yaml::Value) -> Value {+ match v {+ serde_yaml::Value::Null => Value::Null,+ serde_yaml::Value::Bool(b) => Value::Bool(b),+ serde_yaml::Value::Number(n) => {+ if let Some(i) = n.as_i64() {+ Value::Number(i.into())+ } else if let Some(u) = n.as_u64() {+ Value::Number(u.into())+ } else {+ serde_json::Number::from_f64(n.as_f64().unwrap_or(0.0))+ .map(Value::Number)+ .unwrap_or(Value::Null)+ }+ }+ serde_yaml::Value::String(s) => Value::String(s),+ serde_yaml::Value::Sequence(seq) => {+ Value::Array(seq.into_iter().map(yaml_to_json).collect())+ }+ serde_yaml::Value::Mapping(m) => {+ let mut out = Map::new();+ for (k, vv) in m {+ let key = match k {+ serde_yaml::Value::String(s) => s,+ other => serde_yaml::to_string(&other)+ .unwrap_or_else(|_| "key".into())+ .trim()+ .to_string(),+ };+ out.insert(key, yaml_to_json(vv));+ }+ Value::Object(out)+ }+ serde_yaml::Value::Tagged(t) => yaml_to_json(t.value),+ }+}+/// Sanitize a discovered field/column name to a safe ES field name.pub fn sanitize_field_name(name: &str) -> String {let mut s: String = namediff --git a/engine/crates/xerj-autoindex/src/extract/unity.rs b/engine/crates/xerj-autoindex/src/extract/unity.rsnew file mode 100644index 000000000..480d8c00c--- /dev/null+++ b/engine/crates/xerj-autoindex/src/extract/unity.rs@@ -0,0 +1,539 @@+//! Unity text-serialized assets — streaming multi-document splitter — and+//! `.meta` sidecars.+//!+//! Unity YAML is a multi-document stream where every document opens with+//! `--- !u!<classId> &<fileID>` (optionally suffixed `stripped` for prefab+//! instances). serde_yaml cannot be used on the whole stream: it resolves+//! anchors internally and never exposes the anchor NAME, and the `fileID`+//! that makes Unity objects joinable lives in that anchor. So the splitter+//! owns the document boundaries (a cheap line prefix match) and hands each+//! body — plain YAML once the `%YAML`/`%TAG` header is dropped — to+//! serde_yaml individually. Owning the boundaries is also what makes it safe+//! to `continue` past a corrupt document: unlike `yaml_x`, there is no+//! iterator that would re-yield the same broken document forever.+//!+//! Files stream line-by-line (real scenes can exceed 200 MB; a single+//! AnimationClip document can be tens of MB), with a 16 MiB per-document+//! cap: over-cap documents are junked and skipped to the next boundary,+//! the rest of the file survives.+//!+//! Emitted fields per object document:+//! - `unity_class` body's top-level key (authoritative), else class-id table+//! - `unity_class_id` from the `!u!<id>` tag+//! - `file_id` from the `&<anchor>` — the join key for local refs+//! - `stripped` only present (true) on stripped prefab-instance docs+//! - `name` `m_Name` when present+//! - `ref_guids` deduped guids of every `{fileID, guid, type}` reference+//! - `script_guid` the `m_Script` reference's guid (MonoBehaviour → .cs)+//! - flattened body fields+//!+//! KNOWN LIMITATION (engine-side, xerj-org/xerj#332): `ref_guids` is a+//! multi-valued keyword array and the FTS writer joins array elements into+//! ONE space-separated token, so a post-flush `term`/`match` on a single guid+//! does not match. `script_guid`, `script_path` and `script_class` are+//! single-valued and unaffected — the documented "which scenes use this+//! script?" query goes through those, not through `ref_guids`.+//!+//! `.meta` sidecars emit ONE record: `guid`, `asset_name`, `importer`, and+//! flattened settings. The root-relative `asset_path` (and the+//! `script_path`/`script_class` denormalization on MonoBehaviour records) is+//! stamped by the pipeline, which knows the walk root — extractors stay+//! per-file pure.++use super::{flatten_object, yaml_to_json, ExtractStats, FieldOrigin, RawRecord, Sink, MAX_LINE};+use anyhow::Result;+use serde_json::{Map, Value};+use std::path::Path;++/// Per-document cap. One logical unit follows the `MAX_LINE` convention;+/// 16 MiB covers large AnimationClip / font documents while bounding memory.+/// (A 4 MiB cap was considered and rejected: it junks those documents.)+const DOC_CAP: usize = 16 << 20;++const META_CAP: u64 = 16 << 20;++/// Field names this extractor invents on object records. A body field with+/// the same name (possible on MonoBehaviour custom fields) is renamed+/// `data_<name>` rather than dropped, mirroring the `ax_*` collision policy.+const RESERVED: &[&str] = &[+ "unity_class",+ "unity_class_id",+ "file_id",+ "stripped",+ "name",+ "ref_guids",+ "script_guid",+ "script_path",+ "script_class",+];++pub fn extract_unity(+ path: &Path,+ gzip: bool,+ limit_bytes: Option<u64>,+ sink: Sink,+) -> Result<ExtractStats> {+ let mut r = super::open_reader(path, gzip, limit_bytes)?;+ let mut stats = ExtractStats::default();+ let mut offset: u64 = 0;+ let mut line: Vec<u8> = Vec::new();+ let mut doc: Vec<u8> = Vec::new();+ let mut header: Option<DocHeader> = None;+ let mut skipping = false;+ loop {+ line.clear();+ let n = super::jsonl::read_capped_line(&mut r, &mut line)?;+ let eof = n == 0;+ offset += n as u64;+ let boundary = if eof { None } else { parse_boundary(&line) };+ if eof || boundary.is_some() {+ if let Some(h) = header.take() {+ if skipping {+ skipping = false;+ } else {+ let truncated = eof && limit_bytes.is_some_and(|l| offset >= l);+ if !emit_doc(&h, &doc, truncated, &mut stats, sink) {+ return Ok(stats);+ }+ }+ }+ doc.clear();+ header = boundary;+ if eof {+ break;+ }+ continue;+ }+ if header.is_none() || skipping {+ continue; // %YAML/%TAG preamble, or discarding an over-cap doc+ }+ if doc.len() + line.len() > DOC_CAP {+ stats.junk += 1;+ skipping = true;+ doc.clear();+ continue;+ }+ doc.extend_from_slice(&line);+ }+ // Empty yield from a FULL read means the file was preamble-only (or+ // junk-shaped throughout) — record it. A sampling read that truncated+ // before the first document completed is not evidence of anything.+ let truncated_run = limit_bytes.is_some_and(|l| offset >= l);+ if stats.records == 0 && stats.junk == 0 && !truncated_run {+ stats.junk += 1;+ }+ Ok(stats)+}++struct DocHeader {+ class_id: i64,+ /// Raw anchor text (handles negative 64-bit ids verbatim).+ file_id: String,+ stripped: bool,+}++/// `--- !u!<classId> &<fileID>[ stripped]` — cheap manual parse, no regex on+/// the hot per-line path.+fn parse_boundary(line: &[u8]) -> Option<DocHeader> {+ let s = std::str::from_utf8(line).ok()?.trim_end();+ let rest = s.strip_prefix("--- !u!")?;+ let (id_part, rest) = rest.split_once(" &")?;+ let class_id: i64 = id_part.trim().parse().ok()?;+ let (anchor, tail) = match rest.split_once(' ') {+ Some((a, t)) => (a, t.trim()),+ None => (rest, ""),+ };+ let anchor = anchor.trim();+ if anchor.is_empty() || !anchor.chars().all(|c| c.is_ascii_digit() || c == '-') {+ return None;+ }+ Some(DocHeader {+ class_id,+ file_id: anchor.to_string(),+ stripped: tail == "stripped",+ })+}++fn emit_doc(+ h: &DocHeader,+ body: &[u8],+ truncated_by_sampling: bool,+ stats: &mut ExtractStats,+ sink: Sink,+) -> bool {+ let text = String::from_utf8_lossy(body);+ let parsed: serde_yaml::Value = match serde_yaml::from_str(&text) {+ Ok(v) => v,+ Err(_) => {+ if !truncated_by_sampling {+ stats.junk += 1;+ }+ return true;+ }+ };+ let jv = yaml_to_json(parsed);+ let (class_from_body, inner) = match jv {+ Value::Object(m) if m.len() == 1 => {+ let (k, v) = m.into_iter().next().expect("len checked");+ (Some(k), v)+ }+ other => (None, other),+ };+ let unity_class = class_from_body.unwrap_or_else(|| {+ class_name(h.class_id)+ .map(str::to_string)+ .unwrap_or_else(|| format!("class_{}", h.class_id))+ });++ let mut refs: Vec<String> = Vec::new();+ let mut script_guid: Option<String> = None;+ collect_guid_refs(&inner, &mut refs);+ if let Some(script) = inner.get("m_Script") {+ if let Some(g) = script.get("guid").and_then(Value::as_str) {+ script_guid = Some(g.to_string());+ }+ }++ let mut fields = match inner {+ Value::Object(m) => flatten_object(m),+ Value::Null => Map::new(),+ other => {+ let mut m = Map::new();+ m.insert("value".into(), other);+ m+ }+ };+ for k in RESERVED {+ if let Some(v) = fields.remove(*k) {+ fields.insert(format!("data_{k}"), v);+ }+ }+ if let Some(Value::String(n)) = fields.get("m_Name") {+ if !n.is_empty() {+ fields.insert("name".into(), Value::String(n.clone()));+ }+ }+ fields.insert("unity_class".into(), Value::String(unity_class.clone()));+ fields.insert("unity_class_id".into(), Value::Number(h.class_id.into()));+ fields.insert("file_id".into(), Value::String(h.file_id.clone()));+ if h.stripped {+ fields.insert("stripped".into(), Value::Bool(true));+ }+ if !refs.is_empty() {+ let mut seen = std::collections::HashSet::new();+ let deduped: Vec<Value> = refs+ .into_iter()+ .filter(|g| seen.insert(g.clone()))+ .map(Value::String)+ .collect();+ fields.insert("ref_guids".into(), Value::Array(deduped));+ }+ if let Some(g) = script_guid {+ fields.insert("script_guid".into(), Value::String(g));+ }++ stats.records += 1;+ sink(RawRecord {+ fields,+ locator: format!("u{}", h.file_id),+ group: Some(unity_class),+ // Body field names are Unity's serialization vocabulary plus per-script+ // custom fields; letting them cluster would split MonoBehaviours into+ // schema-similarity datasets and re-home documents when scripts change+ // (issue #178). Family+group clustering gives one stable dataset per+ // Unity class instead.+ origin: FieldOrigin::Extractor,+ })+}++/// Walk the parsed document for `{fileID, guid, type}` reference mappings and+/// collect every guid, including inside arrays (`m_Modifications` — prefab+/// overrides — is where the highest-value references live).+fn collect_guid_refs(v: &Value, out: &mut Vec<String>) {+ match v {+ Value::Object(m) => {+ if m.contains_key("fileID") {+ if let Some(g) = m.get("guid").and_then(Value::as_str) {+ out.push(g.to_string());+ }+ }+ for vv in m.values() {+ collect_guid_refs(vv, out);+ }+ }+ Value::Array(a) => {+ for vv in a {+ collect_guid_refs(vv, out);+ }+ }+ _ => {}+ }+}++pub fn extract_meta(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {+ let mut stats = ExtractStats::default();+ let Some(bytes) = super::read_whole(path, gzip, META_CAP)? else {+ stats.junk += 1;+ return Ok(stats);+ };+ let (text, _) = crate::sniff::decode_text(&bytes);+ let text = text.trim_start_matches('\u{feff}');+ let parsed: serde_yaml::Value = match serde_yaml::from_str(text) {+ Ok(v) => v,+ Err(_) => {+ stats.junk += 1;+ return Ok(stats);+ }+ };+ let Value::Object(m) = yaml_to_json(parsed) else {+ stats.junk += 1;+ return Ok(stats);+ };+ let guid = m.get("guid").and_then(Value::as_str).map(str::to_string);+ let importer = m+ .keys()+ .find(|k| k.ends_with("Importer") || k.ends_with("importer"))+ .cloned();+ let mut fields = flatten_object(m);+ if let Some(g) = guid {+ fields.insert("guid".into(), Value::String(g));+ }+ if let Some(imp) = importer {+ fields.insert("importer".into(), Value::String(imp));+ }+ if let Some(name) = path+ .file_name()+ .and_then(|n| n.to_str())+ .and_then(|n| n.strip_suffix(".meta"))+ {+ fields.insert("asset_name".into(), Value::String(name.to_string()));+ }+ stats.records += 1;+ sink(RawRecord {+ fields,+ locator: "meta".into(),+ group: None,+ origin: FieldOrigin::Extractor,+ });+ Ok(stats)+}++/// Fallback names for documents whose body failed to yield a top-level key+/// (the body key is authoritative when present). Sourced from Unity's public+/// class-id reference; unknown ids render `class_<id>`.+fn class_name(id: i64) -> Option<&'static str> {+ Some(match id {+ 1 => "GameObject",+ 2 => "Component",+ 4 => "Transform",+ 20 => "Camera",+ 21 => "Material",+ 23 => "MeshRenderer",+ 25 => "Renderer",+ 28 => "Texture2D",+ 33 => "MeshFilter",+ 43 => "Mesh",+ 54 => "Rigidbody",+ 61 => "BoxCollider2D",+ 64 => "MeshCollider",+ 65 => "BoxCollider",+ 74 => "AnimationClip",+ 81 => "AudioListener",+ 82 => "AudioSource",+ 90 => "Avatar",+ 91 => "AnimatorController",+ 95 => "Animator",+ 104 => "RenderSettings",+ 108 => "Light",+ 114 => "MonoBehaviour",+ 115 => "MonoScript",+ 128 => "Font",+ 135 => "SphereCollider",+ 136 => "CapsuleCollider",+ 137 => "SkinnedMeshRenderer",+ 157 => "LightmapSettings",+ 196 => "NavMeshSettings",+ 198 => "ParticleSystem",+ 199 => "ParticleSystemRenderer",+ 212 => "SpriteRenderer",+ 213 => "Sprite",+ 224 => "RectTransform",+ 320 => "PlayableDirector",+ 850595691 => "LightingSettings",+ 1001 => "PrefabInstance",+ 1660057539 => "SceneRoots",+ _ => return None,+ })+}++// The `MAX_LINE` import is load-bearing indirectly: `read_capped_line` caps+// each physical line at 16 MiB, and DOC_CAP matches it so a single-line+// document cannot bypass the document cap.+const _: () = assert!(DOC_CAP == MAX_LINE);++#[cfg(test)]+mod tests {+ use super::*;++ const SCENE: &str = "\u{feff}%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1234567890\nGameObject:\n m_ObjectHideFlags: 0\n m_Name: Player\n m_IsActive: 1\n--- !u!4 &1234567891\nTransform:\n m_GameObject: {fileID: 1234567890}\n m_LocalPosition: {x: 0, y: 1.5, z: 0}\n--- !u!114 &1234567892\nMonoBehaviour:\n m_GameObject: {fileID: 1234567890}\n m_Script: {fileID: 11500000, guid: abc123def456, type: 3}\n m_EditorClassIdentifier: \n speed: 4.5\n target: {fileID: 5555, guid: fedcba987654, type: 2}\n";++ fn run(text: &str, limit: Option<u64>) -> (ExtractStats, Vec<RawRecord>) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("t.unity");+ std::fs::write(&path, text).unwrap();+ let mut recs = Vec::new();+ let stats = extract_unity(&path, false, limit, &mut |r| {+ recs.push(r);+ true+ })+ .unwrap();+ (stats, recs)+ }++ fn run_meta(text: &str, name: &str) -> (ExtractStats, Vec<RawRecord>) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join(name);+ std::fs::write(&path, text).unwrap();+ let mut recs = Vec::new();+ let stats = extract_meta(&path, false, &mut |r| {+ recs.push(r);+ true+ })+ .unwrap();+ (stats, recs)+ }++ #[test]+ fn each_document_becomes_one_record_with_class_and_file_id() {+ let (stats, recs) = run(SCENE, None);+ assert_eq!((stats.records, stats.junk), (3, 0));+ assert_eq!(recs[0].fields["unity_class"], "GameObject");+ assert_eq!(recs[0].fields["unity_class_id"], 1);+ assert_eq!(recs[0].fields["file_id"], "1234567890");+ assert_eq!(recs[0].fields["name"], "Player");+ assert_eq!(recs[0].locator, "u1234567890");+ assert_eq!(recs[0].group.as_deref(), Some("GameObject"));+ assert_eq!(recs[1].fields["unity_class"], "Transform");+ assert_eq!(+ recs[1].fields["m_LocalPosition_y"], 1.5,+ "nested mappings flatten like every other extractor"+ );+ }++ #[test]+ fn monobehaviour_carries_script_guid_and_deduped_ref_guids() {+ let (_, recs) = run(SCENE, None);+ let mb = &recs[2];+ assert_eq!(mb.fields["unity_class"], "MonoBehaviour");+ assert_eq!(mb.fields["script_guid"], "abc123def456");+ assert_eq!(+ mb.fields["ref_guids"],+ serde_json::json!(["abc123def456", "fedcba987654"])+ );+ assert_eq!(mb.fields["speed"], 4.5, "custom script fields survive");+ }++ #[test]+ fn stripped_and_negative_file_ids_parse() {+ let text = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!4 &-8679921383154817045 stripped\nTransform:\n m_PrefabInstance: {fileID: 100100000, guid: 0123456789abcdef, type: 3}\n";+ let (stats, recs) = run(text, None);+ assert_eq!((stats.records, stats.junk), (1, 0));+ assert_eq!(recs[0].fields["file_id"], "-8679921383154817045");+ assert_eq!(recs[0].fields["stripped"], true);+ assert_eq!(recs[0].locator, "u-8679921383154817045");+ }++ #[test]+ fn crlf_line_endings_are_tolerated() {+ let text = SCENE.replace('\n', "\r\n");+ let (stats, recs) = run(&text, None);+ assert_eq!((stats.records, stats.junk), (3, 0));+ assert_eq!(recs[2].fields["script_guid"], "abc123def456");+ }++ #[test]+ fn a_corrupt_document_junks_only_itself() {+ let text = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1\nGameObject:\n m_Name: A\n--- !u!4 &2\n\t{{{ not yaml\n--- !u!1 &3\nGameObject:\n m_Name: B\n";+ let (stats, recs) = run(text, None);+ assert_eq!(stats.junk, 1);+ assert_eq!(stats.records, 2);+ assert_eq!(recs[1].fields["name"], "B");+ }++ #[test]+ fn an_over_cap_document_is_skipped_and_the_stream_continues() {+ let mut text = String::from("%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &1\nAnimationClip:\n m_Name: huge\n data: ");+ text.push_str(&"x".repeat(DOC_CAP + 1024));+ text.push_str("\n--- !u!1 &2\nGameObject:\n m_Name: after\n");+ let (stats, recs) = run(&text, None);+ assert_eq!(stats.junk, 1, "the oversized doc is junked, not fatal");+ assert_eq!(stats.records, 1);+ assert_eq!(recs[0].fields["name"], "after");+ }++ #[test]+ fn a_doc_cut_short_by_a_sampling_limit_is_not_junk() {+ let (stats, _) = run(SCENE, Some(120));+ assert_eq!(stats.junk, 0, "sampling truncation is not corruption");+ assert!(stats.records <= 1);+ }++ #[test]+ fn sampling_early_stop_via_sink_leaves_no_junk() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("t.unity");+ std::fs::write(&path, SCENE).unwrap();+ let mut n = 0;+ let stats = extract_unity(&path, false, None, &mut |_r| {+ n += 1;+ n < 2+ })+ .unwrap();+ assert_eq!(n, 2);+ assert_eq!(stats.junk, 0);+ }++ #[test]+ fn locators_are_idempotent_across_runs() {+ let (_, a) = run(SCENE, None);+ let (_, b) = run(SCENE, None);+ let la: Vec<_> = a.iter().map(|r| r.locator.clone()).collect();+ let lb: Vec<_> = b.iter().map(|r| r.locator.clone()).collect();+ assert_eq!(la, lb);+ }++ #[test]+ fn a_reserved_body_field_is_renamed_not_clobbered() {+ let text = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!114 &1\nMonoBehaviour:\n name: custom-field\n m_Name: Real\n";+ let (_, recs) = run(text, None);+ assert_eq!(recs[0].fields["data_name"], "custom-field");+ assert_eq!(recs[0].fields["name"], "Real");+ }++ #[test]+ fn unknown_class_id_with_unparseable_body_still_names_the_class() {+ let text = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!999999 &1\nsome scalar\n";+ let (stats, recs) = run(text, None);+ assert_eq!(stats.records, 1);+ assert_eq!(recs[0].fields["unity_class"], "class_999999");+ }++ #[test]+ fn meta_yields_guid_importer_and_asset_name() {+ let text = "fileFormatVersion: 2\nguid: 9f1c4d0ab2e34f6\nMonoImporter:\n externalObjects: {}\n serializedVersion: 2\n";+ let (stats, recs) = run_meta(text, "Player.cs.meta");+ assert_eq!((stats.records, stats.junk), (1, 0));+ assert_eq!(recs[0].fields["guid"], "9f1c4d0ab2e34f6");+ assert_eq!(recs[0].fields["importer"], "MonoImporter");+ assert_eq!(recs[0].fields["asset_name"], "Player.cs");+ assert_eq!(recs[0].locator, "meta");+ }++ #[test]+ fn a_file_with_only_preamble_is_junk() {+ let (stats, recs) = run("%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n", None);+ assert_eq!(stats.records, 0);+ assert!(stats.junk >= 1);+ assert!(recs.is_empty());+ }+}diff --git a/engine/crates/xerj-autoindex/src/extract/yaml_x.rs b/engine/crates/xerj-autoindex/src/extract/yaml_x.rsindex 0b17914d0..6b298d57e 100644--- a/engine/crates/xerj-autoindex/src/extract/yaml_x.rs+++ b/engine/crates/xerj-autoindex/src/extract/yaml_x.rs@@ -1,7 +1,7 @@//! YAML — multi-document streams; each doc becomes a record (a top-level//! sequence of mappings becomes per-element records). 16MB file cap.-use super::{flatten_object, ExtractStats, FieldOrigin, RawRecord, Sink};+use super::{flatten_object, yaml_to_json, ExtractStats, FieldOrigin, RawRecord, Sink};use anyhow::Result;use serde_json::{Map, Value};use std::path::Path;@@ -83,43 +83,6 @@ pub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {use serde::Deserialize;-fn yaml_to_json(v: serde_yaml::Value) -> Value {- match v {- serde_yaml::Value::Null => Value::Null,- serde_yaml::Value::Bool(b) => Value::Bool(b),- serde_yaml::Value::Number(n) => {- if let Some(i) = n.as_i64() {- Value::Number(i.into())- } else if let Some(u) = n.as_u64() {- Value::Number(u.into())- } else {- serde_json::Number::from_f64(n.as_f64().unwrap_or(0.0))- .map(Value::Number)- .unwrap_or(Value::Null)- }- }- serde_yaml::Value::String(s) => Value::String(s),- serde_yaml::Value::Sequence(seq) => {- Value::Array(seq.into_iter().map(yaml_to_json).collect())- }- serde_yaml::Value::Mapping(m) => {- let mut out = Map::new();- for (k, vv) in m {- let key = match k {- serde_yaml::Value::String(s) => s,- other => serde_yaml::to_string(&other)- .unwrap_or_else(|_| "key".into())- .trim()- .to_string(),- };- out.insert(key, yaml_to_json(vv));- }- Value::Object(out)- }- serde_yaml::Value::Tagged(t) => yaml_to_json(t.value),- }-}-#[cfg(test)]mod tests {use super::*;diff --git a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rsindex 2ea5c7c9e..94eb3e0e4 100644--- a/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs@@ -133,7 +133,12 @@ impl MockEndpoint {let server_state = Arc::clone(&state);let join = thread::spawn(move || loop {match listener.accept() {- Ok((stream, _)) => handle(stream, &server_state),+ Ok((stream, _)) => {+ // BSD/macOS: accepted sockets inherit the listener's+ // O_NONBLOCK; the handler does blocking reads.+ stream.set_nonblocking(false).unwrap();+ handle(stream, &server_state)+ }Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {if server_state.lock()@@ -516,6 +521,7 @@ fn cfg(root: &Path, state_dir: &Path, url: &str) -> IndexCfg {state_dir: Some(state_dir.to_owned()),fresh: false,follow_symlinks: false,+ stub_globs: Vec::new(),ignore: crate::ignore_rules::IgnoreOptions::default(),max_file_gb: 1,sample: 50,@@ -2901,6 +2907,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":},100,1,+ false,);assert!(scan.pdf_spool.is_none());assert_eq!(scan.pdf_spool_fallbacks.len(), 1);@@ -2988,6 +2995,7 @@ printf '%s' '{"schema":1,"extractor":"xerj-autoindex/__XERJ_VERSION__","parser":},100,1,+ false,);assert!(@@ -3066,6 +3074,7 @@ fn verified_but_junk_pdf_spool_is_created_then_discarded_not_eligible() {},100,1,+ false,);assert!(scan.junk.is_some());assert!(scan.pdf_spool.is_some());diff --git a/engine/crates/xerj-autoindex/src/ignore_rules.rs b/engine/crates/xerj-autoindex/src/ignore_rules.rsindex 9e4bf7591..95a561f62 100644--- a/engine/crates/xerj-autoindex/src/ignore_rules.rs+++ b/engine/crates/xerj-autoindex/src/ignore_rules.rs@@ -668,6 +668,14 @@ impl IgnoreStack {}}+ /// The marker-gated generated-dir prune (`walk::MARKER_GENERATED_DIRS`)+ /// is also decided by the walker — the verdict needs the SIBLING marker+ /// file, which the per-directory matcher stack cannot see — and reported+ /// through the same accounting.+ pub fn record_marker_dir(&mut self, path: &Path, label: &str) {+ self.record_dir(path, label);+ }+fn record_file(&mut self, label: &str) {self.report.files_skipped += 1;self.reportdiff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rsindex 72b2f4374..39a801e06 100644--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs@@ -52,7 +52,12 @@ impl HttpEndpoint {let server_state = Arc::clone(&state);let join = thread::spawn(move || loop {match listener.accept() {- Ok((stream, _)) => handle_http(stream, &server_state),+ Ok((stream, _)) => {+ // BSD/macOS: accepted sockets inherit the listener's+ // O_NONBLOCK; the handler does blocking reads.+ stream.set_nonblocking(false).unwrap();+ handle_http(stream, &server_state)+ }Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {if server_state.lock().unwrap().stop {break;@@ -386,6 +391,7 @@ fn search_http(path: &str, body: &[u8], state: &Arc<Mutex<HttpState>>) -> Valuefn cfg(root: &Path, state_dir: &Path, url: &str, semantic: bool) -> IndexCfg {IndexCfg {root: root.to_owned(),+ stub_globs: Vec::new(),url: url.to_owned(),api_key: None,api_key_file: None,diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex cef4e71f6..785ca9a39 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -241,6 +241,7 @@ fn project_reconcile_plan(inventory.files.len() as u64,inventory.files.iter().map(|file| file.size).sum(),);+ let stub_matcher = StubMatcher::compile(&cfg.stub_globs).expect("validated at startup");let scans: Vec<FileScan> = crate::pool::install(|| {use rayon::prelude::*;inventory@@ -256,6 +257,7 @@ fn project_reconcile_plan(&ctx,cfg.sample,cfg.max_file_gb,+ stub_matcher.matches(&file.rel),)}).collect()@@ -632,7 +634,7 @@ pub fn run_cli() -> i32 {cli::print_help();return 0;}- Cmd::Index(cfg) => run_index(cfg),+ Cmd::Index(cfg) => run_index(*cfg),Cmd::Map(cfg) => run_map(cfg),Cmd::Status(cfg) => run_status(cfg),};@@ -660,6 +662,19 @@ const GB: u64 = 1 << 30;const REFUSAL_LIST_CAP: usize = 10;const SAMPLE_LIMIT_BYTES: u64 = 4 << 20;const SQLDUMP_SAMPLE_LIMIT: u64 = 64 << 20;+/// Sampling byte cap for Unity assets.+///+/// Unity YAML is a GROUPED family: each `unity_class` is its own cluster, and+/// a class's first document can sit anywhere in the file — `extract/unity.rs`+/// notes real scenes exceed 200 MB. A class whose first document starts past+/// the cap is never sampled, so it gets no entry in `fa.assignments`, and+/// phase B then has nowhere to route its records. Under the old 4 MiB cap+/// that silently became `file_junk`. This cap is set past the size of the+/// scenes the format actually produces so that outcome needs a genuinely+/// pathological file, and when it does happen phase B now names the+/// unsampled group and its record count in `extra_junk` instead of adding+/// them to an anonymous counter.+const UNITY_SAMPLE_LIMIT: u64 = 512 << 20;#[cfg(test)]static REPLACEMENT_FAILPOINT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);@@ -778,6 +793,186 @@ fn section_label(locator: &str) -> Option<String> {(digits(page) && digits(sec)).then(|| format!("page {page} section {sec}"))}+// ─── --stub glob matcher ──────────────────────────────────────────────────++/// Longest accepted `--stub` glob. Far beyond any pattern a person types,+/// and far below the length at which the compiled regex hits its size limit.+const MAX_STUB_GLOB_LEN: usize = 4096;++/// Compiled `--stub <glob>` patterns. A matching file is indexed as ONE+/// name-card record (`Family::Stub`) and its contents are never opened —+/// the owner's way of saying "this data blob should be referenceable but+/// not parsed" without the engine hardcoding per-corpus rules.+///+/// Glob semantics (gitignore-flavored): `**` crosses `/`, `*` and `?` do+/// not; a pattern without `/` matches against the file NAME anywhere in the+/// tree, a pattern with `/` matches the full root-relative path.+pub struct StubMatcher {+ by_name: Vec<regex::Regex>,+ by_path: Vec<regex::Regex>,+}++impl StubMatcher {+ pub fn compile(globs: &[String]) -> Result<Self> {+ let mut by_name = Vec::new();+ let mut by_path = Vec::new();+ for g in globs {+ // `glob_to_regex` escapes every metacharacter, so no glob can+ // produce a SYNTACTICALLY invalid regex — the only reachable+ // failure is the compiled-size limit, which `?` (→ `[^/]`) and+ // `**` (→ `.*`) reach at ~10^5 characters. Caught here by length+ // so the message names the flag and the cause instead of+ // surfacing a regex-internal "compiled regex exceeds size limit".+ if g.len() > MAX_STUB_GLOB_LEN {+ anyhow::bail!(+ "--stub {}…: pattern is {} characters (limit {MAX_STUB_GLOB_LEN})",+ g.chars().take(40).collect::<String>(),+ g.len()+ );+ }+ let re = regex::Regex::new(&glob_to_regex(g))+ .with_context(|| format!("--stub {g}: invalid pattern"))?;+ if g.contains('/') {+ by_path.push(re);+ } else {+ by_name.push(re);+ }+ }+ Ok(Self { by_name, by_path })+ }++ pub fn is_empty(&self) -> bool {+ self.by_name.is_empty() && self.by_path.is_empty()+ }++ /// `rel` is the root-relative path with forward slashes.+ pub fn matches(&self, rel: &str) -> bool {+ if self.by_path.iter().any(|re| re.is_match(rel)) {+ return true;+ }+ if self.by_name.is_empty() {+ return false;+ }+ let name = rel.rsplit('/').next().unwrap_or(rel);+ self.by_name.iter().any(|re| re.is_match(name))+ }+}++fn glob_to_regex(glob: &str) -> String {+ let mut out = String::from("^");+ let mut chars = glob.chars().peekable();+ while let Some(c) = chars.next() {+ match c {+ '*' => {+ if chars.peek() == Some(&'*') {+ chars.next();+ // `**/` also swallows its slash so `**/x` matches a+ // top-level `x`.+ if chars.peek() == Some(&'/') {+ chars.next();+ out.push_str("(?:.*/)?");+ } else {+ out.push_str(".*");+ }+ } else {+ out.push_str("[^/]*");+ }+ }+ '?' => out.push_str("[^/]"),+ other => out.push_str(®ex::escape(&other.to_string())),+ }+ }+ out.push('$');+ out+}++/// The synthetic sniff result for a `--stub`-designated file.+///+/// `logical_path` is the file as the CORPUS names it, which under durable+/// preparation is not the path the bytes live at (`blobs/00000000`). A stub's+/// only output is a name card, so taking the name from the content path would+/// title every stub after a blob ordinal — the #294 failure class that+/// `Sniffed::logical_name` exists to prevent.+fn stub_sniffed(logical_path: &Path) -> Sniffed {+ Sniffed {+ family: Family::Stub,+ gzip: false,+ binary_kind: None,+ csv: None,+ encoding: "utf-8",+ logical_name: logical_path.file_name().map(std::path::PathBuf::from),+ }+}++#[cfg(test)]+mod stub_matcher_tests {+ use super::StubMatcher;++ fn m(globs: &[&str]) -> StubMatcher {+ StubMatcher::compile(&globs.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()+ }++ #[test]+ fn a_bare_pattern_matches_file_names_anywhere() {+ let s = m(&["*.csv"]);+ assert!(s.matches("unity/Assets/Face/f_roommate_004.csv"));+ assert!(s.matches("top.csv"));+ assert!(!s.matches("unity/Assets/notes.csv.md"));+ }++ #[test]+ fn a_path_pattern_matches_the_root_relative_path() {+ let s = m(&["unity/**/*.csv"]);+ assert!(s.matches("unity/Assets/Face/f_roommate_004.csv"));+ assert!(s.matches("unity/top.csv"), "**/ also matches zero dirs");+ assert!(!s.matches("backend/data/users.csv"), "scoped to unity/");+ }++ #[test]+ fn single_star_does_not_cross_directories() {+ let s = m(&["unity/*.csv"]);+ assert!(s.matches("unity/top.csv"));+ assert!(!s.matches("unity/Assets/deep.csv"));+ }++ #[test]+ fn regex_metacharacters_in_patterns_are_literal() {+ let s = m(&["data(v1).csv"]);+ assert!(s.matches("x/data(v1).csv"));+ assert!(!s.matches("x/dataXv1Y.csv"));+ }++ #[test]+ fn an_invalid_pattern_fails_loudly_at_startup() {+ // The old body asserted only that a VALID pattern compiles, so it+ // never tested its own name and would have passed against a `compile`+ // that could not fail at all.+ let msg = match StubMatcher::compile(&["?".repeat(super::MAX_STUB_GLOB_LEN + 1)]) {+ Ok(_) => panic!("an over-long pattern must be refused"),+ Err(e) => e.to_string(),+ };+ assert!(msg.contains("--stub"), "message must name the flag: {msg}");+ assert!(+ msg.contains(&super::MAX_STUB_GLOB_LEN.to_string()),+ "message must state the limit: {msg}"+ );+ }++ /// Why the error above is the ONLY reachable one: `glob_to_regex`+ /// escapes every metacharacter, so no amount of regex syntax in a glob+ /// can produce an invalid pattern. Anything asserting otherwise is+ /// asserting something the code makes impossible.+ #[test]+ fn regex_syntax_in_a_glob_is_never_a_compile_error() {+ for g in ["[", "(", "\\", "*?[a-", "a{2,", "(?P<x>", "+", "|", "^$"] {+ assert!(+ StubMatcher::compile(&[g.to_string()]).is_ok(),+ "{g} must compile: metacharacters are escaped, not interpreted"+ );+ }+ }+}+// ─── Phase A: per-file scan (sniff + bounded sampling) ───────────────────struct FileScan {@@ -842,6 +1037,7 @@ fn scan_file(ctx: &PhaseAContext<'_>,sample: usize,max_file_gb: u64,+ stub: bool,) -> FileScan {let state_dir = ctx.state_dir;let pdf_spool_budget = ctx.budget;@@ -852,11 +1048,15 @@ fn scan_file(pdf_spool: None,pdf_spool_fallbacks: Vec::new(),};- let sn = match sniff::sniff(path) {- Ok(s) => s,- Err(e) => {- out.junk = Some(("junk".into(), format!("unreadable: {e}")));- return out;+ let sn = if stub {+ stub_sniffed(path)+ } else {+ match sniff::sniff(path) {+ Ok(s) => s,+ Err(e) => {+ out.junk = Some(("junk".into(), format!("unreadable: {e}")));+ return out;+ }}};if sn.family == Family::Binary {@@ -888,6 +1088,7 @@ fn scan_file(}let limit = match sn.family {Family::SqlDump => Some(SQLDUMP_SAMPLE_LIMIT),+ Family::UnityYaml => Some(UNITY_SAMPLE_LIMIT),Family::Jsonl | Family::Logs | Family::Csv | Family::TxtLines => Some(SAMPLE_LIMIT_BYTES),Family::Sqlite => Some(1), // signals per-table row cap inside the extractor_ => None, // whole-file extractors cap themselves@@ -898,7 +1099,14 @@ fn scan_file(std::collections::HashSet<String>,);let mut groups: HashMap<Option<String>, GroupAcc> = HashMap::new();- let grouped_family = matches!(sn.family, Family::SqlDump | Family::Sqlite);+ // Grouped families keep reading past the per-group sample size: their+ // groups (SQL tables, Unity classes) appear all through the file, and+ // stopping at the first N records would leave later groups unsampled and+ // untyped.+ let grouped_family = matches!(+ sn.family,+ Family::SqlDump | Family::Sqlite | Family::UnityYaml+ );let mut sink = |rec: extract::RawRecord| -> bool {let entry = groups.entry(rec.group.clone()).or_default();if (entry.1 as usize) < sample {@@ -1044,7 +1252,7 @@ mod clustering_key_tests {progress: &progress,meter: &meter,};- scan_file(&path, size, "d0", &ctx, 500, 2)+ scan_file(&path, size, "d0", &ctx, 500, 2, false)}/// The #178 mechanism, from the extractor to the clustering key: a source@@ -1123,9 +1331,10 @@ mod clustering_key_tests {mod phase_a_grouping_tests {use super::*;- fn cfg_for(root: &Path) -> IndexCfg {+ pub(super) fn cfg_for(root: &Path) -> IndexCfg {IndexCfg {root: root.to_path_buf(),+ stub_globs: Vec::new(),url: "http://unused.invalid".into(),api_key: None,api_key_file: None,@@ -1442,13 +1651,24 @@ fn build_phase_a(// file a scan-pool thread is genuinely sitting on (#241). Retaining a PDF// artifact happens inside that same guard, so a file whose extraction is// spooled is counted exactly like a plainly parsed one.+ // Patterns were validated (loudly) at run start; a failure here would be+ // a programming error, not user input.+ let stub_matcher = StubMatcher::compile(&cfg.stub_globs).expect("validated at startup");let scans: Vec<FileScan> = crate::pool::install(|| {files.par_iter().zip(digests.par_iter()).map(|(f, digest)| {let _in_flight = pr.file(&f.rel, f.size);- scan_file(&f.path, f.size, digest, ctx, cfg.sample, cfg.max_file_gb)+ scan_file(+ &f.path,+ f.size,+ digest,+ ctx,+ cfg.sample,+ cfg.max_file_gb,+ stub_matcher.matches(&f.rel),+ )}).collect()});@@ -1556,8 +1776,27 @@ fn build_phase_a(let mut datasets = Vec::new();for c in &clusters {- let specs =+ let mut specs =infer::infer_fields_with_policy(&c.fields, c.records, cfg.no_semantic, c.is_docs);+ // Unity script-link enrichment fields are stamped by the phase-B+ // pipeline (not the extractor), so inference never sees them —+ // register them here or they would be dynamic-mapped coarsely.+ //+ // Registered for EVERY UnityYaml cluster, not only those whose sample+ // happened to contain a `script_guid`. Phase B stamps these whenever a+ // record carries a resolvable guid, and phase A reads a bounded window+ // of the file — so gating the mapping on the sample meant a cluster+ // whose sampled window held no `m_Script` got these two fields+ // dynamic-mapped at index time instead, feeding the field-budget+ // overshoot in #312. Two keyword specs per Unity cluster is a fixed,+ // predictable cost; a dynamic mapping is not.+ if c.family == Family::UnityYaml {+ specs.push(pipeline_keyword_spec("script_path"));+ specs.push(pipeline_keyword_spec("script_class"));+ }+ if c.family == Family::UnityMeta {+ specs.push(pipeline_keyword_spec("asset_path"));+ }let time_field = infer::elect_time_field(&specs);let semantic_field = specs.iter()@@ -1616,6 +1855,192 @@ pub const PROVENANCE_FIELDS: &[&str] = &["ax_format",];+/// Spec for a field the PIPELINE derives at index time (Unity script-link+/// enrichment): typed keyword in the explicit mapping, zeroed sampling stats+/// because phase-A inference never observes it.+fn pipeline_keyword_spec(name: &str) -> infer::FieldSpec {+ infer::FieldSpec {+ name: name.into(),+ es_type: "keyword".into(),+ date_enc: None,+ semantic: None,+ cardinality_est: 0,+ cardinality_overflow: false,+ null_ratio: 0.0,+ avg_len: 0.0,+ coverage: 0.0,+ examples: Vec::new(),+ notes: vec!["pipeline-derived: resolved from the .meta guid map at index time".into()],+ date_min: None,+ date_max: None,+ date_evidence: Vec::new(),+ }+}++/// Outcome of building the Unity script-link map, including what did NOT+/// resolve. The failures are the whole point: `script_path`/`script_class`+/// are absent both when a guid is unreadable and when nothing references it,+/// and those two look identical in the index.+#[derive(Debug, Default)]+struct UnityGuidMap {+ /// `.meta` guid → root-relative asset path.+ map: std::collections::HashMap<String, String>,+ /// `.meta` files that could not be read or parsed at all.+ unreadable: Vec<(String, String)>,+ /// `.meta` files that parsed but carried no `guid:` key.+ no_guid: Vec<String>,+}++/// Unity script-link map: `.meta` guid → root-relative asset path.+///+/// Runs on `crate::pool` and under the progress meter. A `.meta` is tiny, but+/// a real Unity project has 10k-500k of them, and this is on the critical+/// path of EVERY run — including a resumed no-op incremental, which otherwise+/// has no work to do at all. Doing that serially and unmetered is the+/// unattributed-stretch pattern of #241: the process sits silent for minutes+/// with the bar parked.+fn build_unity_guid_map(files: &[walk::FileEntry], plan: &Plan, pr: &Progress) -> UnityGuidMap {+ use rayon::prelude::*;++ let by_rel: HashMap<&str, &Path> = files+ .iter()+ .map(|f| (f.rel.as_str(), f.path.as_path()))+ .collect();+ let metas: Vec<&FileAssignment> = plan+ .files+ .values()+ .filter(|fa| fa.family == "unity-meta")+ .collect();+ if metas.is_empty() {+ return UnityGuidMap::default();+ }+ pr.phase("unity-guids", metas.len() as u64, 0);++ #[allow(clippy::type_complexity)]+ let parts: Vec<(+ Option<(String, String)>,+ Option<(String, String)>,+ Option<String>,+ )> = crate::pool::install(|| {+ metas+ .par_iter()+ .map(|fa| {+ let _in_flight = pr.file(&fa.rel, 0);+ let Some(asset_rel) = fa.rel.strip_suffix(".meta") else {+ return (None, None, None);+ };+ let Some(path) = by_rel.get(fa.rel.as_str()) else {+ return (None, None, None);+ };+ let mut guid: Option<String> = None;+ // The Result is NOT discarded: an unreadable `.meta` is+ // how the headline "which scenes use this script?" query+ // silently returns nothing.+ match extract::unity::extract_meta(path, fa.gzip, &mut |rec| {+ guid = rec+ .fields+ .get("guid")+ .and_then(Value::as_str)+ .map(str::to_string);+ false+ }) {+ Ok(_) => match guid {+ Some(g) => (Some((g, asset_rel.to_string())), None, None),+ None => (None, None, Some(fa.rel.clone())),+ },+ Err(e) => (None, Some((fa.rel.clone(), e.to_string())), None),+ }+ })+ .collect()+ });++ let mut out = UnityGuidMap::default();+ for (hit, bad, missing) in parts {+ if let Some((g, rel)) = hit {+ out.map.insert(g, rel);+ }+ if let Some(b) = bad {+ out.unreadable.push(b);+ }+ if let Some(m) = missing {+ out.no_guid.push(m);+ }+ }+ out.unreadable.sort();+ out.no_guid.sort();+ out+}++/// Say out loud what the guid map could not resolve. Without this a broken+/// `.meta` produces no counter, no warning and no report line, and the+/// feature's headline query returns empty in a way that is indistinguishable+/// from a script nothing references.+fn report_unity_guid_map(g: &UnityGuidMap, pr: &Progress) {+ if !g.unreadable.is_empty() {+ pr.note(&format!(+ "unity: {} .meta sidecar(s) could not be read — scripts they name \+ will have no script_path/script_class: {}",+ g.unreadable.len(),+ g.unreadable+ .iter()+ .take(REFUSAL_LIST_CAP)+ .map(|(rel, e)| format!("{rel} ({e})"))+ .collect::<Vec<_>>()+ .join(", ")+ ));+ }+ if !g.no_guid.is_empty() {+ pr.note(&format!(+ "unity: {} .meta sidecar(s) carry no guid: {}",+ g.no_guid.len(),+ g.no_guid+ .iter()+ .take(REFUSAL_LIST_CAP)+ .cloned()+ .collect::<Vec<_>>()+ .join(", ")+ ));+ }+}++/// Stamp pipeline-derived Unity fields onto a record. MonoBehaviour records+/// gain `script_path`/`script_class` when their `script_guid` resolves; meta+/// records gain the root-relative `asset_path` their guid names. Denormalized+/// for one-query answers — `script_guid` remains the authoritative join.+/// Returns the `script_guid` that was present but did NOT resolve, if any.+/// A caller that throws this away recreates the silent-failure bug: the+/// record then ships without `script_path`/`script_class` and the index+/// cannot distinguish "guid is broken" from "nothing references this script".+#[must_use]+fn enrich_unity_fields(+ family: Family,+ fields: &mut Map<String, Value>,+ guid_map: &std::collections::HashMap<String, String>,+ rel: &str,+) -> Option<String> {+ match family {+ Family::UnityYaml => {+ let g = fields.get("script_guid").and_then(Value::as_str)?;+ let Some(p) = guid_map.get(g) else {+ return Some(g.to_string());+ };+ let p = p.clone();+ fields.insert("script_path".into(), Value::String(p.clone()));+ if let Some(stem) = Path::new(&p).file_stem().and_then(|s| s.to_str()) {+ fields.insert("script_class".into(), Value::String(stem.to_string()));+ }+ None+ }+ Family::UnityMeta => {+ if let Some(asset_rel) = rel.strip_suffix(".meta") {+ fields.insert("asset_path".into(), Value::String(asset_rel.to_string()));+ }+ None+ }+ _ => None,+ }+}+fn build_mapping(specs: &[infer::FieldSpec]) -> Value {let mut props = Map::new();for s in specs {@@ -2392,6 +2817,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {.with_bulk_concurrency(cfg.workers, pr.enabled());es.ping()?;+ let stub_matcher = StubMatcher::compile(&cfg.stub_globs)?;let root_str = cfg.root.canonicalize()@@ -3381,6 +3807,9 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}replacement_failpoint(1).context("after durable replacement plan")?;+ let unity_guid_map = build_unity_guid_map(&files, &plan, &pr);+ report_unity_guid_map(&unity_guid_map, &pr);+// ── Phase B: full-stream extraction + bulk indexing ─────────────────struct DsRt {index: String,@@ -3732,7 +4161,12 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let fa = plan.files.get(key).unwrap();let asg: HashMap<Option<String>, String> =fa.assignments.iter().cloned().collect();- let sn = match sniff::sniff(&f.path) {+ let sn = if stub_matcher.matches(&f.rel) {+ Ok(stub_sniffed(Path::new(&f.rel)))+ } else {+ sniff::sniff(&f.path)+ };+ let sn = match sn {Ok(s) => s,Err(e) => {extra_junk.lock().unwrap().push(JunkFile {@@ -3748,6 +4182,18 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {};let mut file_records = 0u64;let mut file_junk = 0u64;+ // Groups phase B saw that phase A never sampled, so they+ // have no dataset to route to. Silently counting these as+ // junk is how a whole Unity class (or SQL table) can+ // vanish from a run with nothing in the report to say so.+ let mut unrouted_groups: std::collections::BTreeMap<String, u64> =+ std::collections::BTreeMap::new();+ // `script_guid`s this file referenced that no `.meta` in+ // the tree defines. These are exactly the records that+ // ship without script_path/script_class, which is what+ // makes the headline query come back empty.+ let mut unresolved_script_guids: std::collections::BTreeMap<String, u64> =+ std::collections::BTreeMap::new();let mut file_dropped_by_dataset: HashMap<String, u64> = HashMap::new();let mut send_err: Option<String> = None;// Edges this file teaches — buffered apart from the node@@ -3842,6 +4288,11 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let mut sink = |rec: extract::RawRecord| -> bool {let Some(slug) = asg.get(&rec.group).or_else(|| asg.get(&None)) else {file_junk += 1;+ *unrouted_groups+ .entry(+ rec.group.clone().unwrap_or_else(|| "(ungrouped)".into()),+ )+ .or_insert(0) += 1;return true;};let Some(rt) = ds_rt.get(slug) else {@@ -3849,6 +4300,18 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {return true;};let mut fields = rec.fields;+ // BEFORE coercion, not after: these are ordinary+ // record fields once stamped, and a field that+ // skips `coerce_record` is a field the dataset+ // plan never validated.+ if let Some(unresolved) = enrich_unity_fields(+ sn.family,+ &mut fields,+ &unity_guid_map.map,+ &f.rel,+ ) {+ *unresolved_script_guids.entry(unresolved).or_insert(0u64) += 1;+ }let dropped = coerce::coerce_record(&mut fields, &rt.plan);if dropped > 0 {let durable =@@ -3986,6 +4449,48 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {});}}+ if !unresolved_script_guids.is_empty() {+ let total: u64 = unresolved_script_guids.values().sum();+ pr.note(&format!(+ "unity: {}: {total} MonoBehaviour record(s) reference {} \+ script guid(s) no .meta defines — they ship without \+ script_path/script_class: {}",+ f.rel,+ unresolved_script_guids.len(),+ unresolved_script_guids+ .keys()+ .take(REFUSAL_LIST_CAP)+ .cloned()+ .collect::<Vec<_>>()+ .join(", ")+ ));+ }+ if !unrouted_groups.is_empty() {+ let total: u64 = unrouted_groups.values().sum();+ let named = unrouted_groups+ .iter()+ .take(REFUSAL_LIST_CAP)+ .map(|(g, n)| format!("{g} ({n})"))+ .collect::<Vec<_>>()+ .join(", ");+ let more = unrouted_groups.len().saturating_sub(REFUSAL_LIST_CAP);+ let suffix = if more > 0 {+ format!(" and {more} more")+ } else {+ String::new()+ };+ extra_junk.lock().unwrap().push(JunkFile {+ file_key: key.clone(),+ rel: f.rel.clone(),+ format: format_str(Some(&sn)),+ status: "junk".into(),+ reason: format!(+ "{total} record(s) dropped: group(s) never sampled in \+ phase A, so they have no dataset — {named}{suffix}"+ ),+ bytes: f.size,+ });+ }}// Raw-source href pass: the HTML extractor strips markup// before sectioning, so `<a href>` evidence exists only in@@ -6141,3 +6646,254 @@ mod code_coverage_tests {mod failure_resume_http_tests;#[cfg(test)]mod incremental_reconcile_http_tests;++/// The Unity PIPELINE half — `build_unity_guid_map` + `enrich_unity_fields`+/// + the plan's field registration, driven through the real phase-A planner.+///+/// The PR that introduced Unity support tested `extract::unity::*` thoroughly+/// and this half not at all, which is why the sample-conditional mapping+/// registration survived review: no unit test of an extractor can see a bug+/// whose cause is what phase A sampled.+#[cfg(test)]+mod unity_pipeline_tests {+ use super::*;++ const GUID: &str = "abc123def4560000";++ /// A scene whose MonoBehaviour group's FIRST document has no `m_Script`+ /// and whose SECOND one does. With `sample: 1`, phase A therefore never+ /// sees `script_guid` — but phase B still stamps `script_path` from the+ /// second record. That gap is the bug.+ fn scene_with_late_script_ref() -> String {+ format!(+ "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n\+ --- !u!1 &1\nGameObject:\n m_Name: Player\n\+ --- !u!114 &2\nMonoBehaviour:\n m_Name: NoScriptYet\n speed: 1\n\+ --- !u!114 &3\nMonoBehaviour:\n m_Name: HasScript\n \+ m_Script: {{fileID: 11500000, guid: {GUID}, type: 3}}\n"+ )+ }++ fn write_project(dir: &Path) {+ std::fs::create_dir_all(dir.join("Assets/Scripts")).unwrap();+ std::fs::create_dir_all(dir.join("Assets/Scenes")).unwrap();+ std::fs::write(+ dir.join("Assets/Scripts/PlayerController.cs.meta"),+ format!("fileFormatVersion: 2\nguid: {GUID}\nMonoImporter:\n serializedVersion: 2\n"),+ )+ .unwrap();+ std::fs::write(+ dir.join("Assets/Scenes/Main.unity"),+ scene_with_late_script_ref(),+ )+ .unwrap();+ }++ fn plan_for(root: &Path, sample: usize) -> (Plan, Vec<walk::FileEntry>) {+ let files = walk::walk(root, false).unwrap();+ let keys: Vec<String> = files+ .iter()+ .map(|f| ids::file_key(&f.path, f.size).unwrap())+ .collect();+ let digests: Vec<String> = (0..files.len()).map(|i| format!("d{i}")).collect();+ 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,+ };+ let mut cfg = super::phase_a_grouping_tests::cfg_for(root);+ cfg.sample = sample;+ let plan = build_phase_a(root, &files, &keys, &digests, Vec::new(), &ctx, &cfg).plan;+ (plan, files)+ }++ #[test]+ fn the_guid_map_resolves_a_meta_sidecar_to_its_asset_path() {+ let dir = tempfile::tempdir().unwrap();+ write_project(dir.path());+ let (plan, files) = plan_for(dir.path(), 500);+ let g = build_unity_guid_map(&files, &plan, &Progress::silent());+ assert_eq!(+ g.map.get(GUID).map(String::as_str),+ Some("Assets/Scripts/PlayerController.cs"),+ "guid must resolve to the asset the .meta sits beside"+ );+ assert!(g.unreadable.is_empty(), "{:?}", g.unreadable);+ assert!(g.no_guid.is_empty(), "{:?}", g.no_guid);+ }++ /// Blocker: `script_path`/`script_class` were registered in the explicit+ /// mapping only when the SAMPLE happened to contain `script_guid`. Phase A+ /// reads a bounded window, so a cluster whose window held no `m_Script`+ /// got them dynamic-mapped at index time instead — the field-budget+ /// overshoot of #312.+ #[test]+ fn script_link_fields_are_mapped_even_when_the_sample_never_saw_a_script_guid() {+ let dir = tempfile::tempdir().unwrap();+ write_project(dir.path());++ let (plan, _) = plan_for(dir.path(), 1);+ let mb = plan+ .datasets+ .iter()+ .find(|d| d.group.as_deref() == Some("MonoBehaviour"))+ .expect("a MonoBehaviour cluster must exist");+ assert!(+ !mb.specs.iter().any(|s| s.name == "script_guid"),+ "precondition: with sample=1 the sampled window must NOT contain \+ script_guid, or this test proves nothing"+ );+ for want in ["script_path", "script_class"] {+ assert!(+ mb.specs.iter().any(|s| s.name == want),+ "{want} must be in the explicit mapping regardless of what the \+ sample saw; specs = {:?}",+ mb.specs.iter().map(|s| &s.name).collect::<Vec<_>>()+ );+ }+ }++ /// End to end over the two halves: the guid map built from `.meta` files+ /// resolves the `script_guid` an extractor emitted, and the enrichment+ /// stamps both denormalized fields. This is the feature's headline query+ /// ("which scenes use this script?") reduced to its mechanism.+ #[test]+ fn enrichment_resolves_a_script_guid_to_path_and_class() {+ let dir = tempfile::tempdir().unwrap();+ write_project(dir.path());+ let (plan, files) = plan_for(dir.path(), 500);+ let g = build_unity_guid_map(&files, &plan, &Progress::silent());++ let mut fields = Map::new();+ fields.insert("script_guid".into(), Value::String(GUID.into()));+ let unresolved = enrich_unity_fields(+ Family::UnityYaml,+ &mut fields,+ &g.map,+ "Assets/Scenes/Main.unity",+ );+ assert_eq!(unresolved, None, "a defined guid must resolve");+ assert_eq!(fields["script_path"], "Assets/Scripts/PlayerController.cs");+ assert_eq!(fields["script_class"], "PlayerController");+ }++ /// Blocker: an unresolvable `script_guid` produced no counter, no warning+ /// and no report line — the record shipped without `script_path`, and+ /// "no users" and "broken link" became the same answer.+ #[test]+ fn an_unresolvable_script_guid_is_reported_not_swallowed() {+ let mut fields = Map::new();+ fields.insert("script_guid".into(), Value::String("deadbeef".into()));+ let unresolved = enrich_unity_fields(+ Family::UnityYaml,+ &mut fields,+ &std::collections::HashMap::new(),+ "Assets/Scenes/Main.unity",+ );+ assert_eq!(+ unresolved.as_deref(),+ Some("deadbeef"),+ "the caller must be told which guid failed"+ );+ assert!(!fields.contains_key("script_path"));+ }++ /// The enrichment was moved to run BEFORE `coerce_record` so its fields+ /// are validated like every other field instead of bypassing coercion.+ /// That only works if the plan actually carries them — this drives the+ /// real `coerce::plan_from_specs` over the real planned specs and asserts+ /// both fields survive the round trip with their values intact.+ #[test]+ fn enriched_fields_survive_the_coercion_they_now_pass_through() {+ let dir = tempfile::tempdir().unwrap();+ write_project(dir.path());+ let (plan, files) = plan_for(dir.path(), 500);+ let g = build_unity_guid_map(&files, &plan, &Progress::silent());++ let mb = plan+ .datasets+ .iter()+ .find(|d| d.group.as_deref() == Some("MonoBehaviour"))+ .expect("a MonoBehaviour cluster must exist");+ let coerce_plan = coerce::plan_from_specs(&mb.specs);+ assert!(+ coerce_plan.contains_key("script_path"),+ "the coercion plan must know the field, else it would pass through \+ unvalidated exactly as it did before"+ );++ let mut fields = Map::new();+ fields.insert("script_guid".into(), Value::String(GUID.into()));+ let _ = enrich_unity_fields(+ Family::UnityYaml,+ &mut fields,+ &g.map,+ "Assets/Scenes/Main.unity",+ );+ let dropped = coerce::coerce_record(&mut fields, &coerce_plan);+ assert_eq!(dropped, 0, "nothing may be dropped: {fields:?}");+ assert_eq!(fields["script_path"], "Assets/Scripts/PlayerController.cs");+ assert_eq!(fields["script_class"], "PlayerController");+ }++ /// The failures the map collects have to reach a person. Counting them+ /// into a struct nobody prints is the same silence in a different place.+ #[test]+ fn the_guid_map_failures_are_printed_with_names_and_counts() {+ let (pr, buffer) = progress::Progress::capture(+ progress::Surface::Plain,+ std::time::Duration::from_secs(3600),+ );+ let g = UnityGuidMap {+ map: std::collections::HashMap::new(),+ unreadable: vec![("Assets/A.cs.meta".into(), "permission denied".into())],+ no_guid: vec!["Assets/B.cs.meta".into()],+ };+ report_unity_guid_map(&g, &pr);+ let text = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();+ assert!(text.contains("Assets/A.cs.meta"), "{text}");+ assert!(text.contains("permission denied"), "{text}");+ assert!(text.contains("Assets/B.cs.meta"), "{text}");+ assert!(text.contains("no guid"), "{text}");++ // A healthy map must stay quiet — a warning on every clean run is a+ // warning nobody reads.+ let (pr2, buf2) = progress::Progress::capture(+ progress::Surface::Plain,+ std::time::Duration::from_secs(3600),+ );+ report_unity_guid_map(&UnityGuidMap::default(), &pr2);+ assert!(String::from_utf8(buf2.lock().unwrap().clone())+ .unwrap()+ .is_empty());+ }++ /// Blocker: `build_unity_guid_map` discarded `extract_meta`'s `Result`.+ /// An unparseable `.meta` therefore produced silence.+ #[test]+ fn a_meta_that_carries_no_guid_is_recorded() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(dir.path().join("Assets")).unwrap();+ // Sniffs as UnityMeta (first line is `fileFormatVersion:` and a line+ // starts `guid:`) but the value is a YAML integer, so `extract_meta`+ // recovers no guid STRING — the sidecar is real and still unusable.+ std::fs::write(+ dir.path().join("Assets/Broken.cs.meta"),+ "fileFormatVersion: 2\nguid: 12345\nMonoImporter:\n serializedVersion: 2\n",+ )+ .unwrap();+ let (plan, files) = plan_for(dir.path(), 500);+ let g = build_unity_guid_map(&files, &plan, &Progress::silent());+ assert!(g.map.is_empty(), "no guid should have resolved");+ assert_eq!(+ g.no_guid,+ vec!["Assets/Broken.cs.meta".to_string()],+ "the .meta with no usable guid must be named, not silently skipped"+ );+ }+}diff --git a/engine/crates/xerj-autoindex/src/order.rs b/engine/crates/xerj-autoindex/src/order.rsindex 4f6d77b34..19b537c90 100644--- a/engine/crates/xerj-autoindex/src/order.rs+++ b/engine/crates/xerj-autoindex/src/order.rs@@ -187,6 +187,20 @@ pub fn band(rel: &str, family: Family) -> Band {Family::Yaml | Family::Json | Family::Xml => Band::Config,Family::Csv | Family::Jsonl | Family::Sqlite | Family::SqlDump => Band::Data,Family::Logs | Family::TxtLines => Band::Bulk,+ // Unity assets are the project's own authored content — scenes,+ // prefabs and materials are to a Unity repo what source files are to+ // a Rust one, so they rank with source, not with bulk data.+ Family::UnityYaml => Band::SourceAndDocs,+ // `.meta` sidecars carry the guid join key and nothing a human reads;+ // they are plumbing for `UnityYaml`, so they rank as config.+ Family::UnityMeta => Band::Config,+ // A `.bvh` yields ONE metadata record for a file that is mostly a+ // numeric motion block — data, not documentation.+ Family::Bvh => Band::Data,+ // `--stub` files are opened for a name card only. The owner asked for+ // them to be referenceable, not read, so they must not displace real+ // content in the queue.+ Family::Stub => 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,@@ -201,9 +215,15 @@ pub fn band_from_family_str(rel: &str, family: &str) -> Band {return Band::Vendored;}match family {- "code" | "txt-prose" | "html" | "pdf" | "docx" => Band::SourceAndDocs,- "yaml" | "json" | "xml" => Band::Config,- "csv" | "jsonl" | "sqlite" | "sqldump" => Band::Data,+ "code" | "txt-prose" | "html" | "pdf" | "docx" | "unity" => Band::SourceAndDocs,+ "yaml" | "json" | "xml" | "unity-meta" => Band::Config,+ "csv" | "jsonl" | "sqlite" | "sqldump" | "bvh" => Band::Data,+ // Pre-existing drift, caught by+ // `estimate::tests::the_two_band_functions_agree_for_every_family`:+ // `band` ranks Binary `Vendored`, but the catch-all below ranked the+ // persisted string `Bulk`, so a resumed run ordered it differently+ // from the run that planned it.+ "binary" => Band::Vendored,_ => Band::Bulk,}}diff --git a/engine/crates/xerj-autoindex/src/sniff.rs b/engine/crates/xerj-autoindex/src/sniff.rsindex eca63f885..9dc937816 100644--- a/engine/crates/xerj-autoindex/src/sniff.rs+++ b/engine/crates/xerj-autoindex/src/sniff.rs@@ -24,6 +24,21 @@ pub enum Family {SqlDump,/// Source code — AST-parsed by the matching tree-sitter grammar.Code,+ /// Unity text-serialized asset (scene/prefab/.asset/.mat/.anim/…):+ /// a `%YAML` + `%TAG !u! tag:unity3d.com` multi-document stream.+ UnityYaml,+ /// Unity `.meta` sidecar: plain YAML opening with `fileFormatVersion:`+ /// and carrying the asset `guid` — the join key for everything Unity.+ UnityMeta,+ /// Biovision motion capture: a skeleton HIERARCHY header followed by a+ /// large numeric MOTION block. Indexed as ONE metadata record per file+ /// (joints, frame count, duration) — the motion numbers are never read.+ Bvh,+ /// User-designated existence-only file (`--stub <glob>`): ONE name-card+ /// record, contents never opened. For corpus-specific data blobs the+ /// owner wants referenceable but not parsed — never assigned by+ /// sniffing, only by the CLI flag.+ Stub,Binary,}@@ -44,6 +59,10 @@ impl Family {Family::Sqlite => "sqlite",Family::SqlDump => "sqldump",Family::Code => "code",+ Family::UnityYaml => "unity",+ Family::UnityMeta => "unity-meta",+ Family::Bvh => "bvh",+ Family::Stub => "stub",Family::Binary => "binary",}}@@ -158,6 +177,11 @@ fn sniff_bytes(s.binary_kind = Some("zip".into());return Ok(s);}+ // Compressed image/audio/model payloads routinely pass the NUL and+ // control-char heuristics below (windows-1252 decodes almost every byte+ // to something printable), and a multi-MB PSD misread as prose costs+ // ~100x its size in RAM through sectioning. Magic bytes are the reliable+ // signal.for (magic, kind) in [(&b"\x89PNG"[..], "png"),(&b"GIF8"[..], "gif"),@@ -165,6 +189,15 @@ fn sniff_bytes((&b"\x7fELF"[..], "elf"),(&b"BM"[..], "bmp"),(&b"\x00\x00\x01\x00"[..], "ico"),+ (&b"8BPS"[..], "psd"),+ (&b"II*\x00"[..], "tiff"),+ (&b"MM\x00*"[..], "tiff"),+ (&b"RIFF"[..], "riff"),+ (&b"OggS"[..], "ogg"),+ (&b"fLaC"[..], "flac"),+ (&b"ID3"[..], "mp3"),+ (&b"Kaydara FBX Binary"[..], "fbx"),+ (&b"\x76\x2f\x31\x01"[..], "exr"),] {if prefix.starts_with(magic) {let mut s = mk(Family::Binary);@@ -191,8 +224,63 @@ fn sniff_bytes(s.binary_kind = Some("unknown".into());return Ok(s);}+ // A prefix that only decoded via LOSSY windows-1252 and is majority+ // high-byte is pixel/float soup, not prose in a legacy encoding: real+ // windows-1252 text (accented European prose) runs well under 30%+ // non-ASCII, while raw image channels run ~50%. Without this, a large+ // TGA classified as txt-prose is amplified ~100x in RAM by sectioning.+ //+ // Gated on the windows-1252 fallback SPECIFICALLY, and skipped when the+ // bytes are plausibly legacy CJK: Shift-JIS/GBK/Big5/EUC-KR prose is+ // ~100% high-byte, so the unqualified test junked every legacy-encoded+ // CJK document in the corpus.+ let legacy_cjk = encoding == WINDOWS_1252_LOSSY && looks_like_legacy_cjk(prefix);+ if encoding == WINDOWS_1252_LOSSY && !legacy_cjk {+ let total = text.chars().count().max(1);+ let non_ascii = text.chars().filter(|c| !c.is_ascii()).count();+ if non_ascii * 10 > total * 3 {+ let mut s = mk(Family::Binary);+ s.binary_kind = Some("unknown".into());+ return Ok(s);+ }+ }- // 2b. Source code: a known code extension whose content is text. We only+ // 2b. Unity text serialization, detected by content (never extension):+ // scenes/prefabs/assets open with `%YAML` and declare the Unity tag+ // namespace; `.meta` sidecars open with `fileFormatVersion:` and carry a+ // `guid:`. Binary-serialized Unity assets fail both checks and fall+ // through to the binary/text heuristics as before.+ {+ let body = text.trim_start_matches('\u{feff}');+ if body.starts_with("%YAML") && body.contains("%TAG !u! tag:unity3d.com") {+ let mut s = mk(Family::UnityYaml);+ s.encoding = encoding;+ return Ok(s);+ }+ let first_line = body.lines().next().unwrap_or("");+ if first_line.starts_with("fileFormatVersion:")+ && body.lines().any(|l| l.starts_with("guid:"))+ {+ let mut s = mk(Family::UnityMeta);+ s.encoding = encoding;+ return Ok(s);+ }+ // BVH motion capture: `HIERARCHY` opener with a `ROOT <name>` next.+ // Without this the numeric MOTION block classified as txt-lines and+ // indexed millions of meaningless number rows.+ if first_line.trim() == "HIERARCHY"+ && body+ .lines()+ .nth(1)+ .is_some_and(|l| l.trim_start().starts_with("ROOT "))+ {+ let mut s = mk(Family::Bvh);+ s.encoding = encoding;+ return Ok(s);+ }+ }++ // 2c. Source code: a known code extension whose content is text. We only// reach here after the binary guards above, so a text `.py`/`.rs`/`.go`/…// routes to the tree-sitter AST extractor (crate::extract::code). Extension// is the right signal — code vs prose is not reliably content-sniffable.@@ -226,6 +314,96 @@ fn sniff_bytes(Ok(out)}+/// The label for the last-resort decode. Every byte maps to *something* in+/// windows-1252, so this never fails and therefore carries no evidence that+/// the bytes are text — the binary heuristics key off this exact string.+pub const WINDOWS_1252_LOSSY: &str = "windows-1252 (lossy)";++/// Scripts written without spaces between words ("scriptio continua").+///+/// Whitespace density cannot be used to tell prose from byte soup for these:+/// Chinese, Japanese, Korean, Thai, Lao, Khmer and Burmese prose runs at+/// essentially 0% intra-line whitespace, the same as random bytes. Their+/// presence is instead POSITIVE evidence of text — neither pixel channels nor+/// float dumps produce ideographs.+///+/// The script set is the one Lucene singles out for exactly this reason:+/// `CJKBigramFilter` (`lucene/analysis/common/src/java/org/apache/lucene/+/// analysis/cjk/CJKBigramFilter.java:52-118`, Apache-2.0) defines `HAN`,+/// `HIRAGANA`, `KATAKANA` and `HANGUL` flags because a whitespace tokenizer+/// cannot segment them, and its default constructor+/// (`CJKBigramFilter.java:119-126`) enables all four together. Thai, Lao,+/// Khmer and Myanmar are added here on the same principle — Lucene reaches+/// for `ICUTokenizer`/dictionary breaking for those rather than a bigram+/// filter, but the property this function tests (no inter-word spaces) is+/// identical. Adapted, not copied: Lucene is deciding how to TOKENIZE known+/// text; this only decides whether the bytes are text at all.+fn is_scriptio_continua(c: char) -> bool {+ matches!(c as u32,+ 0x1100..=0x11FF // Hangul Jamo+ | 0x0E00..=0x0EFF // Thai, Lao+ | 0x1000..=0x109F // Myanmar+ | 0x1780..=0x17FF // Khmer+ | 0x3000..=0x303F // CJK symbols and punctuation (、。「」)+ | 0x3040..=0x30FF // Hiragana, Katakana+ | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A+ | 0x4E00..=0x9FFF // CJK Unified Ideographs+ | 0xAC00..=0xD7AF // Hangul Syllables+ | 0xF900..=0xFAFF // CJK Compatibility Ideographs+ | 0xFF00..=0xFFEF // Halfwidth and Fullwidth Forms+ | 0x20000..=0x2A6DF // CJK Unified Ideographs Extension B+ )+}++/// Share of `text` that is scriptio-continua, in percent.+fn continua_percent(text: &str) -> usize {+ let mut total = 0usize;+ let mut hits = 0usize;+ for c in text.chars() {+ total += 1;+ if is_scriptio_continua(c) {+ hits += 1;+ }+ }+ if total == 0 {+ return 0;+ }+ hits * 100 / total+}++/// Whether `bytes` are plausibly text in a legacy CJK encoding.+///+/// This is a TEXT-NESS test and nothing more. It deliberately does NOT return+/// which encoding: Shift-JIS, GBK, Big5 and EUC-KR share most of the same+/// valid double-byte space, so a GBK document also decodes losslessly as+/// Shift-JIS (and vice versa) with a high ideograph share either way. Telling+/// them apart needs a statistical language model — what `chardet`/ICU do —+/// which this crate does not have, and guessing would silently replace a+/// Chinese document with plausible-looking Japanese mojibake. Tracked as a+/// follow-up; see CHANGELOG.+///+/// What it IS sound for is the only question asked here: are these bytes a+/// pixel/float payload, or somebody's prose? The pixel-soup guards below key+/// off high-byte density and whitespace density, and legacy CJK prose looks+/// exactly like soup under both — ~100% high-byte and ~0% whitespace — so+/// without this they junk the file outright. Requiring a LOSSLESS decode+/// (one undecodable pair disqualifies it) plus a substantially ideographic+/// result keeps European windows-1252 prose out: its high bytes sit isolated+/// among ASCII, so most form no valid double-byte pair at all.+fn looks_like_legacy_cjk(bytes: &[u8]) -> bool {+ [+ encoding_rs::SHIFT_JIS,+ encoding_rs::GBK,+ encoding_rs::BIG5,+ encoding_rs::EUC_KR,+ ]+ .into_iter()+ .any(|enc| {+ let (s, _, had_errors) = enc.decode(bytes);+ !had_errors && continua_percent(&s) >= 30+ })+}+fn decode(bytes: &[u8]) -> (String, &'static str) {match std::str::from_utf8(bytes) {Ok(s) => (s.to_string(), "utf-8"),@@ -238,7 +416,7 @@ fn decode(bytes: &[u8]) -> (String, &'static str) {)} else {let (s, _, _) = encoding_rs::WINDOWS_1252.decode(bytes);- (s.into_owned(), "windows-1252 (lossy)")+ (s.into_owned(), WINDOWS_1252_LOSSY)}}}@@ -366,6 +544,30 @@ fn txt_kind(nonblank: &[&str]) -> Family {if nonblank.is_empty() {return Family::TxtLines;}+ // NOTE — a whitespace-density guard ("text over 4 KiB with under 5%+ // whitespace is pixel soup, junk it") was proposed here to catch raw TGA+ // and `.bytes` payloads that decode into printable characters. It is not+ // present, deliberately, because low whitespace density does not mean+ // "not text":+ //+ // * Chinese, Japanese, Korean, Thai, Lao, Khmer and Burmese prose is+ // scriptio continua — `nonblank` comes from `text.lines()`, so the+ // newlines are already stripped and only INTRA-LINE whitespace counts,+ // which those scripts do not have. Every such document over ~4 KiB+ // would be junked, in every corpus, worldwide.+ // * base64 blobs, hex dumps, FASTA/genomic sequences, single-line+ // minified payloads and long-token files are all legitimate text with+ // near-zero whitespace.+ // * `failure_resume_http_tests::legacy_key_collision_fails_before_+ // visibility_with_scoped_guidance` builds a 65,537-byte fixture of one+ // repeated ASCII letter. With the guard in place that file sniffs as+ // binary and the run exits 3 instead of 0 — the false positive is+ // reachable from this repo's own suite.+ //+ // High-byte payloads (which is what a real TGA is) are still caught, by+ // the windows-1252 non-ASCII test in `sniff_bytes`. Bounding sectioning+ // memory is the right fix for the RAM concern; silently deleting files+ // that look unusual is not. Tracked as a follow-up.let avg_len = nonblank.iter().map(|l| l.len()).sum::<usize>() as f64 / nonblank.len() as f64;if avg_len > 60.0 {return Family::TxtProse;@@ -527,6 +729,276 @@ fn sniff_csv_dialect(nonblank: &[&str]) -> Option<CsvDialect> {})}+#[cfg(test)]+mod unity_sniff_tests {+ use super::*;+ use std::path::Path;++ fn sniff_str(s: &str, name: &str) -> Family {+ sniff_bytes(s.as_bytes(), Path::new(name), Path::new(name), false)+ .unwrap()+ .family+ }++ #[test]+ fn unity_tagged_yaml_is_detected_by_header_not_extension() {+ let scene =+ "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &123\nGameObject:\n m_Name: X\n";+ assert_eq!(sniff_str(scene, "Main.unity"), Family::UnityYaml);+ assert_eq!(+ sniff_str(scene, "renamed.txt"),+ Family::UnityYaml,+ "content decides, never the extension"+ );+ }++ #[test]+ fn a_bom_before_the_yaml_directive_is_tolerated() {+ let scene =+ "\u{feff}%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1\nGameObject:\n m_Name: X\n";+ assert_eq!(sniff_str(scene, "Main.unity"), Family::UnityYaml);+ }++ #[test]+ fn meta_needs_the_first_line_rule_and_a_guid() {+ let meta =+ "fileFormatVersion: 2\nguid: 9f1c4d0ab2e34f6\nMonoImporter:\n serializedVersion: 2\n";+ assert_eq!(sniff_str(meta, "Player.cs.meta"), Family::UnityMeta);+ let stray = "config: true\nfileFormatVersion: 2\nguid: abc\n";+ assert_ne!(+ sniff_str(stray, "some.yaml"),+ Family::UnityMeta,+ "guid keys inside ordinary YAML must not reclassify it"+ );+ let no_guid = "fileFormatVersion: 2\nsettings:\n a: 1\n";+ assert_ne!(sniff_str(no_guid, "x.meta"), Family::UnityMeta);+ }++ #[test]+ fn bvh_is_detected_by_hierarchy_root_header() {+ let bvh = "HIERARCHY\nROOT Hips\n{\n OFFSET 0 90 0\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\n}\nMOTION\nFrames: 2\nFrame Time: 0.033\n1 2 3\n4 5 6\n";+ assert_eq!(sniff_str(bvh, "clip.bvh"), Family::Bvh);+ assert_eq!(+ sniff_str(bvh, "clip.txt"),+ Family::Bvh,+ "content decides, never the extension"+ );+ let not_bvh = "HIERARCHY\nof needs (Maslow):\n- physiological\n- safety\n";+ assert_ne!(sniff_str(not_bvh, "notes.txt"), Family::Bvh);+ }++ #[test]+ fn plain_yaml_without_the_unity_tag_stays_yaml() {+ let plain = "%YAML 1.2\n---\nkey: value\nother: 1\nnested:\n a: 2\n";+ assert_ne!(sniff_str(plain, "doc.yaml"), Family::UnityYaml);+ }++ /// Regression: PSD image data decoded via lossy windows-1252 passed the+ /// NUL/control-char heuristics and classified as txt-prose, turning a+ /// multi-MB texture into ~100x its size of prose sections. Media magic+ /// bytes must win before any text heuristic runs.+ #[test]+ fn media_containers_are_binary_by_magic_not_heuristics() {+ for (name, head) in [+ ("t.psd", &b"8BPS\x00\x01"[..]),+ ("t.tif", &b"II*\x00\x08\x00"[..]),+ ("t.tif2", &b"MM\x00*\x00\x08"[..]),+ ("t.wav", &b"RIFF\x24\x08\x00\x00WAVE"[..]),+ ("t.ogg", &b"OggS\x00\x02"[..]),+ ("t.fbx", &b"Kaydara FBX Binary \x00"[..]),+ ] {+ let mut bytes = head.to_vec();+ // A printable tail that WOULD pass the prose heuristics.+ bytes.extend(b"lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(20));+ let sn = sniff_bytes(&bytes, Path::new(name), Path::new(name), false).unwrap();+ assert_eq!(sn.family, Family::Binary, "{name} must be binary");+ }+ }++ /// Whitespace density must NOT be used to junk text. This pins the+ /// counter-examples that make the rejected guard unsafe: a long run of one+ /// ASCII letter (the shape of this repo's own 65,537-byte resume-key+ /// fixture), and a base64 blob. Both are >4 KiB with zero whitespace, and+ /// both are text.+ #[test]+ fn whitespace_free_ascii_text_is_not_junked_as_binary() {+ let mut repeated = "x".repeat(65_536);+ repeated.push('b');+ let b64: String = std::iter::repeat_n("QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", 300)+ .collect::<Vec<_>>()+ .join("");+ for (label, text) in [("repeated-letter", &repeated), ("base64", &b64)] {+ assert!(text.chars().filter(|c| c.is_whitespace()).count() == 0);+ let sn = sniff_bytes(+ text.as_bytes(),+ Path::new("blob.txt"),+ Path::new("blob.txt"),+ false,+ )+ .unwrap();+ assert_ne!(+ sn.family,+ Family::Binary,+ "{label}: whitespace-free ASCII is still text"+ );+ }+ // Real prose is unaffected either way.+ let prose = "The quick brown fox jumps over the lazy dog. ".repeat(200);+ let sn = sniff_bytes(+ prose.as_bytes(),+ Path::new("note.txt"),+ Path::new("note.txt"),+ false,+ )+ .unwrap();+ assert_ne!(sn.family, Family::Binary, "real prose must stay text");+ }++ /// Regression: a whitespace-density guard judged every script by a rule+ /// that only holds for space-delimited ones. `nonblank` is built from+ /// `text.lines()`, so newlines are already gone and only INTRA-LINE+ /// whitespace counts — which CJK/Thai/Lao/Khmer/Burmese prose does not+ /// have. Every such document over ~4 KB became `Family::Binary` and was+ /// junked as "binary content (unknown)", in a Unity PR, for users with no+ /// Unity project. Both original tests used Latin prose and ASCII soup, so+ /// neither could see it. The guard is gone; this pins the outcome so it+ /// cannot come back in another form.+ #[test]+ fn scriptio_continua_prose_is_not_mistaken_for_binary_soup() {+ // Each sample is >= 4096 chars (the old guard's gate) and has NO+ // spaces, exactly like the real documents that were being junked.+ for (label, unit) in [+ ("chinese", "本文档描述了系统的架构设计与实现细节。"),+ (+ "japanese",+ "この文書はシステムの設計と実装について説明します。",+ ),+ ("korean", "이문서는시스템설계와구현에대해설명합니다"),+ ("thai", "เอกสารนี้อธิบายการออกแบบและการใช้งานของระบบ"),+ ] {+ let text = unit.repeat(4096 / unit.chars().count() + 2);+ assert!(+ text.chars().count() >= 4096,+ "{label}: sample must clear the 4096-char gate"+ );+ let ws = text.chars().filter(|c| c.is_whitespace()).count();+ assert!(+ ws * 20 < text.chars().count(),+ "{label}: sample must be below the 5% whitespace ratio, else \+ it would have passed the old guard for the wrong reason"+ );+ let sn = sniff_bytes(+ text.as_bytes(),+ Path::new("notes.txt"),+ Path::new("notes.txt"),+ false,+ )+ .unwrap();+ assert_ne!(+ sn.family,+ Family::Binary,+ "{label}: scriptio-continua prose must not be junked as binary"+ );+ }+ }++ /// Regression: the sibling guard keyed off `encoding != "utf-8"`, and a+ /// legacy CJK encoding decodes as lossy windows-1252 into ~100%+ /// high-byte mojibake — so every Shift-JIS/GBK/Big5/EUC-KR document was+ /// junked before any family heuristic ran.+ ///+ /// The assertion is deliberately only "not binary". This crate cannot+ /// tell these encodings apart (they share most of their valid+ /// double-byte space) and does not pretend to: the file is still decoded+ /// as windows-1252, exactly as it was before this branch, which is+ /// mojibake — but mojibake that is INDEXED rather than deleted.+ #[test]+ fn legacy_encoded_cjk_prose_is_not_junked_as_binary() {+ for (label, enc, unit) in [+ (+ "shift_jis",+ encoding_rs::SHIFT_JIS,+ "この文書はシステムの設計について説明します。",+ ),+ ("gbk", encoding_rs::GBK, "本文档描述了系统的架构设计。"),+ ("big5", encoding_rs::BIG5, "本文件描述系統的架構設計。"),+ (+ "euc-kr",+ encoding_rs::EUC_KR,+ "이문서는시스템설계를설명합니다",+ ),+ ] {+ let text = unit.repeat(4096 / unit.chars().count() + 2);+ let (bytes, _, had_errors) = enc.encode(&text);+ assert!(!had_errors, "{label}: fixture must encode cleanly");+ assert!(+ std::str::from_utf8(&bytes).is_err(),+ "{label}: fixture must not be valid UTF-8, or it proves nothing"+ );+ assert!(+ looks_like_legacy_cjk(&bytes),+ "{label}: text-ness probe must recognise this as prose"+ );+ let sn =+ sniff_bytes(&bytes, Path::new("doc.txt"), Path::new("doc.txt"), false).unwrap();+ assert_ne!(sn.family, Family::Binary, "{label}: must not be junked");+ }+ }++ /// The legacy-CJK probe must not capture European text — that would+ /// replace real windows-1252 prose with plausible-looking ideographs.+ #[test]+ fn european_windows_1252_prose_is_not_claimed_as_cjk() {+ let text = "Le système décrit ici gère les données réservées à \+ l'opérateur, prêtes à être exportées. ";+ let long = text.repeat(80);+ let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode(&long);+ assert!(std::str::from_utf8(&bytes).is_err());+ let (_, enc) = decode(&bytes);+ assert_eq!(enc, WINDOWS_1252_LOSSY, "must stay windows-1252");+ assert!(+ !looks_like_legacy_cjk(&bytes),+ "accented Latin must not be claimed as CJK"+ );+ let sn = sniff_bytes(&bytes, Path::new("note.txt"), Path::new("note.txt"), false).unwrap();+ assert_ne!(sn.family, Family::Binary, "accented prose is still prose");+ }++ /// The pixel-soup protection the guards exist for must survive the fix:+ /// high-byte float/pixel payloads still have to be caught.+ #[test]+ fn high_byte_pixel_soup_is_still_binary() {+ // Bytes that are not valid UTF-8, not valid in any legacy CJK+ // encoding as a whole, and majority high-byte — a raw texture.+ let soup: Vec<u8> = (0..8192u32)+ .map(|i| (0x80 + (i * 37) % 0x7f) as u8)+ .collect();+ assert!(std::str::from_utf8(&soup).is_err());+ let sn = sniff_bytes(+ &soup,+ Path::new("texture.tga"),+ Path::new("texture.tga"),+ false,+ )+ .unwrap();+ assert_eq!(sn.family, Family::Binary, "pixel soup must stay binary");+ }++ #[test]+ fn binary_serialized_unity_assets_stay_binary() {+ let mut bytes = b"UnityFS\x00\x00\x00\x00\x08".to_vec();+ bytes.extend(std::iter::repeat_n(0u8, 64));+ let sn = sniff_bytes(+ &bytes,+ Path::new("scene.unity"),+ Path::new("scene.unity"),+ false,+ )+ .unwrap();+ assert_eq!(sn.family, Family::Binary);+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/engine/crates/xerj-autoindex/src/walk.rs b/engine/crates/xerj-autoindex/src/walk.rsindex f4cb8facf..db0e4eddb 100644--- a/engine/crates/xerj-autoindex/src/walk.rs+++ b/engine/crates/xerj-autoindex/src/walk.rs@@ -23,6 +23,54 @@ pub struct FileEntry {pub size: u64,}+/// Generated/cache directories whose NAMES are too common for the blunt+/// [`crate::ignore_rules::DEFAULT_IGNORE_PATTERNS`] (a folder named `Logs/`+/// or `Library/` is often real data), pruned at any depth ONLY when a sibling+/// marker file proves the parent directory is that kind of project. Part of+/// the built-in defaults: `--no-ignore` / `--no-default-ignores` disable it,+/// and any ignore file in the tree can re-include (`!Library/`) as usual —+/// these run after the ignore files have had their say.+///+/// (dir name, marker path relative to the dir's PARENT, report label)+const MARKER_GENERATED_DIRS: &[(&str, &str, &str)] = &[+ (+ "Library",+ "ProjectSettings/ProjectVersion.txt",+ "default:unity-generated",+ ),+ (+ "Temp",+ "ProjectSettings/ProjectVersion.txt",+ "default:unity-generated",+ ),+ (+ "obj",+ "ProjectSettings/ProjectVersion.txt",+ "default:unity-generated",+ ),+ (+ "Logs",+ "ProjectSettings/ProjectVersion.txt",+ "default:unity-generated",+ ),+ (+ "UserSettings",+ "ProjectSettings/ProjectVersion.txt",+ "default:unity-generated",+ ),+];++/// The marker-gated verdict for one directory entry.+fn marker_generated_dir(path: &Path) -> Option<&'static str> {+ let name = path.file_name()?;+ for (dir, marker, label) in MARKER_GENERATED_DIRS {+ if name == *dir && path.parent().is_some_and(|p| p.join(marker).is_file()) {+ return Some(label);+ }+ }+ None+}+/// Walk with the default ignore rules on and the report discarded.pub fn walk(root: &Path, follow_symlinks: bool) -> Result<Vec<FileEntry>> {walk_reporting(root, follow_symlinks, IgnoreOptions::default()).map(|(files, _)| files)@@ -46,6 +94,7 @@ pub fn walk_reporting(anyhow::bail!("{} is not a directory", root_canon.display());}let mut out = Vec::new();+ let marker_defaults = ignore.enabled && ignore.defaults;let mut stack = IgnoreStack::new(&root_canon, ignore);// Manual iteration rather than `filter_entry`, because the ignore stack has// to load a directory's ignore files *after* that directory is admitted and@@ -110,6 +159,18 @@ pub fn walk_reporting(it.skip_current_dir();continue;}+ // Marker-gated generated dirs (part of the built-in defaults, so+ // `--no-ignore` / `--no-default-ignores` disable it): names like+ // Unity's `Library/` or `Logs/` are too common for the blunt+ // DEFAULT_IGNORE_PATTERNS, so they are pruned only when a sibling+ // marker file proves the parent is that kind of project.+ if entry.depth() > 0 && marker_defaults {+ if let Some(label) = marker_generated_dir(entry.path()) {+ stack.record_marker_dir(entry.path(), label);+ it.skip_current_dir();+ continue;+ }+ }stack.enter_dir(entry.path(), entry.depth());continue;}@@ -408,3 +469,95 @@ mod hidden_skip_tests {);}}++#[cfg(test)]+mod marker_generated_dir_tests {+ use super::{walk, walk_reporting};+ use crate::ignore_rules::IgnoreOptions;+ use std::fs;+ use std::path::Path;++ fn make_unity_project(root: &Path, with_marker: bool) {+ fs::create_dir_all(root.join("Assets")).unwrap();+ fs::write(root.join("Assets/Player.cs"), "class Player {}").unwrap();+ fs::create_dir_all(root.join("Library/Artifacts")).unwrap();+ fs::write(root.join("Library/Artifacts/blob.bin"), b"\x00\x01").unwrap();+ fs::create_dir_all(root.join("Logs")).unwrap();+ fs::write(root.join("Logs/editor.log"), "x").unwrap();+ if with_marker {+ fs::create_dir_all(root.join("ProjectSettings")).unwrap();+ fs::write(+ root.join("ProjectSettings/ProjectVersion.txt"),+ "m_EditorVersion: 2022.3.10f1\n",+ )+ .unwrap();+ }+ }++ /// Monorepo case: the Unity project is a SUBFOLDER of the walk root; the+ /// sibling marker decides at any depth.+ #[test]+ fn a_nested_unity_project_is_pruned_and_reported() {+ let dir = tempfile::TempDir::new().unwrap();+ let unity = dir.path().join("platform/unity");+ fs::create_dir_all(&unity).unwrap();+ make_unity_project(&unity, true);+ let (files, report) = walk_reporting(dir.path(), false, IgnoreOptions::default()).unwrap();+ let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();+ assert!(rels.contains(&"platform/unity/Assets/Player.cs"));+ assert!(+ !rels.iter().any(|r| r.contains("/Library/")),+ "Library/ must be pruned whole: {rels:?}"+ );+ assert!(+ report+ .by_rule+ .keys()+ .any(|k| k == "default:unity-generated"),+ "the prune must be named on the report: {report:?}"+ );+ }++ /// Without the marker, a folder merely NAMED Library or Logs is data.+ #[test]+ fn without_the_marker_nothing_is_pruned() {+ let dir = tempfile::TempDir::new().unwrap();+ make_unity_project(dir.path(), false);+ let files = walk(dir.path(), false).unwrap();+ let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();+ assert!(rels.contains(&"Library/Artifacts/blob.bin"), "{rels:?}");+ assert!(rels.contains(&"Logs/editor.log"), "{rels:?}");+ }++ /// The marker rule is one of the built-in defaults, so both switches+ /// disable it.+ #[test]+ fn no_ignore_and_no_default_ignores_both_disable_the_marker_rule() {+ let dir = tempfile::TempDir::new().unwrap();+ make_unity_project(dir.path(), true);+ let no_defaults = IgnoreOptions {+ defaults: false,+ ..IgnoreOptions::default()+ };+ for opts in [IgnoreOptions::off(), no_defaults] {+ let (files, _) = walk_reporting(dir.path(), false, opts).unwrap();+ let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();+ assert!(+ rels.contains(&"Library/Artifacts/blob.bin"),+ "opts {opts:?} must walk generated dirs: {rels:?}"+ );+ }+ }++ #[test]+ fn a_file_named_like_a_generated_dir_is_not_pruned() {+ let dir = tempfile::TempDir::new().unwrap();+ make_unity_project(dir.path(), true);+ fs::write(dir.path().join("obj"), "a FILE named obj").unwrap();+ let files = walk(dir.path(), false).unwrap();+ assert!(+ files.iter().any(|e| e.rel == "obj"),+ "the prune applies to directories only"+ );+ }+}diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rsindex 34e5d70fa..44dfd73bc 100644--- a/engine/crates/xerj-server/src/brain.rs+++ b/engine/crates/xerj-server/src/brain.rs@@ -573,6 +573,7 @@ fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {state_dir: None,fresh: cfg.fresh,follow_symlinks: false,+ stub_globs: Vec::new(),// `xerj brain` composes autoindex, so it inherits its ignore rules// rather than inventing its own: build output does not belong in a// second brain either (#276).