Skip to main content

rto_graph/
extract.rs

1//! Extraction: turning the bytes of a source blob into a [`FactSet`].
2//!
3//! Extraction must be a deterministic pure function of `(path, blob_id, bytes)`
4//! so its output can be cached; because the facts are path-dependent (node keys
5//! are path-scoped), the cache is keyed by both path and blob id (see
6//! [`crate::sync`]). [`Registry`] dispatches by file extension to a
7//! language-aware extractor ([`RustExtractor`]), falling back to
8//! [`FileNodeExtractor`] for files with no registered language.
9//!
10//! Language extractors emit `defines`/`contains`/`imports` edges directly, and
11//! record each function's callee names in the caller node's `meta.calls`. Call
12//! *edges* are resolved later, at assembly time, once every file's symbols are
13//! known (see [`crate::sync`]) — a single blob cannot resolve cross-file calls.
14
15use crate::{Edge, EdgeKind, FactSet, Node, NodeKind, Provenance, Span};
16
17/// Version of the extraction *output* (node/edge shape and captured `meta`).
18/// Bump whenever extraction changes what it produces, so the content-addressed
19/// cache (keyed by blob oid + path) does not serve stale facts for an unchanged
20/// blob — the version is folded into the cache key. See [`crate::sync`].
21///
22/// The `pdf-text`, `image-ocr` and `audio-metadata` features change what PDFs,
23/// images and audio blobs extract to, so each occupies a distinct version
24/// namespace: a feature build and a default build never serve each other stale
25/// (content-bearing vs content-free) facts from a shared cache. (OCR output also depends on *which* models are
26/// installed; that runtime state is folded into the cache key separately — see
27/// [`media_env_tag`] and [`crate::sync`].)
28///
29/// `image-vision` and `audio-transcribe` deliberately have **no namespace here
30/// any more**: since ADR-0015 they change nothing about extraction output, so
31/// they must not perturb a cache key. What they produce is generated content,
32/// which lives in [`crate::media`].
33///
34/// # Changing this number
35///
36/// **No test pins its value, deliberately.** A bump is the correct response to a
37/// real change in extraction output, so it must not also be a test failure —
38/// pinning it made every legitimate bump land on whoever tripped the guard, who
39/// then had to work out whether they had broken an invariant or merely renumbered
40/// a constant. Tests assert what the version is *for* instead: that it is folded
41/// into the cache key (`sync::tests::cache_key_separates_paths_but_is_stable`),
42/// that a changed identity re-extracts at an unchanged tree, and that work which
43/// is not extraction cannot perturb it
44/// (`tests/sync.rs::memory_writes_do_not_invalidate_the_fact_cache`). So if a
45/// test *does* fail when you bump this, it is reporting a real coupling, not the
46/// number. Record the bump in the history comment below and in the ADR that
47/// motivates it; that record, and review, are what keep bumps honest.
48// Bumped 5 → 6 for config-key nodes (ADR-0009): config files now emit
49// `config_key` nodes, so cached extraction facts must be regenerated. Bumped
50// 6 → 7 for YAML config keys + Dockerfile `image_ref` nodes (ADR-0009 derived
51// deploy-artifact extraction). Bumped 7 → 8 for struct `meta.fields` (the named
52// field list a struct declares) — the signal the config_key→struct follow bridge
53// joins on, so cached struct facts must be regenerated to carry it. Bumped 8 → 9
54// for struct `meta.field_types` / `meta.config_root` and the `config_key` nodes
55// synthesized from a `@rto:config`-marked config-root struct's declared fields
56// (see [`RustWalk::synthesize_config_keys`]), so cached facts regenerate to carry
57// these new nodes/meta. Bumped 9 → 10 for ADR-0015: ASR transcripts and VLM
58// descriptions are no longer written into `meta.content` at all, so every cached
59// fact set that carries one must be regenerated without it. The `image-vision`
60// (+400) and `audio-transcribe` (+800) namespaces are dropped in the same change,
61// because those features no longer affect extraction output. Bumped 10 → 11 for
62// ADR-0016: audio blobs now emit an `audio_stream` node carrying the container's
63// own account of the stream, so cached fact sets must be regenerated. The
64// `audio-metadata` namespace (+400) reoccupies `image-vision`'s retired slot —
65// safe because the base version moved with it, so no historical key can collide,
66// and because the namespaces are powers of ten *bit* values (100/200/400/800)
67// that must stay disjoint: +300 would alias a `pdf-text` + `image-ocr` build.
68// Bumped 11 → 12 for the marker-needle correction: the bare word `placeholder`
69// is no longer a `stub` needle (it scored 0% precision — 36 of 36 findings on
70// this repository named an implemented concept), replaced by the two phrases
71// that predicate incompleteness of an implementation. The next line names them,
72// and so carries the inline opt-out rather than reporting itself — the same
73// reason `markers.rs` carries the file-level one:
74// `placeholder implementation` / `returns a placeholder`.  roteiro:ignore
75// [`crate::markers::augment`] runs inside extraction, so every cached fact set
76// holding one of those 36 must be regenerated without it; without the bump a
77// cached blob keeps serving the phantom marker until its bytes happen to
78// change. No namespace moves: this is a base-version change only, unconditional
79// across every feature combination.
80pub(crate) const EXTRACT_VERSION: u32 = EXTRACT_BASE_VERSION
81    + if cfg!(feature = "pdf-text") { 100 } else { 0 }
82    + if cfg!(feature = "image-ocr") { 200 } else { 0 }
83    + if cfg!(feature = "audio-metadata") {
84        400
85    } else {
86        0
87    };
88
89/// The **generation** half of [`EXTRACT_VERSION`]: what a bump above counts, with
90/// no feature namespace added. Monotone, global, and identical in every build —
91/// which is what makes it, and not [`EXTRACT_VERSION`], the thing an entry's
92/// reachability can be decided against (see [`crate::sync::sweep_superseded`]).
93///
94/// The split was always there, encoded in the arithmetic; naming it only makes
95/// it readable. `EXTRACT_VERSION` is unchanged in every build: this is the same
96/// `12` the sum has always started from.
97pub(crate) const EXTRACT_BASE_VERSION: u32 = 12;
98
99/// The stride between feature namespaces above. Each of the three
100/// extraction-affecting features occupies a distinct power-of-ten *bit* slot
101/// (100/200/400 — see the history above), so a namespace is always a whole
102/// multiple of this and the base is always the remainder.
103pub(crate) const FEATURE_NAMESPACE_STRIDE: u32 = 100;
104
105// The key grammar depends on this: `v{EXTRACT_VERSION}` is decodable back into
106// (base, namespace) only while the base stays below the stride. It has always
107// depended on it — a base of 100 with no features would have written the same
108// `v100` as a base of 0 in a `pdf-text` build, aliasing two generations onto one
109// key — so this asserts an existing invariant rather than adding one. If the
110// base ever approaches 100, widen the stride (and the namespaces with it) in the
111// same change; do not let it wrap.
112const _: () = assert!(
113    EXTRACT_BASE_VERSION < FEATURE_NAMESPACE_STRIDE,
114    "EXTRACT_BASE_VERSION must stay below FEATURE_NAMESPACE_STRIDE, or a version \
115     tag stops decoding into (generation, feature namespace)"
116);
117
118/// Max characters of embeddable content (markdown body / doc-comment / PDF text)
119/// captured into a node's `meta.content`, to keep the store small while giving
120/// inference real text to embed.
121const MAX_CONTENT: usize = 1500;
122
123/// PDFs larger than this are not text-extracted — `pdf-extract` builds the full
124/// document text in memory, so cap the work a pathological file can impose.
125#[cfg(feature = "pdf-text")]
126const MAX_PDF_BYTES: usize = 20 * 1024 * 1024;
127
128/// Images with more pixels than this are not processed — OCR/VLM time scales with
129/// pixel count, and this also guards against decompression bombs (the dimension is
130/// read from the header before the pixels are decoded).
131#[cfg(any(feature = "image-ocr", feature = "image-vision"))]
132const MAX_IMAGE_PIXELS: u64 = 4096 * 4096;
133
134/// Turns one source blob into the nodes and edges derived from it.
135pub trait Extractor {
136    /// Extract a [`FactSet`] from a blob's `path`, git `blob_id`, and `bytes`.
137    ///
138    /// Implementations must be deterministic: identical inputs must always
139    /// produce an identical fact set.
140    fn extract(&self, path: &str, blob_id: &str, bytes: &[u8]) -> FactSet;
141
142    /// Runtime inputs — beyond `(path, bytes)` — that change extraction output
143    /// and so must be folded into the sync cache key: the installed OCR-model
144    /// identity and any [`IngestConfig`] toggles that gate *extraction*. The
145    /// default is the media-model tag alone; [`Registry`] additionally folds in
146    /// its ingestion config so toggling content off re-extracts affected blobs
147    /// instead of serving stale, content-bearing facts.
148    fn env_tag(&self) -> u64 {
149        media_env_tag()
150    }
151}
152
153/// Runtime ingestion toggles (ADR-0007 `[ingest]`). Every toggle defaults to
154/// **on**, and a toggle only gates content *within a build that supports it* —
155/// turning `pdf` on cannot extract PDF text in a binary built without the
156/// `pdf-text` feature, but turning it off suppresses that content in a binary
157/// that has it.
158///
159/// The five toggles split into two groups, and the split is the ADR-0015
160/// boundary:
161///
162/// - `prose`, `pdf` and `ocr` gate **extraction**: what is decoded from the bytes
163///   into `meta.content` as a `derived` fact. They contribute to the extraction
164///   cache key, because turning one off changes what extraction produces.
165/// - `vision` and `audio` gate **generation**: whether `roteiro media build` may
166///   invoke a model at all. They no longer touch extraction, so they contribute
167///   nothing to the cache key — a repository that sets `audio = false` gets
168///   exactly the derived facts it would get with it on.
169// Five independent content toggles: a flat bool-per-class struct is the clearest
170// representation (a state enum or bitflags would obscure, not clarify).
171#[allow(clippy::struct_excessive_bools)]
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct IngestConfig {
174    /// Embed the UTF-8 body of prose files (Markdown, plain text).
175    pub prose: bool,
176    /// Extract text from PDF documents (needs the `pdf-text` feature).
177    pub pdf: bool,
178    /// OCR literal text from images (needs the `image-ocr` feature).
179    pub ocr: bool,
180    /// Allow `roteiro media build` to describe images with a vision model (needs
181    /// the `image-vision` feature). Since ADR-0015 this gates *generation*, not
182    /// extraction: a description is never written to `meta.content`.
183    pub vision: bool,
184    /// Allow `roteiro media build` to transcribe spoken-word audio (needs the
185    /// `audio-transcribe` feature). Gates *generation*, as `vision` does.
186    pub audio: bool,
187}
188
189impl Default for IngestConfig {
190    fn default() -> Self {
191        Self {
192            prose: true,
193            pdf: true,
194            ocr: true,
195            vision: true,
196            audio: true,
197        }
198    }
199}
200
201impl IngestConfig {
202    /// A cache-key contribution that is **`0` when every extraction toggle is
203    /// on** (the default), so the common case leaves existing cache keys
204    /// untouched. Each disabled toggle sets a distinct bit, so turning content
205    /// off changes the key and re-extracts affected blobs.
206    ///
207    /// Only the *extraction* toggles appear. `vision` and `audio` gate
208    /// generation, which no consumer of this key can observe (ADR-0015), and
209    /// folding them in would force a full re-extraction for a setting that
210    /// changes no derived fact.
211    fn disabled_bits(self) -> u64 {
212        u64::from(!self.prose) | (u64::from(!self.pdf) << 1) | (u64::from(!self.ocr) << 2)
213    }
214
215    /// Whether this configuration permits `roteiro media build` to run `kind`.
216    /// An operator can disable generation outright without touching the graph.
217    #[must_use]
218    pub fn generates(self, kind: crate::media::MediaKind) -> bool {
219        match kind {
220            crate::media::MediaKind::Audio => self.audio,
221            crate::media::MediaKind::Vision => self.vision,
222        }
223    }
224}
225
226/// Dispatches extraction to a language-aware extractor by file extension,
227/// falling back to a plain file node when no language is registered. After the
228/// language extractor runs, [`crate::markers`] appends any intent-debt markers
229/// (intent-debt markers) found in the blob. Carries the runtime
230/// [`IngestConfig`] applied to content extraction.
231#[derive(Debug, Clone, Copy, Default)]
232pub struct Registry {
233    /// Which blob content to extract for embedding.
234    pub ingest: IngestConfig,
235}
236
237impl Registry {
238    /// A registry with the given ingestion toggles.
239    #[must_use]
240    pub fn new(ingest: IngestConfig) -> Self {
241        Self { ingest }
242    }
243}
244
245impl Extractor for Registry {
246    fn extract(&self, path: &str, blob_id: &str, bytes: &[u8]) -> FactSet {
247        let mut facts = extract_facts(path, blob_id, bytes, self.ingest);
248        crate::markers::augment(&mut facts, path, blob_id, bytes);
249        facts
250    }
251
252    fn env_tag(&self) -> u64 {
253        let media = media_env_tag();
254        let disabled = self.ingest.disabled_bits();
255        if disabled == 0 {
256            // All-on default: preserve existing cache keys exactly.
257            media
258        } else {
259            // FNV-1a fold of both components — deterministic and stable. As with
260            // any 64-bit hash a collision with the all-on key is possible but
261            // vanishingly unlikely, and a collision only costs a spurious cache
262            // hit/miss, never incorrect facts.
263            let mut h = 0xcbf2_9ce4_8422_2325u64;
264            for b in media
265                .to_le_bytes()
266                .into_iter()
267                .chain(disabled.to_le_bytes())
268            {
269                h ^= u64::from(b);
270                h = h.wrapping_mul(0x0000_0100_0000_01b3);
271            }
272            h
273        }
274    }
275}
276
277/// Shared extraction dispatch used by [`Registry`] and the standalone
278/// extractors: pick the language extractor by extension, applying `ingest` to
279/// content extraction.
280fn extract_facts(path: &str, blob_id: &str, bytes: &[u8], ingest: IngestConfig) -> FactSet {
281    // Config files (TOML / JSON / .env) get config-key nodes rather than a plain
282    // file node, so their keys are first-class graph nodes (ADR-0009).
283    if crate::config_keys::is_config_path(path) {
284        return config_facts(path, blob_id, bytes, ingest);
285    }
286    // Dockerfiles yield `image_ref` nodes (the base-image version pin a spoke
287    // deploys) rather than a plain file node (ADR-0009 derived facts).
288    if is_dockerfile(path) {
289        return dockerfile_facts(path, blob_id, bytes, ingest);
290    }
291    // Audio blobs additionally yield an `audio_stream` node carrying what the
292    // container says about them (ADR-0016). Without the `audio-metadata` feature
293    // this produces exactly the plain file node the extension dispatch below
294    // would have produced, so the default build's output is unchanged.
295    if crate::media::is_audio(path) {
296        return audio_facts(path, blob_id, bytes, ingest);
297    }
298    let ext = extension(path);
299    match ext.as_deref() {
300        // Rust keeps its dedicated AST walker (imports, impl scoping, richer calls).
301        Some("rs") => rust_facts(path, blob_id, bytes, ingest),
302        // Every other supported language goes through the generic tags extractor;
303        // an unhandled extension (or a query that fails to compile) falls back to
304        // a plain file node.
305        Some(ext) => tag_facts(path, blob_id, bytes, ext, ingest).unwrap_or_else(|| {
306            FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest))
307        }),
308        None => FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest)),
309    }
310}
311
312/// Lowercase file extension of `path`, if any. Lowercasing makes extension
313/// dispatch case-insensitive, so `Guide.PDF` and `README.MD` are recognised.
314///
315/// Shared with [`crate::media`], so the paths `media build` considers and the
316/// paths extraction classifies are decided by one function rather than two that
317/// can drift.
318pub(crate) fn extension(path: &str) -> Option<String> {
319    let name = path.rsplit('/').next().unwrap_or(path);
320    name.rsplit_once('.')
321        .map(|(_, ext)| ext.to_ascii_lowercase())
322}
323
324/// The natural key of the `file` node for `path`.
325fn file_key(path: &str) -> String {
326    format!("file:{path}")
327}
328
329/// Build the shared `file` node for a source blob. `ingest` gates which content
330/// is embedded (ADR-0007 `[ingest]`): a disabled class yields no content, as if
331/// the file carried none.
332fn file_node(
333    path: &str,
334    blob_id: &str,
335    bytes: &[u8],
336    lang: Option<&str>,
337    ingest: IngestConfig,
338) -> Node {
339    let name = path.rsplit('/').next().unwrap_or(path).to_owned();
340    let lines = bytes
341        .iter()
342        .fold(0usize, |n, &b| n + usize::from(b == b'\n'));
343    let end = u32::try_from(bytes.len()).unwrap_or(u32::MAX);
344    let mut meta = serde_json::json!({ "bytes": bytes.len(), "lines": lines });
345    // Capture the (capped) body so inference embeds *meaning*, not just the
346    // filename: prose files decode as UTF-8; PDFs go through `pdf_content` (only
347    // when the `pdf-text` feature is on, otherwise it is a no-op). Each class is
348    // gated by its `ingest` toggle so a project can suppress it without a rebuild.
349    //
350    // Every branch here **decodes text that exists in the bytes** — that is the
351    // whole membership rule (ADR-0015). Prose and PDF text are parses; OCR is
352    // discriminative, and its errors are misreadings correctable against the
353    // image. An ASR transcript and a VLM description are neither: they are
354    // generated, they invent fluent text where there is nothing to read, and they
355    // are therefore not `derived` facts. They are produced by `roteiro media
356    // build` into [`crate::media`] instead, and nothing on this path may
357    // reintroduce them.
358    let content = if ingest.prose && is_prose(path) {
359        cap_content(&String::from_utf8_lossy(bytes))
360    } else if let Some(text) = ingest.pdf.then(|| pdf_content(path, bytes)).flatten() {
361        cap_content(&text)
362    } else if let Some(text) = image_content(path, bytes, ingest) {
363        cap_content(&text)
364    } else {
365        String::new()
366    };
367    if !content.is_empty() {
368        meta["content"] = serde_json::Value::from(content);
369    }
370    Node {
371        key: file_key(path),
372        kind: NodeKind::File,
373        name,
374        path: Some(path.to_owned()),
375        lang: lang.map(ToOwned::to_owned),
376        blob_hash: Some(blob_id.to_owned()),
377        span: Some(Span::new(0, end)),
378        provenance: Provenance::Derived,
379        meta,
380    }
381}
382
383/// Emit config-key facts for a config file (ADR-0009): the `file` node, plus a
384/// `config_key` node per flattened leaf — key `cfgkey:<path>#<dotted>`, name the
385/// dotted path, `meta` carrying the key and value — with a `contains` edge from
386/// the file. Deterministic: keys are de-duplicated (dotenv "last one wins") into
387/// a sorted map. Secret-looking values are redacted before they reach the store.
388fn config_facts(path: &str, blob_id: &str, bytes: &[u8], ingest: IngestConfig) -> FactSet {
389    let mut facts = FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest));
390    let file = file_key(path);
391    // A config file that repeats a key yields one node with the final value, and
392    // the emission order is deterministic regardless of parse order.
393    let mut by_key: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
394    for ck in crate::config_keys::flatten(path, bytes) {
395        by_key.insert(ck.key, ck.value);
396    }
397    for (key, value) in by_key {
398        let node_key = format!("cfgkey:{path}#{key}");
399        // Redact the value of secret-looking keys so tokens/passwords from
400        // `.env`/config files are never persisted into the (exportable) store.
401        let value = if crate::config_keys::is_secret_key(&key) {
402            crate::config_keys::REDACTED.to_owned()
403        } else {
404            value
405        };
406        let mut node = Node::new(
407            node_key.clone(),
408            NodeKind::Other(crate::config_keys::KIND.into()),
409            key.clone(),
410        );
411        node.path = Some(path.to_owned());
412        node.blob_hash = Some(blob_id.to_owned());
413        node.meta = serde_json::json!({ "key": key, "value": value });
414        facts = facts.with_node(node).with_edge(Edge::derived(
415            file.clone(),
416            node_key,
417            EdgeKind::Contains,
418        ));
419    }
420    facts
421}
422
423/// The `NodeKind::Other` token for a container base-image reference extracted from
424/// a Dockerfile `FROM` (ADR-0009 derived deploy-artifact facts). Its `meta` carries
425/// `{image, tag, digest}` — the version pin a spoke deploys.
426pub(crate) const IMAGE_REF_KIND: &str = "image_ref";
427
428/// Whether `path` is a Dockerfile/Containerfile (by conventional name):
429/// `Dockerfile`, `Containerfile`, `Dockerfile.<x>`, or `*.dockerfile`.
430fn is_dockerfile(path: &str) -> bool {
431    let base = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
432    base == "dockerfile"
433        || base == "containerfile"
434        || base.starts_with("dockerfile.")
435        || base.ends_with(".dockerfile")
436}
437
438/// Extract each Dockerfile `FROM` external base image into an `image_ref` node
439/// (`imageref:<file>#<n>`, `meta {image, tag, digest}`) with a `references` edge
440/// from the file — the version pin a deployment spoke ships. Internal multi-stage
441/// references (`FROM <prior-stage>`) and `FROM scratch` are skipped.
442fn dockerfile_facts(path: &str, blob_id: &str, bytes: &[u8], ingest: IngestConfig) -> FactSet {
443    let mut facts = FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest));
444    let file = file_key(path);
445    let text = String::from_utf8_lossy(bytes);
446    let mut stages: std::collections::HashSet<String> = std::collections::HashSet::new();
447    let mut idx = 0usize;
448    for line in text.lines() {
449        let Some(rest) = strip_from_prefix(line.trim()) else {
450            continue;
451        };
452        let (image, stage) = parse_from(rest);
453        // Decide whether the image is an earlier stage against the stages seen *so
454        // far*, before recording this line's own alias — otherwise `FROM x AS x`
455        // would wrongly treat the external image `x` as an internal stage.
456        let is_internal_stage = stages.contains(&image.to_ascii_lowercase());
457        if let Some(s) = stage {
458            stages.insert(s.to_ascii_lowercase());
459        }
460        // Skip `scratch` and references to an earlier build stage — neither is an
461        // external image to pin.
462        if image.is_empty() || image.eq_ignore_ascii_case("scratch") || is_internal_stage {
463            continue;
464        }
465        let (name, tag, digest) = split_image(image);
466        let node_key = format!("imageref:{path}#{idx}");
467        idx += 1;
468        let mut node = Node::new(
469            node_key.clone(),
470            NodeKind::Other(IMAGE_REF_KIND.into()),
471            image.to_owned(),
472        );
473        node.path = Some(path.to_owned());
474        node.blob_hash = Some(blob_id.to_owned());
475        node.meta = serde_json::json!({ "image": name, "tag": tag, "digest": digest });
476        facts = facts.with_node(node).with_edge(Edge::derived(
477            file.clone(),
478            node_key,
479            EdgeKind::References,
480        ));
481    }
482    facts
483}
484
485/// Emit the facts for an audio blob (ADR-0016): the usual `file` node, plus — in
486/// an `audio-metadata` build, where the container yielded anything — one
487/// `audio_stream` node under a `contains` edge from the file.
488///
489/// The metadata is a **format read**: codec, sample rate, bit depth, channels,
490/// duration and tags, with no decoder instantiated and no model consulted. That
491/// makes it a deterministic pure function of the bytes, which is what qualifies it
492/// as `derived` at all — the mirror image of ADR-0015, which moved *generated*
493/// text out of this path for failing exactly that test.
494///
495/// A blob the reader cannot make sense of contributes **no node**, rather than a
496/// node full of nulls: absence is recorded as absence.
497fn audio_facts(path: &str, blob_id: &str, bytes: &[u8], ingest: IngestConfig) -> FactSet {
498    let facts = FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest));
499    let Some(node) = audio_stream_node(path, blob_id, bytes) else {
500        return facts;
501    };
502    let node_key = node.key.clone();
503    facts
504        .with_node(node)
505        .with_edge(Edge::derived(file_key(path), node_key, EdgeKind::Contains))
506}
507
508/// The `audio_stream` node for one audio blob, or `None` when the container had
509/// nothing to say.
510///
511/// The facts land in `meta` as the serialised [`crate::audio::AudioFacts`], plus a
512/// rendered `meta.content` so [`crate::search`] finds them through the **ordinary**
513/// scorer — no new branch, and therefore no new ranking rule. Being `derived`, the
514/// node takes no `authored` boost.
515///
516/// Note what is *not* here: nothing is written to the audio **`file`** node's
517/// `meta.content`. That slot is the one ADR-0015 emptied of transcripts, and
518/// leaving it empty is what keeps "this audio file node carries content" an
519/// unambiguous statement.
520#[cfg(feature = "audio-metadata")]
521fn audio_stream_node(path: &str, blob_id: &str, bytes: &[u8]) -> Option<Node> {
522    let facts = crate::audio::read(bytes, extension(path).as_deref())?;
523    let mut meta = serde_json::to_value(&facts).ok()?;
524    // The searchable rendering, capped like every other `meta.content`. Written
525    // last so it cannot be shadowed by a field of the same name.
526    meta["content"] = serde_json::Value::from(cap_content(&facts.summary()));
527    let name = path.rsplit('/').next().unwrap_or(path).to_owned();
528    let mut node = Node::new(
529        format!("audio:{path}"),
530        NodeKind::Other(crate::audio::AUDIO_STREAM_KIND.into()),
531        name,
532    );
533    node.path = Some(path.to_owned());
534    node.blob_hash = Some(blob_id.to_owned());
535    node.span = Some(Span::new(0, u32::try_from(bytes.len()).unwrap_or(u32::MAX)));
536    node.meta = meta;
537    Some(node)
538}
539
540/// No-op without `audio-metadata`: an audio blob is a plain `file` node, exactly
541/// as it was before ADR-0016.
542#[cfg(not(feature = "audio-metadata"))]
543fn audio_stream_node(_path: &str, _blob_id: &str, _bytes: &[u8]) -> Option<Node> {
544    None
545}
546
547/// The remainder of a `FROM ` line (case-insensitive prefix), or `None`.
548fn strip_from_prefix(line: &str) -> Option<&str> {
549    let b = line.as_bytes();
550    (b.len() >= 5 && b[..4].eq_ignore_ascii_case(b"from") && b[4].is_ascii_whitespace())
551        .then(|| line[5..].trim_start())
552}
553
554/// Parse a `FROM` argument list into `(image, stage-alias)`: the first non-flag
555/// token is the image (leading `--platform=…` flags skipped), and an `AS <name>`
556/// suffix names the build stage.
557fn parse_from(rest: &str) -> (&str, Option<&str>) {
558    let image = rest
559        .split_whitespace()
560        .find(|t| !t.starts_with("--"))
561        .unwrap_or("");
562    let mut toks = rest.split_whitespace();
563    let mut stage = None;
564    while let Some(t) = toks.next() {
565        if t.eq_ignore_ascii_case("as") {
566            stage = toks.next();
567            break;
568        }
569    }
570    (image, stage)
571}
572
573/// Split an image reference into `(name, tag, digest)`. A `@sha256:…` digest wins;
574/// otherwise a tag is the `:`-suffix *after the last path segment* (so a registry
575/// `host:port/` prefix is never mistaken for a tag).
576fn split_image(image: &str) -> (String, Option<String>, Option<String>) {
577    if let Some((name, digest)) = image.split_once('@') {
578        return (name.to_owned(), None, Some(digest.to_owned()));
579    }
580    let seg = image.rfind('/').map_or(0, |i| i + 1);
581    if let Some(colon) = image[seg..].find(':') {
582        let at = seg + colon;
583        return (
584            image[..at].to_owned(),
585            Some(image[at + 1..].to_owned()),
586            None,
587        );
588    }
589    (image.to_owned(), None, None)
590}
591
592/// Strip doc-comment markers from a comment, returning its body — or `None` if
593/// it is not a doc comment. Recognises `///` (but not `////`), `//!`, `/** */`,
594/// and `/*! */`; a plain `//` or `/* */` comment returns `None`.
595fn doc_comment_body(raw: &str) -> Option<String> {
596    let t = raw.trim();
597    if t.starts_with("//!") || (t.starts_with("///") && !t.starts_with("////")) {
598        return Some(t[3..].trim().to_owned());
599    }
600    if (t.starts_with("/**") || t.starts_with("/*!")) && t.ends_with("*/") {
601        // Content lies between the 3-char opener (`/**`/`/*!`) and the 2-char
602        // closer (`*/`). Guard the overlap on tiny comments like `/**/`, where
603        // the opener and closer share a `*` — those have no body.
604        let end = t.len() - 2;
605        let inner = if end >= 3 { &t[3..end] } else { "" };
606        let cleaned: Vec<&str> = inner
607            .lines()
608            .map(|l| l.trim().trim_start_matches('*').trim())
609            .filter(|l| !l.is_empty())
610            .collect();
611        return Some(cleaned.join(" "));
612    }
613    None
614}
615
616/// Extract the text of a PDF blob for embedding, or `None` when `path` is not a
617/// PDF, the `pdf-text` feature is off, the file is too large, or extraction
618/// yields no usable text.
619///
620/// `pdf-extract` handles fonts/CMaps internally but can panic on some malformed
621/// documents; the call is panic-guarded so a bad PDF degrades to a plain file
622/// node rather than aborting the whole sync.
623#[cfg(feature = "pdf-text")]
624fn pdf_content(path: &str, bytes: &[u8]) -> Option<String> {
625    if extension(path).as_deref() != Some("pdf") || bytes.len() > MAX_PDF_BYTES {
626        return None;
627    }
628    let owned = bytes.to_vec();
629    let text = std::panic::catch_unwind(move || pdf_extract::extract_text_from_mem(&owned).ok())
630        .ok()
631        .flatten()?;
632    (!text.trim().is_empty()).then_some(text)
633}
634
635/// No-op when the `pdf-text` feature is off: PDFs become plain file nodes.
636#[cfg(not(feature = "pdf-text"))]
637fn pdf_content(_path: &str, _bytes: &[u8]) -> Option<String> {
638    None
639}
640
641/// Embeddable content for an image blob: the literal text OCR reads out of it,
642/// or `None` when `path` is not an image, the image is too large, the `ocr`
643/// toggle is off, the `image-ocr` feature is off, no OCR model is installed, or
644/// nothing is recognised.
645///
646/// **OCR only.** The vision model used to compose a description into this string
647/// when OCR came back sparse; since ADR-0015 it does not, because a description
648/// is generated rather than decoded. OCR stays because it is discriminative: it
649/// reads text that is *actually present*, and its errors are misreadings a human
650/// can correct against the image. The VLM now runs from `roteiro media build`
651/// into [`crate::media`], where its output is labelled and opt-in.
652///
653/// This reads the *installed* OCR models — that runtime dependency is reflected
654/// in the cache key via [`media_env_tag`], so installing/upgrading a model
655/// re-extracts affected images instead of serving stale (content-free) facts.
656#[cfg(feature = "image-ocr")]
657fn image_content(path: &str, bytes: &[u8], ingest: IngestConfig) -> Option<String> {
658    if !ingest.ocr || !crate::media::is_image(path) || bytes.len() > crate::media::MAX_IMAGE_BYTES {
659        return None;
660    }
661    ocr_content(bytes)
662}
663
664/// No-op without `image-ocr`: images become plain file nodes. An `image-vision`
665/// build lands here too — since ADR-0015 the vision model contributes nothing to
666/// extraction.
667#[cfg(not(feature = "image-ocr"))]
668fn image_content(_path: &str, _bytes: &[u8], _ingest: IngestConfig) -> Option<String> {
669    None
670}
671
672/// Whether the image's pixel dimensions (read from its header, without decoding
673/// the pixels — so a decompression bomb is rejected cheaply) are within
674/// [`MAX_IMAGE_PIXELS`]. `false` if the header cannot be parsed or the limit is
675/// exceeded.
676///
677/// Shared with the vision producer in [`crate::media::producers`], which applies
678/// the same guard before loading the projector.
679#[cfg(any(feature = "image-ocr", feature = "image-vision"))]
680pub(crate) fn image_dimensions_ok(bytes: &[u8]) -> bool {
681    let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
682    else {
683        return false;
684    };
685    match reader.into_dimensions() {
686        Ok((w, h)) => u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS,
687        Err(_) => false,
688    }
689}
690
691/// OCR an image's text (or `None` when `image-ocr` is off, the models are not
692/// installed, the image is too large, or extraction yields nothing). The `ocrs`
693/// engine can panic on some inputs, so the call is panic-guarded.
694#[cfg(feature = "image-ocr")]
695fn ocr_content(bytes: &[u8]) -> Option<String> {
696    // Which OCR model *this repository* uses: `[models] ocr` if it pins one, else
697    // `ocrs-text` (Stage 33). A pin that cannot be honoured resolves to `None`
698    // and OCR goes inert, as it does for a model that is not installed;
699    // `roteiro config` is where the reason is stated, because `sync` walks a
700    // whole tree and repeating one configuration error per image would bury it.
701    let model = crate::model_choice::resolve(crate::model_choice::ModelTask::Ocr)
702        .ok()?
703        .model?;
704    let dir = crate::models::model_dir(model);
705    let detection = dir.join("text-detection.rten");
706    let recognition = dir.join("text-recognition.rten");
707    if !detection.exists() || !recognition.exists() || !image_dimensions_ok(bytes) {
708        // Models not installed → OCR is inert (run `roteiro model pull <model>`).
709        return None;
710    }
711    // Borrow `bytes` into the guarded closure — no need to clone the (up to
712    // 20 MiB) image. `&[u8]`/`&Path` are unwind-safe, so no `AssertUnwindSafe`.
713    let text = std::panic::catch_unwind(|| run_ocr(&detection, &recognition, bytes))
714        .ok()
715        .flatten()?;
716    (!text.trim().is_empty()).then_some(text)
717}
718
719/// Run detection + recognition over an image's bytes, returning its text.
720/// Fallible steps collapse to `None` (a bad image yields no content).
721#[cfg(feature = "image-ocr")]
722fn run_ocr(
723    detection: &std::path::Path,
724    recognition: &std::path::Path,
725    bytes: &[u8],
726) -> Option<String> {
727    use ocrs::{ImageSource, OcrEngine, OcrEngineParams};
728
729    let detection_model = rten::Model::load_file(detection).ok()?;
730    let recognition_model = rten::Model::load_file(recognition).ok()?;
731    let engine = OcrEngine::new(OcrEngineParams {
732        detection_model: Some(detection_model),
733        recognition_model: Some(recognition_model),
734        ..Default::default()
735    })
736    .ok()?;
737
738    let img = image::load_from_memory(bytes).ok()?.into_rgb8();
739    let source = ImageSource::from_bytes(img.as_raw(), img.dimensions()).ok()?;
740    let input = engine.prepare_input(source).ok()?;
741    engine.get_text(&input).ok()
742}
743
744/// Destroy the process-wide media engines (vision, ASR) that extraction loaded
745/// **and then** the llama.cpp backend they shared, returning whether anything was
746/// released.
747///
748/// Extraction loads each GGUF engine once and reuses it for the whole run
749/// (`vlm_engine` / `asr_engine`). Those engines own native llama.cpp/ggml state:
750/// on the Metal backend their GPU buffers stay registered in ggml-metal's device
751/// residency set until the engine is dropped, and if that has not happened by the
752/// time libc's C++ finalizers destroy ggml-metal's global device vector at
753/// `exit()`, `ggml_metal_rsets_free` asserts the set is empty and `abort()`s —
754/// a successful run exits 134 instead of 0 (issue #291).
755///
756/// So the engines are released **explicitly**, at a deterministic point that is
757/// still inside `main`. The `roteiro` binary does this through
758/// [`MediaEngineGuard`]; a library embedder that runs extraction should call this
759/// before its process exits. Idempotent, cheap, and a no-op when no engine was
760/// ever built (or when this build has no media features), so it is safe on every
761/// exit path.
762///
763/// Not a shutdown signal: an engine still borrowed by an in-flight extraction
764/// stays alive until that caller is done. Call it once the work is finished.
765///
766/// **Order matters, and is enforced rather than assumed.** Both engines share one
767/// process-wide llama.cpp backend (issue #296), which llama.cpp requires be freed
768/// *after* every model — so the backend is released last, here. It is not
769/// possible to get that wrong by editing this function: each engine holds an
770/// `Arc` on the backend, and `rto_llama::backend::release_shared_backend`
771/// declines while any handle is outstanding.
772// The return value is a fact about what happened, not a status to handle: exit
773// paths bind it to `_released` and move on, tests assert on it.
774#[must_use]
775pub fn release_media_engines() -> bool {
776    // Every step runs; none short-circuits the others.
777    let vision = release_vlm_engine();
778    let audio = release_asr_engine();
779    // Last, once the engines that borrowed it are gone.
780    let backend = release_llama_backend();
781    vision || audio || backend
782}
783
784/// Release the shared llama.cpp backend, or nothing in a build that has no
785/// llama.cpp at all.
786///
787/// A `serve`-only build reaches `rto-llama` without going through this crate, so
788/// `roteiro`'s `main` additionally holds a `rto_llama::backend::SharedBackendGuard`;
789/// both call the same idempotent release, and each covers the builds the other
790/// cannot see.
791#[cfg(any(feature = "image-vision", feature = "audio-transcribe"))]
792fn release_llama_backend() -> bool {
793    rto_llama::backend::release_shared_backend()
794}
795
796#[cfg(not(any(feature = "image-vision", feature = "audio-transcribe")))]
797fn release_llama_backend() -> bool {
798    false
799}
800
801/// Release the vision engine, or nothing in a build without `image-vision`.
802///
803/// The engine itself moved to [`crate::media::producers`] along with the
804/// generation it serves (ADR-0015). The *release* stays here, because this is the
805/// entry point `roteiro`'s `main` holds for the whole process, and splitting it
806/// would make the exit ordering (#291, #296) something two modules had to agree
807/// on rather than something one function states.
808fn release_vlm_engine() -> bool {
809    crate::media::producers::release_vlm_engine()
810}
811
812/// Release the ASR engine, or nothing in a build without `audio-transcribe`.
813fn release_asr_engine() -> bool {
814    crate::media::producers::release_asr_engine()
815}
816
817/// Ties the lifetime of the process-wide media engines — and, after them, the
818/// llama.cpp backend they share — to a scope: dropping the guard runs
819/// [`release_media_engines`].
820///
821/// Held for the whole of `roteiro`'s `main`, so the engines are destroyed while
822/// Rust is still running destructors — before the C++ finalizers that would
823/// otherwise abort the process (issue #291) — on the normal path, on an early
824/// `?` error, and on an unwinding panic alike.
825///
826/// `std::process::exit` skips destructors, so any path that exits that way must
827/// call [`release_media_engines`] itself first.
828#[derive(Debug)]
829pub struct MediaEngineGuard {
830    // A private field keeps the guard un-constructible except through `hold`,
831    // so it cannot be created (and dropped) by accident mid-run.
832    _private: (),
833}
834
835impl MediaEngineGuard {
836    /// Take ownership of the process-wide media engines for this scope.
837    #[must_use]
838    pub const fn hold() -> Self {
839        Self { _private: () }
840    }
841}
842
843impl Drop for MediaEngineGuard {
844    fn drop(&mut self) {
845        // Whether anything was resident is of no consequence here — the point is
846        // that nothing is, from now on.
847        let _released = release_media_engines();
848    }
849}
850
851// Mirror of the `ocr_content` stub: needed only when the image path is compiled
852// (image-ocr on) with image-vision off, not in an audio-only build.
853#[cfg(all(feature = "image-ocr", not(feature = "image-vision")))]
854fn vlm_content(_bytes: &[u8]) -> Option<String> {
855    None
856}
857
858/// A cache-key component reflecting the **extraction** models' runtime
859/// environment: `0` when no extraction model feature is on or no model is
860/// installed, else a hash of the installed OCR model identity. Folded into the
861/// sync cache key so installing/upgrading a model re-extracts affected images
862/// instead of serving stale facts (OCR output is not a pure function of the blob
863/// alone). See [`crate::sync`].
864///
865/// Only OCR is folded in. The vision and audio models used to be, because they
866/// wrote into `meta.content`; since ADR-0015 they do not, so their presence
867/// changes no derived fact and must not perturb a cache key. A machine that
868/// installs Voxtral no longer re-extracts its whole tree.
869///
870/// The model folded in is the **resolved** one, not the built-in default:
871/// repointing `[models] ocr` changes what extraction reads out of an image, so it
872/// has to move the cache key too, or the repository would keep serving text read
873/// by the model it no longer uses. With the key unset this is byte-identical to
874/// what it was before — the resolver returns `ocrs-text`.
875#[cfg(feature = "image-ocr")]
876pub(crate) fn media_env_tag() -> u64 {
877    let Some(model) = crate::model_choice::resolve(crate::model_choice::ModelTask::Ocr)
878        .ok()
879        .and_then(|choice| choice.model)
880    else {
881        return 0;
882    };
883    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
884    if fold_installed_model(&mut hash, model) {
885        hash | 1
886    } else {
887        0
888    }
889}
890
891/// If model `name` is fully installed, fold its host-variant checksums into
892/// `hash` and return `true`. Only the host-selected variant is hashed, so an
893/// unrelated platform variant does not perturb this host's tag.
894#[cfg(feature = "image-ocr")]
895fn fold_installed_model(hash: &mut u64, name: &str) -> bool {
896    let Some(variant) = crate::models::find(name)
897        .and_then(|spec| spec.variant_for(crate::models::Platform::host()))
898    else {
899        return false;
900    };
901    let dir = crate::models::model_dir(name);
902    if !variant.files.iter().all(|f| dir.join(f.name).exists()) {
903        return false;
904    }
905    for file in variant.files {
906        for b in file.sha256.bytes() {
907            *hash ^= u64::from(b);
908            *hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
909        }
910    }
911    true
912}
913
914/// `0` whenever no extraction-model feature is compiled in.
915#[cfg(not(feature = "image-ocr"))]
916pub(crate) fn media_env_tag() -> u64 {
917    0
918}
919
920/// Whether `path` is a prose file whose body is worth embedding.
921///
922/// Public because the *extension list is the definition* and a second copy of it
923/// would drift: the Obsidian renderer's call site (`roteiro render obsidian`)
924/// reads a prose file's full source at render time, and it has to select exactly
925/// the blobs this predicate admitted at extraction time. Nothing about the
926/// judgement itself is exported — only the answer.
927#[must_use]
928pub fn is_prose(path: &str) -> bool {
929    matches!(
930        extension(path).as_deref(),
931        Some("md" | "markdown" | "txt" | "rst" | "adoc")
932    )
933}
934
935/// Trim and cap `text` to [`MAX_CONTENT`] characters (whitespace-collapsed), so
936/// stored content stays small and deterministic.
937///
938/// Public because the *budget is the definition*, and a second copy of it would
939/// drift. The authored layer (`rto-spec`) stores an ADR's section text on its
940/// `adr`/`adr_section` nodes so `search` and `explain` can reach it, and that text
941/// has to be bounded by the same rule the derived layer uses — otherwise the
942/// exportable store grows by whichever cap was written down last. This is not an
943/// extraction path and needs no [`EXTRACT_VERSION`] bump: the authored layer is
944/// re-parsed from blobs on every sync rather than served from the
945/// content-addressed extraction cache.
946#[must_use]
947pub fn cap_content(text: &str) -> String {
948    let mut out = String::with_capacity(text.len().min(MAX_CONTENT));
949    // Track the character count incrementally — `out.chars().count()` per
950    // iteration would make this O(n²) on long inputs.
951    let mut chars = 0usize;
952    let mut last_was_space = true;
953    for c in text.chars() {
954        if chars >= MAX_CONTENT {
955            break;
956        }
957        if c.is_whitespace() {
958            if !last_was_space {
959                out.push(' ');
960                chars += 1;
961                last_was_space = true;
962            }
963        } else {
964            out.push(c);
965            chars += 1;
966            last_was_space = false;
967        }
968    }
969    out.trim().to_owned()
970}
971
972/// Fallback extractor: emits a single `file` node per blob, tagged with its blob
973/// hash and basic size metadata. Produces no edges. Used for files with no
974/// registered language.
975#[derive(Debug, Clone, Copy, Default)]
976pub struct FileNodeExtractor;
977
978impl Extractor for FileNodeExtractor {
979    fn extract(&self, path: &str, blob_id: &str, bytes: &[u8]) -> FactSet {
980        FactSet::new().with_node(file_node(
981            path,
982            blob_id,
983            bytes,
984            None,
985            IngestConfig::default(),
986        ))
987    }
988}
989
990/// Derived extractor for Rust source, backed by tree-sitter. Emits a `file`
991/// node, one symbol node per `fn`/`struct`/`enum`/`trait`/`mod` (and a few
992/// others) with `defines`/`contains` edges reflecting lexical nesting, and
993/// `imports` edges for `use` declarations. Each function records the (optionally
994/// scope-qualified) names it calls in `meta.calls` for later cross-file
995/// resolution — see [`RustWalk::callee_name`].
996#[derive(Debug, Clone, Copy, Default)]
997pub struct RustExtractor;
998
999impl Extractor for RustExtractor {
1000    fn extract(&self, path: &str, blob_id: &str, bytes: &[u8]) -> FactSet {
1001        rust_facts(path, blob_id, bytes, IngestConfig::default())
1002    }
1003}
1004
1005/// Extract Rust facts, applying `ingest` to the file node's embedded content.
1006/// Shared by [`RustExtractor`] (default toggles) and [`Registry`] (its config).
1007fn rust_facts(path: &str, blob_id: &str, bytes: &[u8], ingest: IngestConfig) -> FactSet {
1008    let mut parser = tree_sitter::Parser::new();
1009    // The Rust grammar is compiled in, so this only fails on a version
1010    // mismatch — a build-time invariant, not a runtime input error.
1011    if parser
1012        .set_language(&tree_sitter_rust::LANGUAGE.into())
1013        .is_err()
1014    {
1015        return FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest));
1016    }
1017    let Some(tree) = parser.parse(bytes, None) else {
1018        return FactSet::new().with_node(file_node(path, blob_id, bytes, None, ingest));
1019    };
1020
1021    let mut walk = RustWalk {
1022        path,
1023        blob_id,
1024        src: bytes,
1025        nodes: vec![file_node(path, blob_id, bytes, Some("rust"), ingest)],
1026        edges: Vec::new(),
1027    };
1028    let root = tree.root_node();
1029    let mut cursor = root.walk();
1030    let children: Vec<_> = root.children(&mut cursor).collect();
1031    for child in children {
1032        walk.visit(child, &[]);
1033    }
1034    // Synthesize `config_key` nodes from any `@rto:config`-marked config-root struct
1035    // (ADR-0009): a code-defined config becomes matchable dotted keys without a
1036    // committed `*-example.toml` mirror. Runs after the walk so every struct in the
1037    // file is available to resolve nested field types.
1038    walk.synthesize_config_keys(root);
1039
1040    // Deterministic ordering so the cached fact set is byte-stable regardless of
1041    // traversal incidentals.
1042    walk.nodes.sort_by(|a, b| a.key.cmp(&b.key));
1043    walk.edges
1044        .sort_by(|a, b| (a.kind.as_str(), &a.src, &a.dst).cmp(&(b.kind.as_str(), &b.src, &b.dst)));
1045    FactSet {
1046        nodes: walk.nodes,
1047        edges: walk.edges,
1048    }
1049}
1050
1051/// One entry on the lexical scope stack: a name segment and, when the scope is
1052/// itself an emitted symbol, that symbol's key (impl blocks contribute a segment
1053/// but no node, so their `key` is `None`).
1054struct Scope {
1055    seg: String,
1056    key: Option<String>,
1057}
1058
1059/// One declared struct field: its name and the `type_identifier` tokens of its
1060/// type (outermost first). See [`RustWalk::struct_fields`].
1061struct FieldDef {
1062    name: String,
1063    type_idents: Vec<String>,
1064}
1065
1066/// Single-value **transparent** wrappers whose inner type is the "real" field type
1067/// for config purposes — a `zerobus: Option<ZerobusConfig>` still nests into
1068/// `ZerobusConfig`. Peeled by [`core_type_name`] / [`recursion_target`].
1069const TRANSPARENT_WRAPPERS: &[&str] = &[
1070    "Option", "Box", "Arc", "Rc", "Cow", "RefCell", "Cell", "Mutex", "RwLock",
1071];
1072
1073/// **Collection** wrappers: a `Vec<ItemConfig>` / `HashMap<_, _>` field serialises
1074/// to an array/table keyed by *runtime* index/key, not by nested struct fields, so
1075/// synthesis stops at the field itself (one leaf key) rather than inventing dotted
1076/// paths under it. Detecting one anywhere in a field's type makes it a leaf.
1077const COLLECTION_WRAPPERS: &[&str] = &[
1078    "Vec", "VecDeque", "HashMap", "BTreeMap", "HashSet", "BTreeSet", "IndexMap",
1079];
1080
1081/// The field's **core type name** for `meta.field_types`: the first type token that
1082/// is not a [`TRANSPARENT_WRAPPERS`] wrapper (so `Option<ZerobusConfig>` →
1083/// `ZerobusConfig`, `String` → `String`), or the outermost token if a wrapper is
1084/// all there is. `None` for a type with no identifier (a bare reference, tuple, …).
1085fn core_type_name(type_idents: &[String]) -> Option<String> {
1086    type_idents
1087        .iter()
1088        .find(|t| !TRANSPARENT_WRAPPERS.contains(&t.as_str()))
1089        .or_else(|| type_idents.first())
1090        .cloned()
1091}
1092
1093/// The struct name a field should **recurse into**, given the structs known in this
1094/// file (`known`), or `None` when the field is a config leaf. A collection wrapper
1095/// anywhere short-circuits to a leaf; transparent wrappers are peeled; the first
1096/// remaining token nests only if it names a known struct.
1097fn recursion_target<'a>(
1098    type_idents: &'a [String],
1099    known: &std::collections::BTreeMap<String, StructDef>,
1100) -> Option<&'a str> {
1101    for t in type_idents {
1102        if COLLECTION_WRAPPERS.contains(&t.as_str()) {
1103            return None;
1104        }
1105        if TRANSPARENT_WRAPPERS.contains(&t.as_str()) {
1106            continue;
1107        }
1108        return known.contains_key(t).then_some(t.as_str());
1109    }
1110    None
1111}
1112
1113/// A struct discovered in the file for config synthesis: its fields and whether it
1114/// carries the `@rto:config` root marker.
1115struct StructDef {
1116    fields: Vec<FieldDef>,
1117    is_root: bool,
1118}
1119
1120/// Guard against a pathological or cyclic type graph producing unbounded keys.
1121const MAX_CONFIG_DEPTH: usize = 16;
1122
1123/// Recursively expand a config struct into its dotted **leaf** keys. A field that
1124/// resolves to another known struct ([`recursion_target`]) descends with the field
1125/// name appended to `prefix`; every other field is a leaf recorded in `out`
1126/// (first-writer wins, tagged with the originating `root` for provenance). `visited`
1127/// tracks the current descent path so a cyclic type graph terminates (the cyclic
1128/// field falls back to a leaf) rather than recursing forever.
1129fn expand_config_keys(
1130    table: &std::collections::BTreeMap<String, StructDef>,
1131    struct_name: &str,
1132    prefix: &str,
1133    root: &str,
1134    visited: &mut std::collections::BTreeSet<String>,
1135    depth: usize,
1136    out: &mut std::collections::BTreeMap<String, String>,
1137) {
1138    let Some(def) = table.get(struct_name) else {
1139        return;
1140    };
1141    for f in &def.fields {
1142        let key = if prefix.is_empty() {
1143            f.name.clone()
1144        } else {
1145            format!("{prefix}.{}", f.name)
1146        };
1147        match recursion_target(&f.type_idents, table) {
1148            Some(inner) if depth < MAX_CONFIG_DEPTH && !visited.contains(inner) => {
1149                visited.insert(inner.to_owned());
1150                expand_config_keys(table, inner, &key, root, visited, depth + 1, out);
1151                visited.remove(inner);
1152            }
1153            _ => {
1154                out.entry(key).or_insert_with(|| root.to_owned());
1155            }
1156        }
1157    }
1158}
1159
1160/// Accumulating state for a single Rust file walk.
1161struct RustWalk<'a> {
1162    path: &'a str,
1163    blob_id: &'a str,
1164    src: &'a [u8],
1165    nodes: Vec<Node>,
1166    edges: Vec<Edge>,
1167}
1168
1169impl RustWalk<'_> {
1170    /// Visit one AST node under the given lexical scope stack.
1171    fn visit(&mut self, node: tree_sitter::Node, scope: &[Scope]) {
1172        match node.kind() {
1173            "function_item" => self.visit_symbol(node, scope, NodeKind::Fn, true),
1174            "struct_item" | "union_item" => self.visit_symbol(node, scope, NodeKind::Struct, false),
1175            "enum_item" => self.visit_symbol(node, scope, NodeKind::Enum, false),
1176            "trait_item" => self.visit_symbol(node, scope, NodeKind::Trait, false),
1177            "mod_item" => self.visit_symbol(node, scope, NodeKind::Module, false),
1178            "type_item" => self.visit_symbol(node, scope, NodeKind::Other("type".into()), false),
1179            "macro_definition" => {
1180                self.visit_symbol(node, scope, NodeKind::Other("macro".into()), false);
1181            }
1182            "impl_item" => self.visit_impl(node, scope),
1183            "use_declaration" => self.visit_use(node),
1184            // Recurse through unnamed structural wrappers (e.g. the top-level
1185            // `declaration_list` of a module handled in `visit_symbol`).
1186            _ => self.visit_children(node, scope),
1187        }
1188    }
1189
1190    /// Visit every named child of `node` under the same scope.
1191    fn visit_children(&mut self, node: tree_sitter::Node, scope: &[Scope]) {
1192        let mut cursor = node.walk();
1193        let children: Vec<_> = node.named_children(&mut cursor).collect();
1194        for child in children {
1195            self.visit(child, scope);
1196        }
1197    }
1198
1199    /// Emit a symbol node for a named definition, link it to its containing
1200    /// scope, and recurse into its body for nested definitions.
1201    fn visit_symbol(
1202        &mut self,
1203        node: tree_sitter::Node,
1204        scope: &[Scope],
1205        kind: NodeKind,
1206        collect_calls: bool,
1207    ) {
1208        let Some(name) = self.field_text(node, "name") else {
1209            return self.visit_children(node, scope);
1210        };
1211        let qualified = qualify(scope, &name);
1212        let key = format!("sym:rust:{}#{qualified}", self.path);
1213
1214        let mut meta = serde_json::Map::new();
1215        if collect_calls {
1216            let mut calls = Vec::new();
1217            self.collect_calls(node, &mut calls);
1218            calls.sort();
1219            calls.dedup();
1220            if !calls.is_empty() {
1221                meta.insert("calls".into(), serde_json::Value::from(calls));
1222            }
1223        }
1224        // Capture the item's doc-comment so inference embeds what it *means*.
1225        if let Some(doc) = self.doc_comment(node) {
1226            meta.insert("content".into(), serde_json::Value::from(doc));
1227        }
1228        // A struct/union records its NAMED field identifiers in `meta.fields` — the
1229        // signal the config_key→struct follow bridge joins on (a dotted config key's
1230        // leaf, e.g. `serve.addr`'s `addr`, must be a real field of the matched
1231        // struct before we bridge to it). Tuple/unit structs have no named fields
1232        // and add nothing; the key is omitted rather than emitted empty. Alongside,
1233        // `meta.field_types` maps each named field to its **core type name** (wrapper
1234        // types like `Option`/`Box` peeled — see [`core_type_name`]) so a later,
1235        // cross-file synthesizer can descend into nested config structs from the
1236        // stored graph alone; `meta.config_root` marks a struct authored with the
1237        // `@rto:config` signal as the root of a config tree (see
1238        // [`RustWalk::synthesize_config_keys`]).
1239        if matches!(node.kind(), "struct_item" | "union_item") {
1240            let defs = self.struct_fields(node);
1241            if !defs.is_empty() {
1242                let names: Vec<&str> = defs.iter().map(|f| f.name.as_str()).collect();
1243                meta.insert("fields".into(), serde_json::Value::from(names));
1244                let types: serde_json::Map<String, serde_json::Value> = defs
1245                    .iter()
1246                    .filter_map(|f| {
1247                        core_type_name(&f.type_idents).map(|t| (f.name.clone(), t.into()))
1248                    })
1249                    .collect();
1250                if !types.is_empty() {
1251                    meta.insert("field_types".into(), serde_json::Value::Object(types));
1252                }
1253            }
1254            if self.has_config_marker(node) {
1255                meta.insert("config_root".into(), serde_json::Value::Bool(true));
1256            }
1257        }
1258
1259        self.nodes.push(Node {
1260            key: key.clone(),
1261            kind,
1262            name,
1263            path: Some(self.path.to_owned()),
1264            lang: Some("rust".to_owned()),
1265            blob_hash: Some(self.blob_id.to_owned()),
1266            span: Some(span(node)),
1267            provenance: Provenance::Derived,
1268            meta: serde_json::Value::Object(meta),
1269        });
1270        self.link_parent(&key, scope);
1271
1272        // Recurse into the body so nested items (a fn in a mod, etc.) are found,
1273        // pushing this symbol onto the scope stack.
1274        let child_scope = extend(scope, &self.simple(node, "name"), Some(key));
1275        self.recurse_body(node, &child_scope);
1276    }
1277
1278    /// The doc-comment (`///` / `//!` / `/** … */`) immediately preceding `node`,
1279    /// concatenated, or `None`. Attributes between the comment and the item are
1280    /// skipped; a non-doc comment (or any other node) ends the block.
1281    fn doc_comment(&self, node: tree_sitter::Node) -> Option<String> {
1282        let mut parts: Vec<String> = Vec::new();
1283        let mut prev = node.prev_sibling();
1284        while let Some(n) = prev {
1285            match n.kind() {
1286                "line_comment" | "block_comment" => match doc_comment_body(self.text(n)) {
1287                    Some(body) => {
1288                        parts.push(body);
1289                        prev = n.prev_sibling();
1290                    }
1291                    None => break,
1292                },
1293                "attribute_item" => prev = n.prev_sibling(),
1294                _ => break,
1295            }
1296        }
1297        if parts.is_empty() {
1298            return None;
1299        }
1300        parts.reverse();
1301        let joined = cap_content(&parts.join(" "));
1302        (!joined.is_empty()).then_some(joined)
1303    }
1304
1305    /// An `impl` block emits no node but contributes its type name as a scope
1306    /// segment, so methods qualify as `Type::method`.
1307    fn visit_impl(&mut self, node: tree_sitter::Node, scope: &[Scope]) {
1308        let type_name = self
1309            .field_text(node, "type")
1310            .unwrap_or_else(|| "impl".to_owned());
1311        let child_scope = extend(scope, &type_name, None);
1312        self.recurse_body(node, &child_scope);
1313    }
1314
1315    /// Record a `use` declaration as an `imports` edge from the file to an
1316    /// import-target node keyed by the (whitespace-normalised) import path.
1317    fn visit_use(&mut self, node: tree_sitter::Node) {
1318        let Some(arg) = node.child_by_field_name("argument") else {
1319            return;
1320        };
1321        let text: String = self
1322            .text(arg)
1323            .chars()
1324            .filter(|c| !c.is_whitespace())
1325            .collect();
1326        if text.is_empty() {
1327            return;
1328        }
1329        let key = format!("import:rust:{text}");
1330        self.nodes.push(Node {
1331            key: key.clone(),
1332            kind: NodeKind::Other("import".into()),
1333            name: text,
1334            path: None,
1335            lang: Some("rust".to_owned()),
1336            blob_hash: None,
1337            span: None,
1338            provenance: Provenance::Derived,
1339            meta: serde_json::Value::Null,
1340        });
1341        self.edges
1342            .push(Edge::derived(file_key(self.path), key, EdgeKind::Imports));
1343    }
1344
1345    /// Link a freshly-emitted symbol to its nearest enclosing emitted scope:
1346    /// `contains` from that symbol, or `defines` from the file at top level.
1347    fn link_parent(&mut self, key: &str, scope: &[Scope]) {
1348        if let Some(parent) = scope.iter().rev().find_map(|s| s.key.as_deref()) {
1349            self.edges.push(Edge::derived(
1350                parent.to_owned(),
1351                key.to_owned(),
1352                EdgeKind::Contains,
1353            ));
1354        } else {
1355            self.edges.push(Edge::derived(
1356                file_key(self.path),
1357                key.to_owned(),
1358                EdgeKind::Defines,
1359            ));
1360        }
1361    }
1362
1363    /// The NAMED fields a struct/union declares, in source order — each an entry of
1364    /// its `field_declaration_list` carrying the declared field name plus the
1365    /// type-identifier tokens of its type (outermost first, e.g.
1366    /// `Option<ZerobusConfig>` → `["Option", "ZerobusConfig"]`). A tuple struct's
1367    /// positional fields carry no `name`, and a unit struct has no field list, so
1368    /// both contribute nothing.
1369    fn struct_fields(&self, node: tree_sitter::Node) -> Vec<FieldDef> {
1370        let mut out = Vec::new();
1371        let mut cursor = node.walk();
1372        for child in node.named_children(&mut cursor) {
1373            if child.kind() == "field_declaration_list" {
1374                let mut inner = child.walk();
1375                for field in child.named_children(&mut inner) {
1376                    if field.kind() == "field_declaration"
1377                        && let Some(name) = field.child_by_field_name("name")
1378                    {
1379                        let type_idents = field
1380                            .child_by_field_name("type")
1381                            .map(|t| self.type_idents(t))
1382                            .unwrap_or_default();
1383                        out.push(FieldDef {
1384                            name: self.text(name).to_owned(),
1385                            type_idents,
1386                        });
1387                    }
1388                }
1389            }
1390        }
1391        out
1392    }
1393
1394    /// Every `type_identifier` token in a type subtree, outermost first — so a
1395    /// generic like `Option<Vec<Inner>>` yields `["Option", "Vec", "Inner"]`. The
1396    /// order lets [`core_type_name`] / [`recursion_target`] peel transparent
1397    /// wrappers and stop at a collection.
1398    fn type_idents(&self, ty: tree_sitter::Node) -> Vec<String> {
1399        let mut out = Vec::new();
1400        self.collect_type_idents(ty, &mut out);
1401        out
1402    }
1403
1404    fn collect_type_idents(&self, node: tree_sitter::Node, out: &mut Vec<String>) {
1405        // A named type (`ZerobusConfig`, `String`) or a primitive (`u32`, `bool`) —
1406        // both are field-type tokens; primitives never name a struct, so they only
1407        // ever resolve to a leaf, but they make `meta.field_types` complete.
1408        if matches!(node.kind(), "type_identifier" | "primitive_type") {
1409            out.push(self.text(node).to_owned());
1410        }
1411        let mut cursor = node.walk();
1412        for child in node.named_children(&mut cursor) {
1413            self.collect_type_idents(child, out);
1414        }
1415    }
1416
1417    /// Whether an authored **`@rto:config`** marker precedes `node` — the explicit,
1418    /// opt-in signal that a struct is the root of a config tree
1419    /// [`RustWalk::synthesize_config_keys`] may expand. Scans the immediately
1420    /// preceding run of comments (`//`, `///`, `//!`, or `/* … */` block comments)
1421    /// and attributes, returning `true` as soon as any of them contains the marker
1422    /// token; the first node that is not a comment or attribute ends the run. Unlike
1423    /// [`doc_comment`] this does not require the comments to be *doc* comments and
1424    /// does not stop at a plain `//` comment — a bare `// @rto:config` line is
1425    /// accepted. Requiring an authored marker keeps synthesis conservative — a
1426    /// struct is never guessed to be config.
1427    fn has_config_marker(&self, node: tree_sitter::Node) -> bool {
1428        const MARKER: &str = "@rto:config";
1429        let mut prev = node.prev_sibling();
1430        while let Some(n) = prev {
1431            match n.kind() {
1432                "line_comment" | "block_comment" | "attribute_item" => {
1433                    if self.text(n).contains(MARKER) {
1434                        return true;
1435                    }
1436                    prev = n.prev_sibling();
1437                }
1438                _ => break,
1439            }
1440        }
1441        false
1442    }
1443
1444    /// Recurse into the `declaration_list` / body of a definition.
1445    fn recurse_body(&mut self, node: tree_sitter::Node, scope: &[Scope]) {
1446        let mut cursor = node.walk();
1447        let children: Vec<_> = node.named_children(&mut cursor).collect();
1448        for child in children {
1449            match child.kind() {
1450                "declaration_list" | "field_declaration_list" | "trait_body" => {
1451                    self.visit_children(child, scope);
1452                }
1453                _ => {}
1454            }
1455        }
1456    }
1457
1458    /// Collect the simple names of functions called anywhere within `node`'s
1459    /// subtree (used for later call resolution).
1460    fn collect_calls(&self, node: tree_sitter::Node, out: &mut Vec<String>) {
1461        let mut cursor = node.walk();
1462        for child in node.named_children(&mut cursor) {
1463            if child.kind() == "call_expression"
1464                && let Some(func) = child.child_by_field_name("function")
1465                && let Some(name) = self.callee_name(func)
1466            {
1467                out.push(name);
1468            }
1469            self.collect_calls(child, out);
1470        }
1471    }
1472
1473    /// A callee descriptor for a `call_expression`'s function child, keeping the
1474    /// *immediate* qualifier when the syntax supplies one so [`crate::sync`] can
1475    /// resolve scope-aware (not just by unique simple name):
1476    /// - `foo()` → `foo` (unqualified)
1477    /// - `a::b::foo()` → `b::foo` (immediate module/type qualifier)
1478    /// - `Type::assoc()` → `Type::assoc`
1479    /// - `self.foo()` / `Self::foo()` → `Self::foo` (a same-impl method call,
1480    ///   resolved via the caller's own type)
1481    /// - `x.foo()` on a non-`self` receiver → `foo` (the receiver's type is
1482    ///   unknown without type inference, so no qualifier is claimed)
1483    fn callee_name(&self, func: tree_sitter::Node) -> Option<String> {
1484        match func.kind() {
1485            "identifier" => Some(self.text(func).to_owned()),
1486            "scoped_identifier" => {
1487                let name = func.child_by_field_name("name")?;
1488                // The immediate qualifier is the last segment of the `path` child
1489                // (`a::b` → `b`), which most closely scopes the call.
1490                let qualifier = func
1491                    .child_by_field_name("path")
1492                    .and_then(|p| self.text(p).rsplit("::").next().map(str::to_owned));
1493                Some(qualify_callee(qualifier.as_deref(), self.text(name)))
1494            }
1495            "field_expression" => {
1496                let name = func.child_by_field_name("field")?;
1497                // A call on the `self` receiver targets a method of the caller's
1498                // own impl type; mark it `Self` so the resolver can bind it.
1499                let on_self = func
1500                    .child_by_field_name("value")
1501                    .is_some_and(|v| self.text(v) == "self");
1502                Some(qualify_callee(on_self.then_some("Self"), self.text(name)))
1503            }
1504            _ => None,
1505        }
1506    }
1507
1508    /// Synthesize `config_key` nodes from any **config-root** struct in this file —
1509    /// a struct authored with the `@rto:config` marker (see [`has_config_marker`]).
1510    /// Its declared fields are walked recursively, descending into nested
1511    /// struct-typed fields (resolved by name against the other structs in *this
1512    /// file*), and each config **leaf** becomes a `config_key` node keyed
1513    /// `cfgkey:<path>#<dotted>` — so a code-defined config (`zerobus: ZerobusConfig`
1514    /// with `server_endpoint: String`) yields `zerobus.server_endpoint` **without** a
1515    /// committed `*-example.toml` mirror. The nodes carry `meta.source = "struct"`
1516    /// (and `meta.struct = <root>`) so they stay distinguishable from file-derived
1517    /// keys, while sharing the `config_key` kind so they flow through
1518    /// `Store::config_keys` → `links --infer`/`--matrix`/the explorer unchanged.
1519    ///
1520    /// Deliberately conservative and additive: nothing is emitted unless a root is
1521    /// explicitly marked. Field names are used verbatim as dotted segments; the
1522    /// cross-convention matcher ([`crate::canonicalize_config_key`]) already bridges
1523    /// a `snake_case` field to a `camelCase`/`kebab` infra key, so `serde`
1524    /// `rename_all` conventions match without being parsed here.
1525    ///
1526    /// Known limits (documented, deferred): recursion resolves nested structs by
1527    /// name **within this file only** (a config struct split across modules/files is
1528    /// not descended — those leaves simply stay unsynthesized, as today); an explicit
1529    /// `#[serde(rename = "...")]` to an unrelated spelling is not applied; and
1530    /// collection-typed fields (`Vec`/`Map`) are one leaf, not indexed paths.
1531    fn synthesize_config_keys(&mut self, root: tree_sitter::Node) {
1532        let table = self.collect_struct_defs(root);
1533        // key → the root struct name that produced it (first root wins; deterministic
1534        // because `table` iterates roots by name).
1535        let mut keys: std::collections::BTreeMap<String, String> =
1536            std::collections::BTreeMap::new();
1537        for (name, def) in &table {
1538            if !def.is_root {
1539                continue;
1540            }
1541            let mut visited = std::collections::BTreeSet::new();
1542            visited.insert(name.clone());
1543            expand_config_keys(&table, name, "", name, &mut visited, 0, &mut keys);
1544        }
1545        let file = file_key(self.path);
1546        for (dotted, root_name) in keys {
1547            let node_key = format!("cfgkey:{}#{dotted}", self.path);
1548            let mut node = Node::new(
1549                node_key.clone(),
1550                NodeKind::Other(crate::config_keys::KIND.into()),
1551                dotted.clone(),
1552            );
1553            node.path = Some(self.path.to_owned());
1554            node.blob_hash = Some(self.blob_id.to_owned());
1555            // A struct field declares no literal value, so `meta.value` is OMITTED
1556            // (not `""`): the store reader surfaces this as `value_known = false` so
1557            // value-agreement matching treats the value as *unknown*, never as an
1558            // empty string that could false-match a spoke's genuine empty value.
1559            // `source`/`struct` mark the provenance and keep these distinguishable
1560            // from file-derived config keys.
1561            node.meta = serde_json::json!({
1562                "key": dotted,
1563                "source": "struct",
1564                "struct": root_name,
1565            });
1566            self.edges.push(Edge::derived(
1567                file.clone(),
1568                node_key.clone(),
1569                EdgeKind::Contains,
1570            ));
1571            self.nodes.push(node);
1572        }
1573    }
1574
1575    /// Index every struct/union in the file by its **simple name** (first
1576    /// declaration wins on a collision) for config synthesis — recording its fields,
1577    /// its node key, and whether it is a `@rto:config` root.
1578    fn collect_struct_defs(
1579        &self,
1580        root: tree_sitter::Node,
1581    ) -> std::collections::BTreeMap<String, StructDef> {
1582        let mut out = std::collections::BTreeMap::new();
1583        self.collect_struct_defs_into(root, &mut out);
1584        out
1585    }
1586
1587    fn collect_struct_defs_into(
1588        &self,
1589        node: tree_sitter::Node,
1590        out: &mut std::collections::BTreeMap<String, StructDef>,
1591    ) {
1592        if matches!(node.kind(), "struct_item" | "union_item")
1593            && let Some(name) = self.field_text(node, "name")
1594        {
1595            out.entry(name.clone()).or_insert_with(|| StructDef {
1596                fields: self.struct_fields(node),
1597                is_root: self.has_config_marker(node),
1598            });
1599        }
1600        let mut cursor = node.walk();
1601        for child in node.named_children(&mut cursor) {
1602            self.collect_struct_defs_into(child, out);
1603        }
1604    }
1605
1606    fn text(&self, node: tree_sitter::Node) -> &str {
1607        node.utf8_text(self.src).unwrap_or("")
1608    }
1609
1610    fn field_text(&self, node: tree_sitter::Node, field: &str) -> Option<String> {
1611        node.child_by_field_name(field)
1612            .map(|n| self.text(n).to_owned())
1613    }
1614
1615    fn simple(&self, node: tree_sitter::Node, field: &str) -> String {
1616        self.field_text(node, field).unwrap_or_default()
1617    }
1618}
1619
1620// ======================= Generic tags-query extraction =======================
1621//
1622// One extractor drives every non-Rust language through its tree-sitter `tags.scm`
1623// query (the `@definition.*` / `@reference.*` capture convention). It emits the
1624// same fact shape as the Rust walker — a `file` node, one symbol node per
1625// definition with `defines`/`contains` edges reflecting byte-range nesting, and
1626// each function's callee simple-names in `meta.calls` — so cross-file (and
1627// cross-language) call resolution in `crate::sync` works uniformly. Where the
1628// language has an import query (`import_query_for`), it also emits `imports`
1629// edges (`file → import` target), as the Rust walker does for `use`. A new
1630// language is a row in `tag_lang_for` (and optionally `import_query_for`), not
1631// new code.
1632
1633/// A language dispatched to the generic tags extractor: its label, grammar, and
1634/// `tags.scm` source (from the grammar crate, or vendored under `src/queries/`).
1635struct TagLang {
1636    /// Canonical label — the node `lang` and the `sym:<lang>:` key namespace.
1637    lang: &'static str,
1638    /// Cache key identifying the *grammar* (not just the label): one `lang` can
1639    /// map to more than one grammar — OCaml `.ml` and `.mli` are both `"ocaml"`
1640    /// but use distinct grammars — so the config cache must key on this, not
1641    /// `lang`, to avoid parsing one grammar's blobs with another's parser.
1642    grammar_key: &'static str,
1643    /// The tree-sitter grammar.
1644    language: tree_sitter::Language,
1645    /// The `tags.scm` query source. Usually borrowed from the grammar crate's
1646    /// const; owned when it is assembled (TypeScript's query `inherits` the
1647    /// JavaScript one, which the crate's `TAGS_QUERY` const does not concatenate).
1648    query: std::borrow::Cow<'static, str>,
1649}
1650
1651/// Resolve a lowercase file extension to its tags-extractor language, or `None`
1652/// when no generic extractor handles it (the caller then falls back to a plain
1653/// file node). Rust is intentionally absent — it keeps its richer AST walker.
1654// A flat extension→grammar dispatch table; length is inherent to the breadth.
1655#[allow(clippy::too_many_lines)]
1656fn tag_lang_for(ext: &str) -> Option<TagLang> {
1657    use std::borrow::Cow;
1658    // TypeScript's tags query `inherits` JavaScript's; the crate const ships only
1659    // the TS-specific supplement, so concatenate the two. The JavaScript patterns
1660    // match against the TypeScript superset grammar.
1661    let ts_query = || -> Cow<'static, str> {
1662        Cow::Owned(format!(
1663            "{}\n{}",
1664            tree_sitter_javascript::TAGS_QUERY,
1665            tree_sitter_typescript::TAGS_QUERY
1666        ))
1667    };
1668    let borrowed = |q: &'static str| -> Cow<'static, str> { Cow::Borrowed(q) };
1669
1670    let (lang, language, query): (&str, tree_sitter::Language, Cow<'static, str>) = match ext {
1671        "py" | "pyi" => (
1672            "python",
1673            tree_sitter_python::LANGUAGE.into(),
1674            borrowed(tree_sitter_python::TAGS_QUERY),
1675        ),
1676        "js" | "jsx" | "mjs" | "cjs" => (
1677            "javascript",
1678            tree_sitter_javascript::LANGUAGE.into(),
1679            borrowed(tree_sitter_javascript::TAGS_QUERY),
1680        ),
1681        "ts" | "mts" | "cts" => (
1682            "typescript",
1683            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
1684            ts_query(),
1685        ),
1686        "tsx" => (
1687            "tsx",
1688            tree_sitter_typescript::LANGUAGE_TSX.into(),
1689            ts_query(),
1690        ),
1691        "go" => (
1692            "go",
1693            tree_sitter_go::LANGUAGE.into(),
1694            borrowed(tree_sitter_go::TAGS_QUERY),
1695        ),
1696        "rb" => (
1697            "ruby",
1698            tree_sitter_ruby::LANGUAGE.into(),
1699            borrowed(tree_sitter_ruby::TAGS_QUERY),
1700        ),
1701        "java" => (
1702            "java",
1703            tree_sitter_java::LANGUAGE.into(),
1704            borrowed(tree_sitter_java::TAGS_QUERY),
1705        ),
1706        "c" | "h" => (
1707            "c",
1708            tree_sitter_c::LANGUAGE.into(),
1709            borrowed(tree_sitter_c::TAGS_QUERY),
1710        ),
1711        "cc" | "cpp" | "cxx" | "hpp" | "hh" | "hxx" => (
1712            "cpp",
1713            tree_sitter_cpp::LANGUAGE.into(),
1714            borrowed(tree_sitter_cpp::TAGS_QUERY),
1715        ),
1716        // The crate's TAGS_QUERY has a stray `@module` capture that
1717        // `tree-sitter-tags` rejects, so a corrected copy is vendored.
1718        "cs" => (
1719            "csharp",
1720            tree_sitter_c_sharp::LANGUAGE.into(),
1721            borrowed(include_str!("queries/csharp/tags.scm")),
1722        ),
1723        "php" => (
1724            "php",
1725            tree_sitter_php::LANGUAGE_PHP.into(),
1726            borrowed(tree_sitter_php::TAGS_QUERY),
1727        ),
1728        // Scala's crate bundles a tags.scm but exposes no const, so it is vendored.
1729        "scala" | "sc" => (
1730            "scala",
1731            tree_sitter_scala::LANGUAGE.into(),
1732            borrowed(include_str!("queries/scala/tags.scm")),
1733        ),
1734        "ml" => (
1735            "ocaml",
1736            tree_sitter_ocaml::LANGUAGE_OCAML.into(),
1737            borrowed(tree_sitter_ocaml::TAGS_QUERY),
1738        ),
1739        "mli" => (
1740            "ocaml",
1741            tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE.into(),
1742            borrowed(tree_sitter_ocaml::TAGS_QUERY),
1743        ),
1744        "ex" | "exs" => (
1745            "elixir",
1746            tree_sitter_elixir::LANGUAGE.into(),
1747            borrowed(tree_sitter_elixir::TAGS_QUERY),
1748        ),
1749        // Bash ships no tags query at all, so one is vendored.
1750        "sh" | "bash" => (
1751            "bash",
1752            tree_sitter_bash::LANGUAGE.into(),
1753            borrowed(include_str!("queries/bash/tags.scm")),
1754        ),
1755        // SQL (tree-sitter-sequel) ships no tags query, so one is vendored.
1756        "sql" => (
1757            "sql",
1758            tree_sitter_sequel::LANGUAGE.into(),
1759            borrowed(include_str!("queries/sql/tags.scm")),
1760        ),
1761        _ => return None,
1762    };
1763    // Distinguish grammars that share a `lang` label: `.ml` and `.mli` are both
1764    // "ocaml" but parse with different grammars, so they must cache separately.
1765    let grammar_key = match ext {
1766        "mli" => "ocaml-interface",
1767        _ => lang,
1768    };
1769    Some(TagLang {
1770        lang,
1771        grammar_key,
1772        language,
1773        query,
1774    })
1775}
1776
1777/// A compiled tags configuration, shared across the blobs of one language.
1778type TagConfig = std::sync::Arc<tree_sitter_tags::TagsConfiguration>;
1779
1780/// Cache of compiled tags configurations, keyed by [`TagLang::grammar_key`] (not
1781/// the `lang` label, since one label can back multiple grammars). Compiling a
1782/// `tags.scm` query is not free, and `sync` extracts many blobs, so each
1783/// grammar's configuration is built once. A grammar whose query fails to compile
1784/// (a grammar/query mismatch — a build-time invariant, not a runtime input)
1785/// caches `None` so it is not retried per file.
1786static TAG_CONFIGS: std::sync::LazyLock<
1787    std::sync::Mutex<std::collections::HashMap<&'static str, Option<TagConfig>>>,
1788> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1789
1790/// The compiled tags configuration for a language, building and caching it on
1791/// first use. `None` if the query does not compile against the grammar.
1792fn tag_config(def: &TagLang) -> Option<TagConfig> {
1793    let mut cache = TAG_CONFIGS
1794        .lock()
1795        .unwrap_or_else(std::sync::PoisonError::into_inner);
1796    cache
1797        .entry(def.grammar_key)
1798        .or_insert_with(|| {
1799            tree_sitter_tags::TagsConfiguration::new(def.language.clone(), &def.query, "")
1800                .ok()
1801                .map(std::sync::Arc::new)
1802        })
1803        .clone()
1804}
1805
1806/// A per-language tree-sitter query capturing import/include targets as `@path`.
1807/// Run alongside the tags extraction so the generic languages emit `imports`
1808/// edges (`file → import` node) the way the Rust walker does for `use`. `None`
1809/// for a language whose imports we do not yet capture (it simply emits none).
1810///
1811/// Node names are grammar-specific; a query that fails to compile against its
1812/// grammar is cached as absent (see [`import_query`]) rather than retried.
1813fn import_query_for(lang: &str) -> Option<&'static str> {
1814    Some(match lang {
1815        // `import a.b.c`, `import a.b as d`, `from a.b import x`, `from . import x`.
1816        "python" => {
1817            "(import_statement name: (dotted_name) @path)\n\
1818             (import_statement name: (aliased_import name: (dotted_name) @path))\n\
1819             (import_from_statement module_name: (dotted_name) @path)\n\
1820             (import_from_statement module_name: (relative_import) @path)"
1821        }
1822        // `import x from \"mod\"`, `export … from \"mod\"` — the module string.
1823        "javascript" | "typescript" | "tsx" => {
1824            "(import_statement source: (string (string_fragment) @path))\n\
1825             (export_statement source: (string (string_fragment) @path))"
1826        }
1827        // Each spec's quoted path inside an `import ( … )` block or single import.
1828        "go" => "(import_spec path: (interpreted_string_literal) @path)",
1829        // `import a.b.C;` / `import static a.b.C;`.
1830        "java" => {
1831            "(import_declaration (scoped_identifier) @path)\n\
1832             (import_declaration (identifier) @path)"
1833        }
1834        // `#include \"x.h\"` and `#include <x>` (C and, by inheritance, C++).
1835        "c" | "cpp" => {
1836            "(preproc_include path: (string_literal) @path)\n\
1837             (preproc_include path: (system_lib_string) @path)"
1838        }
1839        _ => return None,
1840    })
1841}
1842
1843/// A compiled import query, shared across the blobs of one grammar.
1844type ImportQuery = std::sync::Arc<tree_sitter::Query>;
1845
1846/// Cache of compiled import queries, keyed by [`TagLang::grammar_key`] (as with
1847/// [`TAG_CONFIGS`]). `None` when the language has no import query or it does not
1848/// compile against the grammar, so it is not retried per file.
1849static IMPORT_QUERIES: std::sync::LazyLock<
1850    std::sync::Mutex<std::collections::HashMap<&'static str, Option<ImportQuery>>>,
1851> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1852
1853/// The compiled import query for a language, building and caching it on first use.
1854fn import_query(def: &TagLang) -> Option<ImportQuery> {
1855    let mut cache = IMPORT_QUERIES
1856        .lock()
1857        .unwrap_or_else(std::sync::PoisonError::into_inner);
1858    cache
1859        .entry(def.grammar_key)
1860        .or_insert_with(|| {
1861            let src = import_query_for(def.lang)?;
1862            tree_sitter::Query::new(&def.language, src)
1863                .ok()
1864                .map(std::sync::Arc::new)
1865        })
1866        .clone()
1867}
1868
1869/// Normalise a captured import target to a bare module string: strip surrounding
1870/// quotes (`"…"`), C system-header brackets (`<…>`), and whitespace.
1871fn normalize_import(raw: &str) -> String {
1872    raw.trim()
1873        .trim_matches(|c| c == '"' || c == '\'' || c == '<' || c == '>')
1874        .trim()
1875        .to_owned()
1876}
1877
1878/// Append `imports` edges for a blob by running its language's import query.
1879/// Emits one `import:<lang>:<module>` node (deduped) and a `file → import`
1880/// `Imports` edge per distinct target, mirroring the Rust walker's `use` handling.
1881fn append_import_facts(
1882    path: &str,
1883    def: &TagLang,
1884    bytes: &[u8],
1885    nodes: &mut Vec<Node>,
1886    edges: &mut Vec<Edge>,
1887) {
1888    use streaming_iterator::StreamingIterator as _;
1889
1890    let Some(query) = import_query(def) else {
1891        return;
1892    };
1893    let mut parser = tree_sitter::Parser::new();
1894    if parser.set_language(&def.language).is_err() {
1895        return;
1896    }
1897    let Some(tree) = parser.parse(bytes, None) else {
1898        return;
1899    };
1900    let mut cursor = tree_sitter::QueryCursor::new();
1901    let mut seen = std::collections::BTreeSet::new();
1902    let mut matches = cursor.matches(&query, tree.root_node(), bytes);
1903    while let Some(m) = matches.next() {
1904        for cap in m.captures {
1905            let Ok(raw) = cap.node.utf8_text(bytes) else {
1906                continue;
1907            };
1908            let module = normalize_import(raw);
1909            if module.is_empty() {
1910                continue;
1911            }
1912            let key = format!("import:{}:{module}", def.lang);
1913            if seen.insert(key.clone()) {
1914                nodes.push(Node {
1915                    key: key.clone(),
1916                    kind: NodeKind::Other("import".into()),
1917                    name: module,
1918                    // The import *target* is not owned by any one file (its key is
1919                    // global): leave `path` unset, as the Rust walker does, so two
1920                    // files importing the same module dedup to one stable node.
1921                    path: None,
1922                    lang: Some(def.lang.to_owned()),
1923                    blob_hash: None,
1924                    span: None,
1925                    provenance: Provenance::Derived,
1926                    meta: serde_json::Value::Null,
1927                });
1928                edges.push(Edge::derived(file_key(path), key, EdgeKind::Imports));
1929            }
1930        }
1931    }
1932}
1933
1934/// Map a `tags.scm` syntax type (the tail of a `@definition.X` capture) to a
1935/// graph node kind. Unrecognised kinds are kept verbatim under `Other`.
1936fn tag_node_kind(syntax_type: &str) -> NodeKind {
1937    match syntax_type {
1938        "function" | "method" | "constructor" => NodeKind::Fn,
1939        "class" | "struct" => NodeKind::Struct,
1940        "interface" | "trait" | "protocol" => NodeKind::Trait,
1941        "enum" => NodeKind::Enum,
1942        // A Scala/Kotlin `object` is a singleton namespace; group it with modules.
1943        "module" | "namespace" | "object" => NodeKind::Module,
1944        other => NodeKind::Other(other.to_owned()),
1945    }
1946}
1947
1948/// A definition captured from a `tags.scm` run, before nesting is resolved.
1949struct TagDef {
1950    name: String,
1951    kind: NodeKind,
1952    range: std::ops::Range<usize>,
1953    docs: Option<String>,
1954}
1955
1956/// Extract facts from a source blob via its language's tags query. Returns `None`
1957/// when the extension has no generic extractor or the query cannot compile, so
1958/// the caller falls back to a plain file node.
1959fn tag_facts(
1960    path: &str,
1961    blob_id: &str,
1962    bytes: &[u8],
1963    ext: &str,
1964    ingest: IngestConfig,
1965) -> Option<FactSet> {
1966    let def = tag_lang_for(ext)?;
1967    let lang = def.lang;
1968    let config = tag_config(&def)?;
1969
1970    let mut ctx = tree_sitter_tags::TagsContext::new();
1971    let (tags, _had_error) = ctx.generate_tags(&config, bytes, None).ok()?;
1972
1973    let mut defs: Vec<TagDef> = Vec::new();
1974    // Call references, as (byte offset of the call, callee simple-name), attached
1975    // later to whichever function definition encloses them.
1976    let mut calls: Vec<(usize, String)> = Vec::new();
1977    for tag in tags {
1978        let Ok(tag) = tag else { continue };
1979        let Some(name) = bytes
1980            .get(tag.name_range.clone())
1981            .and_then(|b| std::str::from_utf8(b).ok())
1982        else {
1983            continue;
1984        };
1985        let syntax = config.syntax_type_name(tag.syntax_type_id);
1986        if tag.is_definition {
1987            defs.push(TagDef {
1988                name: name.to_owned(),
1989                kind: tag_node_kind(syntax),
1990                range: tag.range.clone(),
1991                // The tags machinery already resolves a definition's doc comment.
1992                docs: tag.docs.clone(),
1993            });
1994        } else if syntax == "call" || syntax == "send" {
1995            // `send` is Ruby's message-send; both mean "invokes a name".
1996            calls.push((tag.range.start, name.to_owned()));
1997        }
1998    }
1999
2000    // Resolve nesting purely by byte-range containment: a definition's parent is
2001    // the smallest other definition whose range strictly encloses it. This yields
2002    // `contains` edges (parent→child) and qualified, collision-resistant keys
2003    // without any language-specific scope rules.
2004    let parents: Vec<Option<usize>> = (0..defs.len())
2005        .map(|i| smallest_enclosing(&defs, defs[i].range.clone(), Some(i)))
2006        .collect();
2007
2008    let keys: Vec<String> = (0..defs.len())
2009        .map(|i| {
2010            let qualified = qualified_name(&defs, &parents, i);
2011            format!("sym:{lang}:{path}#{qualified}")
2012        })
2013        .collect();
2014
2015    let mut nodes = vec![file_node(path, blob_id, bytes, Some(lang), ingest)];
2016    let mut edges: Vec<Edge> = Vec::new();
2017
2018    for (i, d) in defs.iter().enumerate() {
2019        let mut meta = serde_json::Map::new();
2020        if let Some(doc) = &d.docs {
2021            let content = cap_content(doc);
2022            if !content.is_empty() {
2023                meta.insert("content".into(), serde_json::Value::from(content));
2024            }
2025        }
2026        // Attach the calls this definition encloses — but only for functions, the
2027        // only kind `crate::sync::resolve_calls` links.
2028        if d.kind == NodeKind::Fn {
2029            let mut names: Vec<String> = calls
2030                .iter()
2031                .filter(|(off, _)| d.range.contains(off))
2032                .filter(|(off, _)| smallest_enclosing_off(&defs, *off) == Some(i))
2033                .map(|(_, name)| name.clone())
2034                .collect();
2035            names.sort();
2036            names.dedup();
2037            if !names.is_empty() {
2038                meta.insert("calls".into(), serde_json::Value::from(names));
2039            }
2040        }
2041
2042        let start = u32::try_from(d.range.start).unwrap_or(u32::MAX);
2043        let end = u32::try_from(d.range.end).unwrap_or(u32::MAX);
2044        nodes.push(Node {
2045            key: keys[i].clone(),
2046            kind: d.kind.clone(),
2047            name: d.name.clone(),
2048            path: Some(path.to_owned()),
2049            lang: Some(lang.to_owned()),
2050            blob_hash: Some(blob_id.to_owned()),
2051            span: Some(Span::new(start, end)),
2052            provenance: Provenance::Derived,
2053            meta: serde_json::Value::Object(meta),
2054        });
2055
2056        match parents[i] {
2057            Some(p) => edges.push(Edge::derived(
2058                keys[p].clone(),
2059                keys[i].clone(),
2060                EdgeKind::Contains,
2061            )),
2062            None => edges.push(Edge::derived(
2063                file_key(path),
2064                keys[i].clone(),
2065                EdgeKind::Defines,
2066            )),
2067        }
2068    }
2069
2070    // Import/include edges (file → import target), where the language has a query.
2071    append_import_facts(path, &def, bytes, &mut nodes, &mut edges);
2072
2073    // Deterministic, duplicate-free output (two query patterns can capture the
2074    // same definition, and distinct symbols can share a qualified name).
2075    nodes.sort_by(|a, b| a.key.cmp(&b.key));
2076    nodes.dedup_by(|a, b| a.key == b.key);
2077    edges.sort_by(|a, b| (a.kind.as_str(), &a.src, &a.dst).cmp(&(b.kind.as_str(), &b.src, &b.dst)));
2078    edges.dedup();
2079    Some(FactSet { nodes, edges })
2080}
2081
2082/// Index of the smallest definition (other than `skip`) whose range strictly
2083/// encloses `range`, or `None` if `range` is top-level.
2084fn smallest_enclosing(
2085    defs: &[TagDef],
2086    range: std::ops::Range<usize>,
2087    skip: Option<usize>,
2088) -> Option<usize> {
2089    let mut best: Option<usize> = None;
2090    for (j, c) in defs.iter().enumerate() {
2091        if Some(j) == skip {
2092            continue;
2093        }
2094        // Strictly encloses: contains both ends and is a larger span.
2095        let encloses = c.range.start <= range.start
2096            && c.range.end >= range.end
2097            && (c.range.end - c.range.start) > (range.end - range.start);
2098        if encloses
2099            && best.is_none_or(|b| {
2100                defs[b].range.end - defs[b].range.start > c.range.end - c.range.start
2101            })
2102        {
2103            best = Some(j);
2104        }
2105    }
2106    best
2107}
2108
2109/// Index of the smallest definition enclosing byte offset `off`.
2110fn smallest_enclosing_off(defs: &[TagDef], off: usize) -> Option<usize> {
2111    let mut best: Option<usize> = None;
2112    for (j, c) in defs.iter().enumerate() {
2113        if c.range.contains(&off)
2114            && best.is_none_or(|b| {
2115                defs[b].range.end - defs[b].range.start > c.range.end - c.range.start
2116            })
2117        {
2118            best = Some(j);
2119        }
2120    }
2121    best
2122}
2123
2124/// A definition's qualified name: its ancestors' names (root→leaf) joined to its
2125/// own by `::`, so nested symbols get distinct, stable keys.
2126fn qualified_name(defs: &[TagDef], parents: &[Option<usize>], i: usize) -> String {
2127    let mut chain: Vec<&str> = vec![defs[i].name.as_str()];
2128    let mut cur = parents[i];
2129    // Bound the walk by the number of definitions — parents form a DAG toward
2130    // smaller-or-equal spans, but guard against any pathological cycle.
2131    let mut guard = defs.len();
2132    while let Some(p) = cur {
2133        if guard == 0 {
2134            break;
2135        }
2136        guard -= 1;
2137        chain.push(defs[p].name.as_str());
2138        cur = parents[p];
2139    }
2140    chain.reverse();
2141    chain.join("::")
2142}
2143
2144/// Byte span of an AST node, clamped to `u32`.
2145fn span(node: tree_sitter::Node) -> Span {
2146    let start = u32::try_from(node.start_byte()).unwrap_or(u32::MAX);
2147    let end = u32::try_from(node.end_byte()).unwrap_or(u32::MAX);
2148    Span::new(start, end)
2149}
2150
2151/// Qualified name for a new symbol: all enclosing scope segments plus `name`.
2152fn qualify(scope: &[Scope], name: &str) -> String {
2153    let mut parts: Vec<&str> = scope.iter().map(|s| s.seg.as_str()).collect();
2154    parts.push(name);
2155    parts.join("::")
2156}
2157
2158/// Combine an optional immediate qualifier with a callee `name` into the stored
2159/// `meta.calls` descriptor. Path-relative qualifiers (`self`/`crate`/`super`) and
2160/// an empty qualifier collapse to the bare name, since they don't scope a
2161/// cross-file target; `Self` is preserved as the marker for a same-impl call.
2162fn qualify_callee(qualifier: Option<&str>, name: &str) -> String {
2163    match qualifier {
2164        Some(q) if !q.is_empty() && !matches!(q, "self" | "crate" | "super") => {
2165            format!("{q}::{name}")
2166        }
2167        _ => name.to_owned(),
2168    }
2169}
2170
2171/// Push a scope entry, returning the extended stack.
2172fn extend(scope: &[Scope], seg: &str, key: Option<String>) -> Vec<Scope> {
2173    let mut next: Vec<Scope> = scope
2174        .iter()
2175        .map(|s| Scope {
2176            seg: s.seg.clone(),
2177            key: s.key.clone(),
2178        })
2179        .collect();
2180    next.push(Scope {
2181        seg: seg.to_owned(),
2182        key,
2183    });
2184    next
2185}
2186
2187#[cfg(test)]
2188mod tests {
2189    use super::{Extractor, FileNodeExtractor, Registry, RustExtractor};
2190    use crate::{EdgeKind, Node, NodeKind};
2191
2192    #[test]
2193    fn file_node_extractor_is_deterministic_and_tagged() {
2194        let ex = FileNodeExtractor;
2195        let a = ex.extract("src/lib.rs", "abc123", b"one\ntwo\n");
2196        let b = ex.extract("src/lib.rs", "abc123", b"one\ntwo\n");
2197        assert_eq!(a, b, "extraction must be deterministic");
2198
2199        assert_eq!(a.nodes.len(), 1);
2200        assert!(a.edges.is_empty());
2201        let node = &a.nodes[0];
2202        assert_eq!(node.key, "file:src/lib.rs");
2203        assert_eq!(node.kind, NodeKind::File);
2204        assert_eq!(node.name, "lib.rs");
2205        assert_eq!(node.blob_hash.as_deref(), Some("abc123"));
2206        assert_eq!(node.meta["lines"], 2);
2207        assert_eq!(node.meta["bytes"], 8);
2208    }
2209
2210    #[test]
2211    fn config_files_emit_config_key_nodes() {
2212        let reg = Registry::new(crate::IngestConfig::default());
2213        let toml = b"[serve]\naddr = \"0.0.0.0:8443\"\ntools = false\n";
2214        let a = reg.extract("config.toml", "cfg1", toml);
2215        let b = reg.extract("config.toml", "cfg1", toml);
2216        assert_eq!(a, b, "config extraction must be deterministic");
2217
2218        // The file node plus a config_key node per leaf.
2219        assert!(a.nodes.iter().any(|n| n.key == "file:config.toml"));
2220        let addr = a
2221            .nodes
2222            .iter()
2223            .find(|n| n.key == "cfgkey:config.toml#serve.addr")
2224            .expect("serve.addr config_key node");
2225        assert_eq!(addr.kind, NodeKind::Other("config_key".into()));
2226        assert_eq!(addr.name, "serve.addr");
2227        assert_eq!(addr.meta["value"], "0.0.0.0:8443"); // unquoted
2228        // A `contains` edge from the file to each config key.
2229        assert!(a.edges.iter().any(|e| {
2230            e.src == "file:config.toml"
2231                && e.dst == "cfgkey:config.toml#serve.addr"
2232                && e.kind == EdgeKind::Contains
2233        }));
2234
2235        // A `.env` (no extension) is recognised by name; a repeated key yields one
2236        // node with the last value; a secret value is redacted.
2237        let env = reg.extract(".env", "env1", b"PORT=8080\nPORT=9090\nAPI_TOKEN=s3cr3t\n");
2238        let port = env
2239            .nodes
2240            .iter()
2241            .find(|n| n.key == "cfgkey:.env#PORT")
2242            .expect("PORT node");
2243        assert_eq!(port.meta["value"], "9090", "dotenv last-one-wins");
2244        assert_eq!(
2245            env.nodes
2246                .iter()
2247                .filter(|n| n.key == "cfgkey:.env#PORT")
2248                .count(),
2249            1
2250        );
2251        let token = env
2252            .nodes
2253            .iter()
2254            .find(|n| n.key == "cfgkey:.env#API_TOKEN")
2255            .expect("API_TOKEN node");
2256        assert_eq!(token.meta["value"], "<redacted>", "secret not persisted");
2257        // A source file is unaffected.
2258        let rs = reg.extract("src/lib.rs", "x", b"pub fn f() {}\n");
2259        assert!(
2260            rs.nodes
2261                .iter()
2262                .all(|n| n.kind != NodeKind::Other("config_key".into()))
2263        );
2264    }
2265
2266    #[test]
2267    fn dockerfile_emits_image_ref_nodes_and_skips_internal_stages() {
2268        let reg = Registry::new(crate::IngestConfig::default());
2269        // Multi-stage: a builder stage (external), an internal `FROM builder`
2270        // (skipped), and a runtime external base pinned by digest.
2271        let df = b"FROM --platform=linux/amd64 rust:1.90 AS builder\nRUN cargo build\n\
2272                   FROM builder AS test\nFROM registry.io/app:1.2@sha256:abc AS run\nFROM scratch\n";
2273        let a = reg.extract("Dockerfile", "d1", df);
2274        let b = reg.extract("Dockerfile", "d1", df);
2275        assert_eq!(a, b, "dockerfile extraction must be deterministic");
2276
2277        let refs: Vec<&Node> = a
2278            .nodes
2279            .iter()
2280            .filter(|n| n.kind == NodeKind::Other("image_ref".into()))
2281            .collect();
2282        // Two external images: rust:1.90 and the app digest. `FROM builder` and
2283        // `FROM scratch` are not pins.
2284        assert_eq!(refs.len(), 2, "got: {refs:?}");
2285        let rust = refs
2286            .iter()
2287            .find(|n| n.meta["image"] == "rust")
2288            .expect("rust");
2289        assert_eq!(rust.meta["tag"], "1.90");
2290        let app = refs
2291            .iter()
2292            .find(|n| n.meta["image"] == "registry.io/app:1.2")
2293            .expect("app digest");
2294        assert_eq!(app.meta["digest"], "sha256:abc");
2295        // A `references` edge from the file to each image_ref.
2296        assert!(
2297            a.edges
2298                .iter()
2299                .any(|e| { e.src == "file:Dockerfile" && e.kind == EdgeKind::References })
2300        );
2301        // `Dockerfile.prod` is recognised too; a plain source file is not.
2302        assert!(
2303            reg.extract("Dockerfile.prod", "d2", b"FROM alpine:3\n")
2304                .nodes
2305                .iter()
2306                .any(|n| n.kind == NodeKind::Other("image_ref".into()))
2307        );
2308
2309        // A stage alias equal to the image name (`FROM alpine AS alpine`) must not
2310        // make the external `alpine` look like an internal stage — it is still a pin.
2311        let c = reg.extract("Dockerfile", "d3", b"FROM alpine AS alpine\n");
2312        assert!(
2313            c.nodes
2314                .iter()
2315                .any(|n| n.kind == NodeKind::Other("image_ref".into())
2316                    && n.meta["image"] == "alpine"),
2317            "FROM x AS x is an external pin, got: {:?}",
2318            c.nodes
2319        );
2320    }
2321
2322    const SAMPLE: &str = r"
2323use std::path::Path;
2324
2325pub struct Store;
2326
2327impl Store {
2328    pub fn open() -> Store {
2329        helper();
2330        Store
2331    }
2332}
2333
2334fn helper() {}
2335
2336mod inner {
2337    pub fn nested() {}
2338}
2339";
2340
2341    fn keys(fs: &crate::FactSet) -> Vec<String> {
2342        let mut k: Vec<_> = fs.nodes.iter().map(|n| n.key.clone()).collect();
2343        k.sort();
2344        k
2345    }
2346
2347    #[test]
2348    fn rust_extractor_emits_symbols_and_edges() {
2349        let fs = RustExtractor.extract("src/lib.rs", "blob1", SAMPLE.as_bytes());
2350        let ks = keys(&fs);
2351        assert!(ks.contains(&"file:src/lib.rs".to_owned()));
2352        assert!(ks.contains(&"sym:rust:src/lib.rs#Store".to_owned()));
2353        assert!(ks.contains(&"sym:rust:src/lib.rs#Store::open".to_owned()));
2354        assert!(ks.contains(&"sym:rust:src/lib.rs#helper".to_owned()));
2355        assert!(ks.contains(&"sym:rust:src/lib.rs#inner".to_owned()));
2356        assert!(ks.contains(&"sym:rust:src/lib.rs#inner::nested".to_owned()));
2357
2358        // `open` records that it calls `helper`.
2359        let open = fs
2360            .nodes
2361            .iter()
2362            .find(|n| n.key == "sym:rust:src/lib.rs#Store::open")
2363            .expect("open node");
2364        assert_eq!(open.meta["calls"], serde_json::json!(["helper"]));
2365
2366        // file defines top-level items; a module contains its nested fn.
2367        let defines: Vec<_> = fs
2368            .edges
2369            .iter()
2370            .filter(|e| e.kind == EdgeKind::Defines && e.dst == "sym:rust:src/lib.rs#helper")
2371            .collect();
2372        assert_eq!(defines.len(), 1);
2373        assert!(fs.edges.iter().any(|e| e.kind == EdgeKind::Contains
2374            && e.src == "sym:rust:src/lib.rs#inner"
2375            && e.dst == "sym:rust:src/lib.rs#inner::nested"));
2376
2377        // the `use` becomes an imports edge.
2378        assert!(fs.edges.iter().any(|e| e.kind == EdgeKind::Imports
2379            && e.src == "file:src/lib.rs"
2380            && e.dst == "import:rust:std::path::Path"));
2381    }
2382
2383    #[test]
2384    fn rust_extractor_records_struct_field_names() {
2385        // A struct with named fields records them in `meta.fields` (the follow
2386        // bridge's join signal); a tuple struct and a unit struct carry none.
2387        let src = "pub struct ServeConfig {\n\
2388                   \x20   pub addr: Option<String>,\n\
2389                   \x20   pub tls_cert: Option<String>,\n\
2390                   }\n\
2391                   pub struct Pair(u8, u8);\n\
2392                   pub struct Marker;\n";
2393        let fs = RustExtractor.extract("src/config.rs", "b", src.as_bytes());
2394        let fields = |key: &str| {
2395            fs.nodes
2396                .iter()
2397                .find(|n| n.key == key)
2398                .and_then(|n| n.meta.get("fields").cloned())
2399        };
2400        assert_eq!(
2401            fields("sym:rust:src/config.rs#ServeConfig"),
2402            Some(serde_json::json!(["addr", "tls_cert"])),
2403            "named fields captured in source order"
2404        );
2405        // Positional (tuple) and unit structs declare no named fields → no key.
2406        assert_eq!(fields("sym:rust:src/config.rs#Pair"), None);
2407        assert_eq!(fields("sym:rust:src/config.rs#Marker"), None);
2408    }
2409
2410    #[test]
2411    fn struct_records_field_types_and_config_root_marker() {
2412        // Field types land in `meta.field_types` (transparent wrappers peeled), and
2413        // the `@rto:config` marker sets `meta.config_root`.
2414        let src = "// @rto:config\n\
2415                   pub struct Config {\n\
2416                   \x20   pub zerobus: ZerobusConfig,\n\
2417                   \x20   pub replicas: Option<u32>,\n\
2418                   }\n\
2419                   pub struct ZerobusConfig {\n\
2420                   \x20   pub server_endpoint: String,\n\
2421                   }\n";
2422        let fs = RustExtractor.extract("src/config.rs", "b", src.as_bytes());
2423        let node = |key: &str| fs.nodes.iter().find(|n| n.key == key).expect("node");
2424        let root = node("sym:rust:src/config.rs#Config");
2425        assert_eq!(root.meta.get("config_root"), Some(&serde_json::json!(true)));
2426        assert_eq!(
2427            root.meta.get("field_types"),
2428            Some(&serde_json::json!({ "zerobus": "ZerobusConfig", "replicas": "u32" })),
2429            "transparent wrappers peeled (Option<u32> → u32)"
2430        );
2431        // An unmarked struct carries no `config_root` flag.
2432        assert_eq!(
2433            node("sym:rust:src/config.rs#ZerobusConfig")
2434                .meta
2435                .get("config_root"),
2436            None
2437        );
2438    }
2439
2440    #[test]
2441    fn config_root_struct_synthesizes_recursive_dotted_config_keys() {
2442        // A `@rto:config` root with a nested struct field yields dotted `config_key`
2443        // nodes for its leaves — no committed `*-example.toml` needed. The nested
2444        // field descends by name into a struct defined in the same file.
2445        let src = "// @rto:config\n\
2446                   pub struct Config {\n\
2447                   \x20   pub zerobus: ZerobusConfig,\n\
2448                   \x20   pub log_level: String,\n\
2449                   }\n\
2450                   pub struct ZerobusConfig {\n\
2451                   \x20   pub server_endpoint: String,\n\
2452                   \x20   pub workspace_url: String,\n\
2453                   }\n";
2454        let fs = RustExtractor.extract("src/config.rs", "b", src.as_bytes());
2455        let cfg = |dotted: &str| {
2456            fs.nodes
2457                .iter()
2458                .find(|n| n.key == format!("cfgkey:src/config.rs#{dotted}"))
2459        };
2460        for dotted in [
2461            "zerobus.server_endpoint",
2462            "zerobus.workspace_url",
2463            "log_level",
2464        ] {
2465            let n = cfg(dotted).unwrap_or_else(|| panic!("missing {dotted}: {:?}", fs.nodes));
2466            assert_eq!(n.kind, NodeKind::Other("config_key".into()));
2467            assert_eq!(n.meta.get("key").and_then(|v| v.as_str()), Some(dotted));
2468            // Provenance marks it struct-derived, distinguishable from file keys.
2469            assert_eq!(
2470                n.meta.get("source").and_then(|v| v.as_str()),
2471                Some("struct")
2472            );
2473            assert_eq!(
2474                n.meta.get("struct").and_then(|v| v.as_str()),
2475                Some("Config")
2476            );
2477        }
2478        // The nested struct's own container name is NOT a leaf (only leaves emit).
2479        assert!(
2480            cfg("zerobus").is_none(),
2481            "intermediate section is not a leaf"
2482        );
2483        // A `contains` edge runs from the file node to each synthesized key.
2484        assert!(fs.edges.iter().any(|e| e.src == "file:src/config.rs"
2485            && e.dst == "cfgkey:src/config.rs#zerobus.server_endpoint"
2486            && e.kind == EdgeKind::Contains));
2487    }
2488
2489    #[test]
2490    fn struct_without_config_marker_synthesizes_no_config_keys() {
2491        // The safety property: an ordinary struct (no `@rto:config`) never produces
2492        // synthetic config keys, so the feature is strictly opt-in and additive.
2493        let src = "pub struct Config {\n\
2494                   \x20   pub zerobus: ZerobusConfig,\n\
2495                   }\n\
2496                   pub struct ZerobusConfig {\n\
2497                   \x20   pub server_endpoint: String,\n\
2498                   }\n";
2499        let fs = RustExtractor.extract("src/config.rs", "b", src.as_bytes());
2500        assert!(
2501            fs.nodes
2502                .iter()
2503                .all(|n| n.kind != NodeKind::Other("config_key".into())),
2504            "no synthetic config_key nodes without the marker: {:?}",
2505            fs.nodes
2506        );
2507    }
2508
2509    #[test]
2510    fn config_root_recursion_terminates_on_a_type_cycle() {
2511        // A self-referential config type must not loop forever: the cyclic field
2512        // falls back to a leaf and synthesis terminates.
2513        let src = "// @rto:config\n\
2514                   pub struct Config {\n\
2515                   \x20   pub addr: String,\n\
2516                   \x20   pub next: Box<Config>,\n\
2517                   }\n";
2518        let fs = RustExtractor.extract("src/config.rs", "b", src.as_bytes());
2519        let has = |dotted: &str| {
2520            fs.nodes
2521                .iter()
2522                .any(|n| n.key == format!("cfgkey:src/config.rs#{dotted}"))
2523        };
2524        assert!(has("addr"));
2525        // The descent path already holds `Config`, so the self-referential `next`
2526        // field is a leaf rather than recursing — synthesis terminates.
2527        assert!(has("next"), "cyclic field falls back to a leaf");
2528        assert!(!has("next.addr"), "no unbounded expansion");
2529    }
2530
2531    #[test]
2532    fn rust_extraction_is_deterministic() {
2533        let a = RustExtractor.extract("src/lib.rs", "blob1", SAMPLE.as_bytes());
2534        let b = RustExtractor.extract("src/lib.rs", "blob1", SAMPLE.as_bytes());
2535        assert_eq!(a, b);
2536    }
2537
2538    #[test]
2539    fn rust_extractor_captures_doc_comments() {
2540        let src = "/// The central store.\n\
2541                   pub struct Store;\n\n\
2542                   /// Opens it.\n\
2543                   /// Reads the config.\n\
2544                   pub fn open() {}\n\n\
2545                   // not a doc comment\n\
2546                   pub fn plain() {}\n";
2547        let fs = RustExtractor.extract("src/lib.rs", "b", src.as_bytes());
2548        let content = |key: &str| {
2549            fs.nodes
2550                .iter()
2551                .find(|n| n.key == key)
2552                .and_then(|n| n.meta.get("content"))
2553                .and_then(|v| v.as_str())
2554                .map(ToOwned::to_owned)
2555        };
2556        assert_eq!(
2557            content("sym:rust:src/lib.rs#Store").as_deref(),
2558            Some("The central store.")
2559        );
2560        assert_eq!(
2561            content("sym:rust:src/lib.rs#open").as_deref(),
2562            Some("Opens it. Reads the config.")
2563        );
2564        // A plain `//` comment is not captured.
2565        assert_eq!(content("sym:rust:src/lib.rs#plain"), None);
2566    }
2567
2568    #[test]
2569    fn prose_file_captures_capped_body() {
2570        let md = FileNodeExtractor.extract("docs/x.md", "b", b"# Title\n\nSome prose   here.\n");
2571        assert_eq!(md.nodes[0].meta["content"], "# Title Some prose here.");
2572        // A non-prose file gets no content.
2573        let rs = FileNodeExtractor.extract("notes.bin", "b", b"\x00\x01binary");
2574        assert!(rs.nodes[0].meta.get("content").is_none());
2575        // Extension matching is case-insensitive: `README.MD` is prose too.
2576        let upper = FileNodeExtractor.extract("README.MD", "b", b"# Hi\n");
2577        assert_eq!(upper.nodes[0].meta["content"], "# Hi");
2578    }
2579
2580    /// Build a one-page PDF with a single Helvetica text run, computing exact
2581    /// byte offsets for the xref table so `pdf-extract` can parse it.
2582    #[cfg(feature = "pdf-text")]
2583    fn minimal_pdf(text: &str) -> Vec<u8> {
2584        let content = format!("BT /F1 24 Tf 72 720 Td ({text}) Tj ET");
2585        let objects = [
2586            "<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
2587            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
2588            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_owned(),
2589            format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
2590            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_owned(),
2591        ];
2592        let mut pdf = Vec::new();
2593        pdf.extend_from_slice(b"%PDF-1.4\n");
2594        let mut offsets = Vec::new();
2595        for (i, obj) in objects.iter().enumerate() {
2596            offsets.push(pdf.len());
2597            pdf.extend_from_slice(format!("{} 0 obj\n{obj}\nendobj\n", i + 1).as_bytes());
2598        }
2599        let xref_start = pdf.len();
2600        pdf.extend_from_slice(
2601            format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
2602        );
2603        for off in &offsets {
2604            pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
2605        }
2606        pdf.extend_from_slice(
2607            format!(
2608                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
2609                objects.len() + 1
2610            )
2611            .as_bytes(),
2612        );
2613        pdf
2614    }
2615
2616    #[cfg(feature = "pdf-text")]
2617    #[test]
2618    fn pdf_file_captures_text_content() {
2619        let pdf = minimal_pdf("Hello Roteiro");
2620        let facts = FileNodeExtractor.extract("docs/guide.pdf", "b", &pdf);
2621        let content = facts.nodes[0].meta["content"].as_str().unwrap();
2622        assert!(content.contains("Hello Roteiro"), "got: {content:?}");
2623        // Extension matching is case-insensitive: `Guide.PDF` extracts too.
2624        let upper = FileNodeExtractor.extract("docs/Guide.PDF", "b", &pdf);
2625        assert!(upper.nodes[0].meta.get("content").is_some());
2626        // A malformed PDF degrades to a plain file node — no panic, no content.
2627        let bad = FileNodeExtractor.extract("docs/bad.pdf", "b", b"%PDF-1.4\ngarbage");
2628        assert!(bad.nodes[0].meta.get("content").is_none());
2629    }
2630
2631    #[cfg(any(feature = "image-ocr", feature = "image-vision"))]
2632    #[test]
2633    fn image_content_guards_before_touching_models() {
2634        // Case-insensitive image detection. The classifier and the byte cap moved
2635        // to `crate::media` with ADR-0015, so `media build` and extraction decide
2636        // what counts as an image with one function rather than two that drift.
2637        use crate::media::{MAX_IMAGE_BYTES, is_image};
2638        assert!(is_image("shot.PNG"));
2639        assert!(is_image("b.jpeg"));
2640        assert!(is_image("c.jpg"));
2641        assert!(!is_image("d.gif"));
2642        // A non-image path returns None without ever looking for models.
2643        assert!(
2644            super::image_content("notes.txt", b"hello", super::IngestConfig::default()).is_none()
2645        );
2646        // An oversized image is rejected by the size guard, before model lookup.
2647        let big = vec![0u8; MAX_IMAGE_BYTES + 1];
2648        assert!(super::image_content("shot.png", &big, super::IngestConfig::default()).is_none());
2649    }
2650
2651    #[test]
2652    fn doc_comment_body_recognises_doc_markers() {
2653        assert_eq!(super::doc_comment_body("/// hi").as_deref(), Some("hi"));
2654        assert_eq!(
2655            super::doc_comment_body("//! mod doc").as_deref(),
2656            Some("mod doc")
2657        );
2658        assert_eq!(
2659            super::doc_comment_body("/** block */").as_deref(),
2660            Some("block")
2661        );
2662        // Plain and `////` comments are not docs.
2663        assert_eq!(super::doc_comment_body("// plain"), None);
2664        assert_eq!(super::doc_comment_body("//// header"), None);
2665        // Degenerate block comments have an empty body, never garbage like "/".
2666        assert_eq!(super::doc_comment_body("/**/").as_deref(), Some(""));
2667        assert_eq!(super::doc_comment_body("/*!*/").as_deref(), Some(""));
2668    }
2669
2670    #[test]
2671    fn registry_dispatches_by_extension() {
2672        let rs = Registry::default().extract("src/lib.rs", "b", SAMPLE.as_bytes());
2673        assert!(rs.nodes.len() > 1, "rust file yields symbols");
2674        let txt = Registry::default().extract("notes.txt", "b", b"hello\n");
2675        assert_eq!(
2676            txt.nodes.len(),
2677            1,
2678            "non-code file falls back to a file node"
2679        );
2680        assert_eq!(txt.nodes[0].kind, NodeKind::File);
2681    }
2682
2683    #[test]
2684    fn tags_extracts_python_symbols_calls_and_nesting() {
2685        let src = "def helper():\n    pass\n\nclass Thing:\n    def run(self):\n        helper()\n";
2686        let fs = Registry::default().extract("app.py", "b", src.as_bytes());
2687
2688        let names: Vec<&str> = fs.nodes.iter().map(|n| n.name.as_str()).collect();
2689        assert!(names.contains(&"helper"), "top-level function");
2690        assert!(names.contains(&"Thing"), "class");
2691        assert!(names.contains(&"run"), "method");
2692
2693        // Every symbol is language-tagged.
2694        assert_eq!(
2695            fs.nodes
2696                .iter()
2697                .find(|n| n.name == "helper")
2698                .and_then(|n| n.lang.as_deref()),
2699            Some("python")
2700        );
2701
2702        // The method is nested in the class: a `contains` edge to `Thing::run`.
2703        assert!(
2704            fs.edges
2705                .iter()
2706                .any(|e| e.kind == EdgeKind::Contains && e.dst.ends_with("#Thing::run")),
2707            "method nested under class via containment"
2708        );
2709
2710        // The method's body calls `helper`, recorded for later resolution.
2711        let run = fs.nodes.iter().find(|n| n.name == "run").unwrap();
2712        let calls = run.meta.get("calls").and_then(|v| v.as_array()).unwrap();
2713        assert!(
2714            calls.iter().any(|c| c.as_str() == Some("helper")),
2715            "enclosed call captured in meta.calls"
2716        );
2717    }
2718
2719    #[test]
2720    fn tags_extraction_is_deterministic() {
2721        let src = b"package main\nfunc Add(a int) int { return a }\n";
2722        let a = Registry::default().extract("m.go", "b", src);
2723        let b = Registry::default().extract("m.go", "b", src);
2724        assert_eq!(a, b, "tags extraction must be deterministic");
2725        assert!(
2726            a.nodes
2727                .iter()
2728                .any(|n| n.name == "Add" && n.kind == NodeKind::Fn)
2729        );
2730    }
2731
2732    #[test]
2733    fn tags_extracts_typescript() {
2734        let ts = Registry::default().extract("svc.ts", "b", b"export class Svc {\n  run() {}\n}\n");
2735        assert!(ts.nodes.iter().any(|n| n.name == "Svc"), "class");
2736        assert!(ts.nodes.iter().any(|n| n.name == "run"), "method");
2737        assert_eq!(
2738            ts.nodes
2739                .iter()
2740                .find(|n| n.name == "Svc")
2741                .and_then(|n| n.lang.as_deref()),
2742            Some("typescript")
2743        );
2744    }
2745
2746    // Extract `src` as `path` and collect the `import:<…>` targets it emits.
2747    // Every import node's key is global, so — like the Rust walker's — it must
2748    // carry no `path`, keeping the node stable when several files import it.
2749    fn import_targets(path: &str, src: &[u8]) -> Vec<String> {
2750        Registry::default()
2751            .extract(path, "b", src)
2752            .nodes
2753            .iter()
2754            .filter(|n| n.kind == NodeKind::Other("import".into()))
2755            .inspect(|n| {
2756                assert!(
2757                    n.path.is_none(),
2758                    "import node must not be file-scoped: {}",
2759                    n.key
2760                );
2761            })
2762            .map(|n| n.key.clone())
2763            .collect()
2764    }
2765
2766    #[test]
2767    fn extracts_imports_edges_per_language() {
2768        // Each case: a file with import statements → the expected `import:` nodes,
2769        // plus a `file → import` Imports edge.
2770        let cases: &[(&str, &[u8], &[&str])] = &[
2771            (
2772                "app.py",
2773                b"import os\nfrom a.b import c\nimport x.y as z\n",
2774                &["import:python:os", "import:python:a.b", "import:python:x.y"],
2775            ),
2776            (
2777                "m.js",
2778                b"import foo from \"./mod.js\";\nexport { y } from \"./y.js\";\n",
2779                &["import:javascript:./mod.js", "import:javascript:./y.js"],
2780            ),
2781            (
2782                "svc.ts",
2783                b"import { A } from \"./a\";\n",
2784                &["import:typescript:./a"],
2785            ),
2786            (
2787                "m.go",
2788                b"package main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n",
2789                &["import:go:fmt", "import:go:os"],
2790            ),
2791            (
2792                "M.java",
2793                b"import java.util.List;\nimport static a.B.c;\n",
2794                &["import:java:java.util.List", "import:java:a.B.c"],
2795            ),
2796            (
2797                "m.c",
2798                b"#include <stdio.h>\n#include \"local.h\"\n",
2799                &["import:c:stdio.h", "import:c:local.h"],
2800            ),
2801            ("m.cpp", b"#include <vector>\n", &["import:cpp:vector"]),
2802        ];
2803        for (path, src, expected) in cases {
2804            let got = import_targets(path, src);
2805            for want in *expected {
2806                assert!(
2807                    got.iter().any(|k| k == want),
2808                    "{path}: expected import node {want}, got {got:?}"
2809                );
2810            }
2811            // The corresponding file → import edge is derived.
2812            let fs = Registry::default().extract(path, "b", src);
2813            for want in *expected {
2814                assert!(
2815                    fs.edges.iter().any(|e| e.kind == EdgeKind::Imports
2816                        && e.src == format!("file:{path}")
2817                        && &e.dst == want),
2818                    "{path}: expected Imports edge to {want}"
2819                );
2820            }
2821        }
2822    }
2823
2824    #[test]
2825    fn every_registered_language_query_compiles() {
2826        // A grammar/query mismatch (e.g. a future grammar bump) would make a
2827        // language silently fall back to a plain file node; assert each query
2828        // compiles against its grammar so that regression surfaces here instead.
2829        for ext in [
2830            "py", "js", "ts", "tsx", "go", "rb", "java", "c", "cpp", "cs", "php", "scala", "ml",
2831            "mli", "ex", "sh", "sql",
2832        ] {
2833            let def = super::tag_lang_for(ext).unwrap_or_else(|| panic!("no language for .{ext}"));
2834            let lang = def.lang;
2835            assert!(
2836                super::tag_config(&def).is_some(),
2837                "tags query for .{ext} ({lang}) must compile against its grammar"
2838            );
2839        }
2840    }
2841
2842    #[test]
2843    fn ocaml_impl_and_interface_cache_under_distinct_grammars() {
2844        // `.ml` and `.mli` share the `ocaml` label but use different grammars, so
2845        // their config-cache keys must differ or one would parse with the other's
2846        // grammar (see the config cache keyed on `grammar_key`, not `lang`).
2847        let ml = super::tag_lang_for("ml").unwrap();
2848        let mli = super::tag_lang_for("mli").unwrap();
2849        assert_eq!(ml.lang, "ocaml");
2850        assert_eq!(mli.lang, "ocaml");
2851        assert_ne!(
2852            ml.grammar_key, mli.grammar_key,
2853            "distinct grammars must cache separately"
2854        );
2855    }
2856
2857    #[test]
2858    fn tags_extracts_vendored_bash_query() {
2859        let src = "greet() {\n  echo hi\n}\nmain() {\n  greet\n}\n";
2860        let fs = Registry::default().extract("run.sh", "b", src.as_bytes());
2861        let names: Vec<&str> = fs.nodes.iter().map(|n| n.name.as_str()).collect();
2862        assert!(names.contains(&"greet"), "shell function greet");
2863        assert!(names.contains(&"main"), "shell function main");
2864
2865        // `main` invokes `greet` — a command reference captured as a call.
2866        let main = fs.nodes.iter().find(|n| n.name == "main").unwrap();
2867        assert!(
2868            main.meta
2869                .get("calls")
2870                .and_then(|v| v.as_array())
2871                .is_some_and(|c| c.iter().any(|x| x.as_str() == Some("greet"))),
2872            "internal command invocation captured"
2873        );
2874    }
2875
2876    #[test]
2877    fn tags_extracts_vendored_sql_query() {
2878        let src = "CREATE TABLE users (id int);\n\
2879                   CREATE FUNCTION recent() RETURNS int AS $$ SELECT total(id) FROM users $$ LANGUAGE sql;\n";
2880        let fs = Registry::default().extract("schema.sql", "b", src.as_bytes());
2881        let names: Vec<&str> = fs.nodes.iter().map(|n| n.name.as_str()).collect();
2882        assert!(names.contains(&"users"), "table definition");
2883        assert!(names.contains(&"recent"), "function definition");
2884
2885        // The table maps to a non-function kind; the function to `Fn`.
2886        assert_eq!(
2887            fs.nodes.iter().find(|n| n.name == "users").map(|n| &n.kind),
2888            Some(&NodeKind::Other("table".to_owned()))
2889        );
2890        // The function body invokes `total`, captured for resolution.
2891        let f = fs.nodes.iter().find(|n| n.name == "recent").unwrap();
2892        assert!(
2893            f.meta
2894                .get("calls")
2895                .and_then(|v| v.as_array())
2896                .is_some_and(|c| c.iter().any(|x| x.as_str() == Some("total"))),
2897            "invocation inside function captured in meta.calls"
2898        );
2899        assert_eq!(
2900            fs.nodes
2901                .iter()
2902                .find(|n| n.name == "users")
2903                .and_then(|n| n.lang.as_deref()),
2904            Some("sql")
2905        );
2906    }
2907
2908    #[test]
2909    fn ingest_prose_toggle_gates_embedded_content() {
2910        use super::IngestConfig;
2911
2912        let content = |ingest: IngestConfig| {
2913            Registry::new(ingest)
2914                .extract("notes.md", "b", b"# Title\n\nBody text.\n")
2915                .nodes[0]
2916                .meta
2917                .get("content")
2918                .and_then(|v| v.as_str())
2919                .map(str::to_owned)
2920        };
2921
2922        // Default (prose on) embeds the markdown body; disabling prose drops it.
2923        assert!(
2924            content(IngestConfig::default()).is_some_and(|c| c.contains("Body text")),
2925            "prose content embedded by default"
2926        );
2927        assert_eq!(
2928            content(IngestConfig {
2929                prose: false,
2930                ..IngestConfig::default()
2931            }),
2932            None,
2933            "disabling prose suppresses the embedded body"
2934        );
2935    }
2936
2937    #[test]
2938    fn env_tag_stable_by_default_and_shifts_when_gated() {
2939        use super::IngestConfig;
2940
2941        // All-on is the default: its tag must equal a plain `Registry` so existing
2942        // caches are untouched.
2943        let all_on = Registry::new(IngestConfig::default()).env_tag();
2944        assert_eq!(all_on, Registry::default().env_tag());
2945
2946        // Each disabled toggle changes the tag (forcing re-extraction), and
2947        // distinct disabled sets produce distinct tags.
2948        let no_prose = Registry::new(IngestConfig {
2949            prose: false,
2950            ..IngestConfig::default()
2951        })
2952        .env_tag();
2953        let no_pdf = Registry::new(IngestConfig {
2954            pdf: false,
2955            ..IngestConfig::default()
2956        })
2957        .env_tag();
2958        let no_ocr = Registry::new(IngestConfig {
2959            ocr: false,
2960            ..IngestConfig::default()
2961        })
2962        .env_tag();
2963        assert_ne!(no_prose, all_on);
2964        assert_ne!(no_pdf, all_on);
2965        assert_ne!(no_ocr, all_on);
2966        assert_ne!(no_prose, no_pdf);
2967        assert_ne!(no_ocr, no_prose);
2968        assert_ne!(no_ocr, no_pdf);
2969    }
2970
2971    /// The generation toggles must **not** move the extraction cache key.
2972    ///
2973    /// Before ADR-0015 they did, and correctly so: `audio = false` changed what
2974    /// went into `meta.content`. It no longer changes any derived fact, so
2975    /// folding it in would force every user of `[ingest] audio = false` — this
2976    /// repository among them — into a full, pointless re-extraction. This test is
2977    /// the difference between that being a decision and being an oversight.
2978    #[test]
2979    fn generation_toggles_do_not_move_the_extraction_cache_key() {
2980        use super::IngestConfig;
2981
2982        let all_on = Registry::default().env_tag();
2983        for (label, cfg) in [
2984            (
2985                "audio",
2986                IngestConfig {
2987                    audio: false,
2988                    ..IngestConfig::default()
2989                },
2990            ),
2991            (
2992                "vision",
2993                IngestConfig {
2994                    vision: false,
2995                    ..IngestConfig::default()
2996                },
2997            ),
2998            (
2999                "both",
3000                IngestConfig {
3001                    audio: false,
3002                    vision: false,
3003                    ..IngestConfig::default()
3004                },
3005            ),
3006        ] {
3007            assert_eq!(
3008                Registry::new(cfg).env_tag(),
3009                all_on,
3010                "`{label}` gates generation, not extraction, so it must not move the cache key",
3011            );
3012        }
3013    }
3014
3015    /// The two groups of toggle, stated as behaviour: `generates` answers for the
3016    /// generation pair and nothing else consults them.
3017    #[test]
3018    fn generation_toggles_gate_media_build() {
3019        use super::IngestConfig;
3020        use crate::media::MediaKind;
3021
3022        let all_on = IngestConfig::default();
3023        assert!(all_on.generates(MediaKind::Audio));
3024        assert!(all_on.generates(MediaKind::Vision));
3025
3026        let no_audio = IngestConfig {
3027            audio: false,
3028            ..IngestConfig::default()
3029        };
3030        assert!(!no_audio.generates(MediaKind::Audio));
3031        assert!(
3032            no_audio.generates(MediaKind::Vision),
3033            "each modality is gated independently"
3034        );
3035    }
3036}
3037
3038/// A tiny in-memory PNG for the media-engine tests, so they need no fixture file
3039/// on disk. A visible diagonal, so the model has *something* to describe.
3040#[cfg(all(test, feature = "image-vision"))]
3041fn tiny_png() -> Vec<u8> {
3042    let img = image::RgbImage::from_fn(32, 32, |x, y| {
3043        if x == y {
3044            image::Rgb([0, 0, 0])
3045        } else {
3046            image::Rgb([255, 255, 255])
3047        }
3048    });
3049    let mut png = std::io::Cursor::new(Vec::new());
3050    image::DynamicImage::ImageRgb8(img)
3051        .write_to(&mut png, image::ImageFormat::Png)
3052        .expect("encode png");
3053    png.into_inner()
3054}
3055
3056/// Serialises the tests that drive the process-wide media engines.
3057///
3058/// The engine slots and the llama.cpp backend beneath them are process globals,
3059/// and these tests both build and release them; the harness's default parallelism
3060/// would otherwise let one test's [`release_media_engines`] land in the middle of
3061/// another's engine lifetime, making both flaky. A poisoned lock only means an
3062/// earlier test panicked, so recover rather than cascade.
3063#[cfg(all(test, any(feature = "image-vision", feature = "audio-transcribe")))]
3064fn serialise_media_engine_test() -> std::sync::MutexGuard<'static, ()> {
3065    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
3066    LOCK.lock()
3067        .unwrap_or_else(std::sync::PoisonError::into_inner)
3068}
3069
3070/// Teardown cover for the real vision engine (issue #291), on a host that has
3071/// the model installed.
3072///
3073/// Compiled only under `image-vision` and **self-skipping** when
3074/// `smolvlm-500m-gguf` is not in the model store, so CI — Ubuntu, no GPU, no
3075/// models — compiles it and prints a skip rather than failing. On a machine that
3076/// *does* have the model there are two assertions:
3077///
3078/// 1. the explicit one below: after a real description, the cached engine is
3079///    released, exactly once;
3080/// 2. an implicit one that is the whole point of the fix — the **test binary's
3081///    own exit status**. This test loads a llama.cpp engine on the process's
3082///    default backend; if the engine were parked in a never-dropped `static`
3083///    again, this binary would abort in ggml-metal's exit-time teardown
3084///    (SIGABRT) after every test had "passed", exactly as `roteiro sync` did.
3085///
3086/// The mechanism itself — release-once, idempotent, safe when uninitialised — is
3087/// covered without any model or GPU in `rto_llama::slot`'s unit tests.
3088#[cfg(all(test, feature = "image-vision"))]
3089mod vision_engine_teardown {
3090    // The engines and the generation they serve moved to `crate::media::producers`
3091    // with ADR-0015; the *release* stayed in `extract`, which is what `main` holds
3092    // for the process. So this test imports from both, and that split is the thing
3093    // it is guarding.
3094    use super::{release_media_engines, serialise_media_engine_test, tiny_png};
3095    use crate::media::producers::{VLM_MODEL, vlm_content};
3096
3097    #[test]
3098    fn describing_an_image_leaves_a_releasable_engine() {
3099        let _serial = serialise_media_engine_test();
3100        let dir = crate::models::model_dir(VLM_MODEL);
3101        if !dir.join("model.gguf").exists() || !dir.join("mmproj.gguf").exists() {
3102            eprintln!("SKIP: `{VLM_MODEL}` not installed (run `roteiro model pull {VLM_MODEL}`)");
3103            return;
3104        }
3105
3106        // The production path: this is what a `sync` does for every image blob.
3107        // Whether the model finds words for a 32×32 diagonal is not the subject —
3108        // that it loaded, and can now be torn down, is.
3109        let _description = vlm_content(&tiny_png());
3110
3111        assert!(
3112            release_media_engines(),
3113            "the engine `vlm_content` cached must be released, not leaked to exit"
3114        );
3115        assert!(
3116            !release_media_engines(),
3117            "releasing again must be a no-op, so every exit path can call it"
3118        );
3119    }
3120}
3121
3122/// Both modalities in one process (issue #296), on a host that has both models.
3123///
3124/// This is the case the shared backend exists for, and the one that could not be
3125/// written before it: `LlamaBackend::init()` was per-engine, so whichever engine
3126/// a run built second got `BackendAlreadyInitialized`, `.ok()` turned that into
3127/// `None`, and the second modality was quietly missing. The first assertion below
3128/// is that *both* engines now exist.
3129///
3130/// Compiled only when both media features are on, and **self-skipping** when
3131/// either GGUF is absent, so CI — Ubuntu, no GPU, no models — compiles it and
3132/// prints a skip. On a host that has them, three things are checked:
3133///
3134/// 1. both engines build in one process, and are the same backend's;
3135/// 2. both actually run — the vision engine describes a generated PNG and the
3136///    audio engine transcribes a committed WAV fixture, so the audio path is
3137///    exercised end to end (the coverage gap #292 could not close);
3138/// 3. that each modality loads **its own** projector, exactly once (issue #301).
3139///    Two blobs per modality leave each engine at one projector initialisation,
3140///    and the two projectors are separate objects: a cache that ignored *which*
3141///    projector was being asked for would hand the audio engine the vision one,
3142///    whose `support_audio` is false — the failure mode #298 makes possible by
3143///    letting both modalities be live at the same time;
3144/// 4. the **test binary's own exit status**, which is the sharpest guard of all:
3145///    two engines' models — and now their cached projectors — are resident on one
3146///    backend, and if the backend were freed before them, or any of them leaked
3147///    to `exit()`, this binary would abort in ggml-metal's teardown (SIGABRT,
3148///    exit 134) *after* every test had "passed", exactly as `roteiro sync` did in
3149///    #291.
3150#[cfg(all(test, feature = "image-vision", feature = "audio-transcribe"))]
3151mod two_modality_teardown {
3152    use super::{release_media_engines, serialise_media_engine_test, tiny_png};
3153    use crate::media::producers::{
3154        ASR_MODEL, VLM_MODEL, asr_content, asr_engine, vlm_content, vlm_engine,
3155    };
3156
3157    /// Half a second of 16-bit mono 16 kHz PCM in a WAV container: the committed
3158    /// `syllables` fixture, embedded at compile time.
3159    ///
3160    /// This test used to synthesise its own WAV here, which made the workspace
3161    /// carry two hand-written RIFF writers (#302). The other one — in
3162    /// `tests/audio_fixtures.rs` — is the one worth keeping: it is a reusable
3163    /// `encode(rate, samples)` rather than one hardcoded clip, it sits alongside
3164    /// the FLAC and MP3 writers, and it is integer-exact end to end (a Q15 sine
3165    /// table, no `f64::sin` and no `as i16`), so it needs no
3166    /// `cast_possible_truncation` suppression where the generator here did.
3167    ///
3168    /// It cannot simply be *called* from here, though — and a shared helper in
3169    /// `src/` could not be called from there either. Both directions are
3170    /// blocked, for *different* reasons:
3171    ///
3172    /// * `src/` → `tests/`: each file under `tests/` is compiled as its own
3173    ///   crate, which links the library. The library cannot depend on them; they
3174    ///   depend on it. `cfg(test)` has nothing to do with this direction.
3175    /// * `tests/` → `src/`: the library is rebuilt *without* `--cfg test` when
3176    ///   an integration-test crate links it, so a `#[cfg(test)]` helper in
3177    ///   `src/` is simply absent from the artefact those crates see.
3178    ///
3179    /// So what crosses the boundary is the encoder's *output*, not its source:
3180    /// the bytes it already commits under `tests/fixtures/audio/`, whose
3181    /// reproducibility `fixtures_are_byte_reproducible` gates on every run. This
3182    /// test reads the artefact instead of re-implementing the tool, and the
3183    /// workspace is left with exactly one WAV encoder.
3184    ///
3185    /// `include_bytes!` rather than `std::fs::read`, so a renamed or deleted
3186    /// fixture is a build error rather than a panic inside a test whose subject
3187    /// is engine teardown.
3188    ///
3189    /// `syllables` and not `silence` for the reason the old generator picked a
3190    /// tone over silence — near-silence makes an ASR model hallucinate — and over
3191    /// the tone because it is speech-*shaped* (four voiced bursts under a
3192    /// trapezoidal envelope), which is a fairer exercise of decode + projection.
3193    /// It is also the fixture `audio_ingest.rs` already drives through the real
3194    /// projector, so it is known to decode. The point is still to reach the
3195    /// model, not to assert on its words.
3196    /// `pub(super)` so the sibling `projector_binding` test drives the same clip
3197    /// rather than reaching for a second fixture — one committed WAV, read by
3198    /// everything that needs one (#302).
3199    pub(super) const TINY_WAV: &[u8] =
3200        include_bytes!("../tests/fixtures/audio/syllables-16khz-mono-512ms.wav");
3201
3202    /// Whether `name`'s GGUF pair is in the model store.
3203    fn installed(name: &str) -> bool {
3204        let dir = crate::models::model_dir(name);
3205        dir.join("model.gguf").exists() && dir.join("mmproj.gguf").exists()
3206    }
3207
3208    #[test]
3209    fn both_modalities_get_a_working_engine_in_one_process() {
3210        let _serial = serialise_media_engine_test();
3211        if !installed(VLM_MODEL) || !installed(ASR_MODEL) {
3212            eprintln!(
3213                "SKIP: need both `{VLM_MODEL}` and `{ASR_MODEL}` installed \
3214                 (run `roteiro model pull <name>`)"
3215            );
3216            return;
3217        }
3218
3219        // (1) Construction, which is where #296 bit. Order is deliberate: the
3220        // audio engine is the *second* one built, so it is the one that used to
3221        // come back `None`.
3222        assert!(vlm_engine().is_some(), "the vision engine must build");
3223        assert!(
3224            asr_engine().is_some(),
3225            "the second engine must share the first's backend, not be inert (#296)"
3226        );
3227
3228        // (2) Both actually infer. What the models make of a diagonal and four
3229        // voiced bursts is not the subject — that each loaded a model on the
3230        // shared backend and produced a completion is. `*_content` returns `None`
3231        // on a blank result, so this asserts on reaching the model, not on its
3232        // words. Two blobs per modality, because one could not tell a cached
3233        // projector from a rebuilt one.
3234        let png = tiny_png();
3235        let _description = vlm_content(&png);
3236        let _transcript = asr_content(TINY_WAV);
3237        let _description_again = vlm_content(&png);
3238        let _transcript_again = asr_content(TINY_WAV);
3239
3240        // (3) Each modality loaded its own projector, once (#301). Before the
3241        // cache these counts would have been 2 and 2; with a cache that was not
3242        // keyed per projector, the second modality would have been handed the
3243        // first's context and produced nothing at all.
3244        let (vision, audio) = (
3245            vlm_engine().expect("resident").projector_inits(),
3246            asr_engine().expect("resident").projector_inits(),
3247        );
3248        assert_eq!(vision, 1, "two images must load the vision projector once");
3249        assert_eq!(audio, 1, "two clips must load the audio projector once");
3250
3251        // (4) Teardown, in the order llama.cpp requires: both engines, then the
3252        // backend they shared. `release_media_engines` does that, and nothing
3253        // here could have got it wrong — while either engine were alive, the
3254        // backend release would simply have declined.
3255        assert!(
3256            release_media_engines(),
3257            "two engines and a backend must all be released, not leaked to exit"
3258        );
3259        assert!(
3260            !release_media_engines(),
3261            "releasing again must be a no-op, so every exit path can call it"
3262        );
3263    }
3264}
3265
3266/// A cached projector never outlives the model it is bound to (issue #301).
3267///
3268/// This is the hazard caching an `mtmd_context` introduces, and the reason the
3269/// cache is keyed by the model as well as by the `mmproj`: `mtmd_init_from_file`
3270/// keeps the `llama_model *` it was handed and dereferences it on every
3271/// `tokenize`/`eval_chunks`. Models are not permanent — the residency cache
3272/// evicts them — so a projector that survived its model would be a dangling
3273/// pointer waiting for the next blob.
3274///
3275/// The test drives that eviction deliberately: one engine, both models, and the
3276/// default budget, which keeps exactly **one** model resident. Alternating
3277/// modalities therefore unloads and reloads, and the projector count is what
3278/// distinguishes the two designs — a cache keyed on the `mmproj` path alone would
3279/// hand the third call the first call's projector, pointing at freed memory.
3280///
3281/// Self-skipping when either GGUF is absent, like its neighbours, and it uses the
3282/// fixtures they already commit rather than generating new ones. Its own exit
3283/// status is an assertion too: it builds projectors over a model that is then
3284/// freed, which is precisely the sequence that would abort at `exit()` if a
3285/// projector were left behind.
3286#[cfg(all(test, feature = "image-vision", feature = "audio-transcribe"))]
3287mod projector_binding {
3288    use super::two_modality_teardown::TINY_WAV;
3289    use super::{release_media_engines, serialise_media_engine_test, tiny_png};
3290    use crate::media::producers::{ASR_MODEL, VLM_MODEL};
3291    use rto_llama::llama::{LlamaEngine, Served};
3292    use rto_llama::{ChatRequest, Engine, Message};
3293
3294    /// `name`'s installed GGUF pair, or `None` when it is not in the model store.
3295    fn served(name: &str) -> Option<Served> {
3296        let dir = crate::models::model_dir(name);
3297        let (gguf, mmproj) = (dir.join("model.gguf"), dir.join("mmproj.gguf"));
3298        (gguf.exists() && mmproj.exists()).then(|| Served {
3299            name: name.to_owned(),
3300            path: gguf,
3301            mmproj: Some(mmproj),
3302        })
3303    }
3304
3305    /// One media request through `engine`, returning the completion text.
3306    fn media_chat(
3307        engine: &LlamaEngine,
3308        model: &str,
3309        images: Vec<Vec<u8>>,
3310        audio: Vec<Vec<u8>>,
3311    ) -> String {
3312        engine
3313            .chat(&ChatRequest {
3314                model: model.to_owned(),
3315                messages: vec![Message {
3316                    role: "user".to_owned(),
3317                    content: "Describe what you perceive in one short sentence.".to_owned(),
3318                }],
3319                images,
3320                audio,
3321                temperature: 0.0,
3322                max_tokens: 32,
3323            })
3324            .expect("the blob reaches its projector and completes")
3325            .content
3326    }
3327
3328    #[test]
3329    fn evicting_a_model_rebuilds_its_projector_rather_than_reusing_a_stale_one() {
3330        let _serial = serialise_media_engine_test();
3331        let (Some(vlm), Some(asr)) = (served(VLM_MODEL), served(ASR_MODEL)) else {
3332            eprintln!(
3333                "SKIP: need both `{VLM_MODEL}` and `{ASR_MODEL}` installed \
3334                 (run `roteiro model pull <name>`)"
3335            );
3336            return;
3337        };
3338
3339        // Budget 0: one model resident, so each switch of modality evicts the
3340        // other — and takes its projector with it.
3341        let engine = LlamaEngine::new(vec![vlm, asr], 0).expect("engine builds");
3342
3343        let first = media_chat(&engine, ASR_MODEL, Vec::new(), vec![TINY_WAV.to_vec()]);
3344        assert_eq!(engine.projector_inits(), 1, "the audio projector loaded");
3345
3346        let described = media_chat(&engine, VLM_MODEL, vec![tiny_png()], Vec::new());
3347        assert!(
3348            !described.trim().is_empty(),
3349            "a second, different projector must work in the same process (#298)"
3350        );
3351        assert_eq!(
3352            engine.projector_inits(),
3353            2,
3354            "a different mmproj is a different projector — never the first one reused"
3355        );
3356
3357        // The audio model was evicted by the image; asking for it again reloads it
3358        // at a new address, so its projector must be rebuilt against *that* model.
3359        let again = media_chat(&engine, ASR_MODEL, Vec::new(), vec![TINY_WAV.to_vec()]);
3360        assert_eq!(
3361            engine.projector_inits(),
3362            3,
3363            "a reloaded model gets a freshly bound projector, not the evicted model's"
3364        );
3365        assert_eq!(
3366            first, again,
3367            "and the rebuilt projector produces exactly what the original did"
3368        );
3369
3370        // Engine first (its models and their projectors), backend last.
3371        drop(engine);
3372        assert!(
3373            release_media_engines(),
3374            "the backend is releasable once the engine holding it is gone"
3375        );
3376    }
3377}